@adhdev/daemon-standalone 0.9.26 → 0.9.27

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.
@@ -28,7 +28,7 @@ var td=Object.defineProperty;var sd=(e,t,r)=>t in e?td(e,t,{enumerable:!0,config
28
28
 
29
29
  `)))return}const Y=(c==null?void 0:c[L.id])??p[L.id];try{const O=await w(L.invokeScript),D=pr(O);if(D&&!D.ok||hr(O))throw new Error((D==null?void 0:D.error)||Ps(O)||`Could not run ${L.label}`);D&&g(L,Y??!0,D)}catch(O){E(L,Y);const D=O instanceof Error?O.message:`Could not run ${L.label}`;lt.showToast(D,"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:`${f}33`,background:`${f}12`,color:f},children:a}),M.map(L=>{const Y=String(h[L.id]||""),O=im(L,j,Y),D=N===L.id,W=y===L.id,Q=Tr(L,j),be="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(L.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${be} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:D?`${f}55`:"var(--border-default)",background:D?`${f}10`:"var(--surface-tertiary)",color:Y?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void C(L),title:L.label,children:[L.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:W?"Loading…":O||L.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),D&&Q.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>A(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:L.label}),Q.map(pe=>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:pe.value===Y?`${f}14`:"transparent",color:pe.value===Y?"var(--text-primary)":"var(--text-secondary)",borderLeft:pe.value===Y?`2px solid ${f}`:"2px solid transparent"},title:pe.description||pe.label,onMouseEnter:ue=>{ue.currentTarget.style.background=`${f}10`},onMouseLeave:ue=>{ue.currentTarget.style.background=pe.value===Y?`${f}14`:"transparent"},onClick:()=>void R(L,pe.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:pe.label}),pe.value===Y&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:f},children:"✓"})]},pe.value))]})]})]},L.id);case"cycle":return s.jsxs("button",{type:"button",className:`${be} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:Y?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void K(L),title:`Click to cycle: ${Q.map(pe=>pe.label).join(" → ")}`,children:[L.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:O||L.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},L.id);case"toggle":return s.jsxs("button",{type:"button",className:`${be} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:Y?`${f}44`:"var(--border-default)",background:Y?`${f}14`:"var(--surface-tertiary)",color:Y?f:"var(--text-muted)"},onClick:()=>void z(L),"aria-pressed":!!Y,children:[L.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),L.label]},L.id);case"action":return s.jsxs("button",{type:"button",className:`${be} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void T(L),children:[L.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:L.resultDisplay==="inline"&&Y?`${L.label}: ${Y}`:L.label})]},L.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:Y?"var(--text-primary)":"var(--text-muted)"},children:[L.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:Y?`${L.label}: ${Y}`:L.label})]},L.id);default:return null}})]})})}function dm({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:d}){const{isVisible:f}=Ui(),u=ka(l,{hostIdeType:a,providerType:i});return!e||t||u.length===0||!f?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx(lm,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:u,controlValues:d})})}function um({hasDraft:e,isBusy:t=!1}){return!e||t}const Qi=o.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:i=null,onSend:c,isActive:l=!0,showControlsToggle:d=!1,animateVisibility:f=!0}){const u=o.useRef(null),[x,m]=o.useState(""),{isVisible:v,toggleVisibility:S}=Ui();o.useEffect(()=>{m("")},[t]),o.useEffect(()=>{var h;l&&((h=u.current)==null||h.focus({preventScroll:!0}))},[t,l]);const p=async()=>{const h=x.trim();if(!h||a)return;await c(h)!==!1&&m("")};return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",f?"transition-all duration-200 ease-out":""].filter(Boolean).join(" "),style:{borderTop:l?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:l?72:0,opacity:l?1:0,transform:l?"translateY(0)":"translateY(10px)",padding:l?"10px 12px":"0 12px",pointerEvents:l?"auto":"none"},"aria-hidden":!l,children:[s.jsxs("div",{className:"flex gap-2 items-center",title:l?`Send message to ${r}`:void 0,children:[d&&s.jsx("button",{type:"button",onClick:S,"aria-label":v?"Hide controls":"Show controls","aria-pressed":v,title:v?"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"})]})}),s.jsx("div",{className:"flex-1 relative",children:s.jsx("input",{ref:u,type:"text",placeholder:i||`Send message to ${r}...`,value:x,onChange:h=>m(h.target.value),onPaste:h=>{const j=h.clipboardData.getData("text");j&&m(b=>b+j),h.preventDefault()},onKeyDown:h=>{if(h.key==="Enter"){if(h.nativeEvent.isComposing){h.preventDefault();return}h.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:um({hasDraft:!!x.trim(),isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${x.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:x.trim()&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,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:x.trim()?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),i&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),Ze=e=>e.transport==="pty",Ls=(e,t)=>Ze(e)?e.mode||"terminal":"chat",Zi=(e,t)=>Ze(e)&&Ls(e)==="terminal",Xe=e=>e.transport==="acp";function Vt(e){return e.streamSource!=="agent-stream"}function fs(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function ec(e){return e.machineName||""}function Rs(e){return fs(e)}function Kt(e){return e.agentType||""}function Hr(e){return e.hostIdeType||""}function Sa(e){return e.displayPrimary||e.agentName||"Agent"}function tc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function mm(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function No(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 fm(e){return No(e==null?void 0:e.receivedAt)||No(e==null?void 0:e.timestamp)||0}function sc(e){const t=mm(e),r=Ss(t==null?void 0:t.content),n=fm(t),a=Ss(e.lastMessagePreview),i=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0;return a&&!r?a:r&&!a?r:a&&r&&i>0&&n>0&&i>n?a:r||a||""}function pm(e){return sc(e)||e.displaySecondary||""}function rc(e){return[e.displaySecondary,ec(e)].filter(Boolean)}function Cs(e){return e.agentName||st(Kt(e))}function hm(e){var t,r;if(!Vt(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return st(Hr(e)||Kt(e))}function nc(e){return Vt(e)?e.sessionId:e.nativeSessionId}function Co(e){return Vt(e)?"native":e.tabKey}function xm(e){return e.sessionId}function bm(e,t){if(t)return Vt(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function gm(e,t){const r=Kt(e),n=Vt(e),a=Ze(e)||Xe(e),i=n?a?Cs(e)||(t==null?void 0:t.cliName)||st(Hr(e)||r):t!=null&&t.type?st(t.type):st(Hr(e)||r):Cs(e);return{isNativeConversation:n,isCli:Ze(e),isAcp:Xe(e),isCliTerminal:Zi(e),providerType:r,displayLabel:i,targetEntry:bm(e,t)}}function gt(e){return(typeof e=="string"?e.trim():"")||void 0}function Ft(e,t){const r=gt(t);return r?`${e}:${r}`:void 0}function zt(e,t,r){const n=Ft(t,r),a=gt(r);n&&e.push(n),a&&e.push(a)}function gs(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function ac(e){return gt(e.providerSessionId)||gt(e.sessionId)||gt(e.tabKey)||gt(e.routeId)}function Na(e){return gs([gt(e.providerSessionId),gt(e.sessionId)])}function ws(e){const t=[];return zt(t,"provider",e.providerSessionId),zt(t,"session",e.sessionId),zt(t,"tab",e.tabKey),zt(t,"route",e.routeId),gs(t)}function ym(e){const t=[];return gt(e.providerSessionId)?(zt(t,"provider",e.providerSessionId),gs(t)):gt(e.sessionId)?(zt(t,"session",e.sessionId),gs(t)):gt(e.tabKey)?(zt(t,"tab",e.tabKey),gs(t)):gt(e.routeId)?(zt(t,"route",e.routeId),gs(t)):[]}function Ca(e){return Ft("provider",e.providerSessionId)||Ft("session",e.sessionId)||Ft("tab",e.tabKey)||Ft("route",e.routeId)||"unknown:"}function nr(e){return Na(e)[0]}function vm(e){const t=gt(e.providerSessionId),r=gt(e.sessionId),n=gt(e.tabKey),a=gt(e.routeId),i=[Ft("provider",t),Ft("session",r),Ft("tab",n),Ft("route",a)].filter(d=>typeof d=="string"),c=ws({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),l=Ca({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:ac({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:nr({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function Zn(e,t){const r=vm(e);return ym(t).some(n=>r.lookupKeys.includes(n))}function Io(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 es(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=Io(t==null?void 0:t.receivedAt)||Io(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function ea(e,t=0){return es(e)||e.lastUpdated||t||0}function oc(e){return es(e)||e.lastUpdated||0}function ic(e,t,r=oc){const n=r(t)-r(e);if(n!==0)return n;const a=(e.machineName||"").localeCompare(t.machineName||"");if(a!==0)return a;const i=e.displayPrimary.localeCompare(t.displayPrimary);if(i!==0)return i;const c=e.displaySecondary.localeCompare(t.displaySecondary);return c!==0?c:e.tabKey.localeCompare(t.tabKey)}function ta(e){var r;const t=bt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function wm(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!ta(e)&&!e.title.trim()}function jm(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(ta(r))-Number(ta(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:ic(t,r)})[0]||null}function _t(e,t){const r=e.filter(c=>c.routeId===t);if(r.length===0)return null;const n=r.find(c=>c.streamSource==="native")||null,a=r.filter(c=>c.streamSource==="agent-stream"),i=jm(a);return n?i&&wm(n)?i:n:i||r[0]||null}function Gt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Ia(e){return nr(e)||e.tabKey||e.routeId||null}function cc(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"";if(t)return t;const r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"";if(r)return r;const n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"";if(!n)return null;const a=_t(e.conversations,n)||e.conversations.find(i=>i.routeId===n);return a?Ia(a):null}function lc({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=As(),c=fs(e),l=ec(e),d=e.transport==="cdp-page"||e.transport==="cdp-webview",f=e.streamSource==="agent-stream"&&!!e.agentName,u=!f&&(e.transport==="pty"||e.transport==="acp"),x=Cs(e),m=hm(e),v=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),S=o.useCallback(()=>{if(r){r();return}const p=Ia(e);p&&i(Gt(p))},[e,i,r]);return s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[d&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:S,title:m,children:[s.jsx(Nt,{size:12}),s.jsx("span",{children:m})]}):s.jsxs("span",{className:"conversation-meta-chip",title:m,children:[s.jsx(Nt,{size:12}),s.jsx("span",{children:m})]})),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[s.jsx(Js,{size:12}),s.jsx("span",{children:x})]}),u&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[s.jsx(Js,{size:12}),s.jsx("span",{children:x})]}),l&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:v,title:l,children:[s.jsx(ls,{size:12}),s.jsx("span",{children:l})]}):s.jsxs("span",{className:"conversation-meta-chip",title:l,children:[s.jsx(ls,{size:12}),s.jsx("span",{children:l})]}))]})}function xn(e,t){return`${e}:${t}`}function km(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function _s(e,t){km()&&console.debug(`[subscription-manager] ${e}`,t)}class Sm{constructor(){Ge(this,"active",new Map);Ge(this,"retryTimers",new Map)}subscribe(t,r,n,a,i){var u;const c=xn(n.topic,n.key),l=this.active.get(c);let d=!0;if(l)l.handlers.add(a),l.lastUpdate&&a(l.lastUpdate);else{const x={daemonId:r,request:n,handlers:new Set([a])};this.active.set(c,x),_s("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((u=t.sendData)==null?void 0:u.call(t,r,n))??!1,!d&&(i!=null&&i.retryIntervalMs)&&this.scheduleRetry(c,t,i.retryIntervalMs)}const f=()=>{var v;this.clearRetry(c);const x=this.active.get(c);if(!x||(x.handlers.delete(a),x.handlers.size>0))return;this.active.delete(c);const m={type:"unsubscribe",topic:n.topic,key:n.key};_s("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(v=t.sendData)==null||v.call(t,r,m)};return f.initialSendAccepted=d,f}publish(t){const r=xn(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,ks.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),ks.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=xn(t,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(t){var r;_s("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(i=>i.daemonId===t);_s("resubscribe_daemon",{daemonId:t,count:n.length,subscriptions:n.map(i=>({topic:i.request.topic,key:i.request.key}))});for(const i of n)(a=r.sendData)==null||a.call(r,i.daemonId,i.request)}scheduleRetry(t,r,n){if(this.retryTimers.has(t))return;const a=setTimeout(()=>{var l;this.retryTimers.delete(t);const i=this.active.get(t);if(!i)return;const c=((l=r.sendData)==null?void 0:l.call(r,i.daemonId,i.request))??!1;_s("subscribe_retry",{id:t,accepted:c,topic:i.request.topic,key:i.request.key}),c||this.scheduleRetry(t,r,n)},n);this.retryTimers.set(t,a)}clearRetry(t){const r=this.retryTimers.get(t);r!==void 0&&(clearTimeout(r),this.retryTimers.delete(t))}}const qt=new Sm;function Nm(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});for(const i of n.childSessions||[]){if(!(i!=null&&i.id))continue;const c=r.get(i.id)||{};r.set(i.id,{...c,...i})}}return r}function Cm(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 Fr(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:i,timestamp:c}=t,l=c||e.timestamp||Date.now(),d=e.sessions||[],{topLevel:f,childrenByParent:u}=Cm(d),x=Nm(i,n),m=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,v=f.filter(h=>h.kind==="workspace"&&h.transport==="cdp-page"),S=f.filter(h=>h.kind==="agent"&&h.transport==="pty"),p=f.filter(h=>h.kind==="agent"&&h.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...m&&{machine:m,platform:m.platform},...e.instanceId&&{instanceId:e.instanceId},...e.machineNickname!==void 0&&{machineNickname:e.machineNickname},...e.p2p&&{p2p:e.p2p},...e.workspaces&&{workspaces:e.workspaces},...e.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:e.defaultWorkspaceId},...e.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:e.defaultWorkspacePath},...e.terminalSizingMode!==void 0&&{terminalSizingMode:e.terminalSizingMode},...e.recentLaunches&&{recentLaunches:e.recentLaunches},...e.terminalBackend&&{terminalBackend:e.terminalBackend},...e.detectedIdes&&{detectedIdes:e.detectedIdes},...e.availableProviders&&{availableProviders:e.availableProviders},cdpConnected:v.some(h=>!!h.cdpConnected)});for(const h of v){const j=x.get(h.id),b=Ws(h,j),N=(u.get(h.id)||[]).map(A=>Ws(A,x.get(A.id)));r.push({id:`${n}:ide:${h.id}`,sessionId:h.id,providerSessionId:h.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,status:b.cdpConnected?"online":"detected",daemonId:n,instanceId:h.id,workspace:b.workspace,terminals:0,childSessions:N,agents:N.map(A=>({id:A.id,name:A.providerName||A.providerType,type:A.providerType,status:A.status})),activeChat:b.activeChat,chats:[],cdpConnected:b.cdpConnected,...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l})}for(const h of S){const j=x.get(h.id),b=Ws(h,j);r.push({id:`${n}:cli:${h.id}`,sessionId:h.id,providerSessionId:h.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,agentType:b.providerType,status:b.status||"running",daemonId:n,instanceId:h.id,cliName:b.providerName||b.providerType,mode:b.mode||(j==null?void 0:j.mode)||"terminal",workspace:b.workspace||"",activeChat:b.activeChat,...b.resume!==void 0&&{resume:b.resume},...b.runtimeKey!==void 0&&{runtimeKey:b.runtimeKey},...b.runtimeDisplayName!==void 0&&{runtimeDisplayName:b.runtimeDisplayName},...b.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:b.runtimeWorkspaceLabel},...b.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:b.runtimeWriteOwner},...b.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:b.runtimeAttachedClients},...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l,_isCli:!0})}for(const h of p){const j=x.get(h.id),b=Ws(h,j);r.push({id:`${n}:acp:${h.id}`,sessionId:h.id,providerSessionId:h.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,agentType:b.providerType,status:b.status||"running",daemonId:n,instanceId:h.id,cliName:b.providerName||b.providerType,mode:"chat",workspace:b.workspace||"",activeChat:b.activeChat,...b.runtimeKey!==void 0&&{runtimeKey:b.runtimeKey},...b.runtimeDisplayName!==void 0&&{runtimeDisplayName:b.runtimeDisplayName},...b.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:b.runtimeWorkspaceLabel},...b.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:b.runtimeWriteOwner},...b.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:b.runtimeAttachedClients},...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l,_isAcp:!0})}return r}const Im=15e3,Mm=15e3,Am=6e4,Tm=1200,Mo=12,Lm=8e3,Rm=4e3,bn=new Map,gn=new Map,xr=new Set,Us=new Map;function Pm(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 Ao(e,t){const r=Us.get(e);!r||r.size===0||(Us.delete(e),r.forEach(n=>n(t)))}function _m(e,t){return new Promise(r=>{const n=Us.get(e)||new Set;Us.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&Us.delete(e),r(c)},i=setTimeout(()=>a(!1),t);n.add(a)})}function ar(){const{sendCommand:e,sendData:t}=wt(),{injectEntries:r,getIdes:n}=Ys();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??Am,l=gn.get(a)||0;if(!(i!=null&&i.force)&&xr.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const d=bn.get(a);if(d)return d;const f=(async()=>{if(t&&!xr.has(a)){const p=qt.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},h=>{const j=n(),b=j.find(A=>A.id===a),N=Fr(h.status,{daemonId:a,existingDaemon:b,existingEntries:j,timestamp:h.timestamp});N.length>0&&r(N),gn.set(a,Date.now()),Ao(a,!0)});if(p.initialSendAccepted?xr.add(a):xr.delete(a),!(i!=null&&i.force)&&p.initialSendAccepted&&await _m(a,Tm))return}const u=await e(a,"get_status_metadata"),x=Pm(u);if(!x)return;const m=n(),v=m.find(p=>p.id===a),S=Fr(x,{daemonId:a,existingDaemon:v,existingEntries:m,timestamp:x.timestamp||Date.now()});S.length>0&&r(S,{authoritativeDaemonIds:[a]}),gn.set(a,Date.now()),Ao(a,!0)})().finally(()=>{bn.delete(a)});return bn.set(a,f),f},[n,r,e,t])}function Ma(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}function js(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:Ze(e)||Xe(e)?{agentType:Kt(e)}:e.streamSource==="agent-stream"?{agentType:Kt(e)}:t}function Zs(e){return e?Rs(e):""}function Ds(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function Aa(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function Dm(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."}const Em=60,$m=1e3;function dc(e={}){return e.isCliLike?$m:Em}function Bm(e={}){return dc(e)}const or=60,Km=1e3,Ta=12e4,Om=new Set(["generating","waiting_approval","starting","streaming","working"]),To=new Map;function La(e,t){return`${e}::${t}`}function sa(e=or){return{liveMessages:[],cursor:uc([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function ra(e){return Mi(e)}function uc(e,t=or){return{knownMessageCount:e.length,lastMessageSignature:ra(e[e.length-1]),tailLimit:t}}function br(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("|")}function Wm(e,t){const r=Array.isArray(t.messages)?t.messages:[];switch(t.syncMode){case"noop":return e;case"append":return[...e,...r];case"replace_tail":{const n=Math.max(0,Math.min(Number(t.replaceFrom??e.length),e.length));return[...e.slice(0,n),...r]}case"full":return r;default:return r}}class Hm{constructor(t){Ge(this,"manager");Ge(this,"sendData");Ge(this,"daemonId");Ge(this,"sessionId");Ge(this,"historySessionId");Ge(this,"subscriptionKey");Ge(this,"snapshot");Ge(this,"transportSubscription",null);Ge(this,"listeners",new Set);Ge(this,"retainCount",0);Ge(this,"loadHistoryPromise",null);Ge(this,"pendingDisconnectTimer",null);this.manager=t.manager||qt,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.snapshot=sa(Math.max(0,t.tailLimit??or))}updateOptions(t){if(t.manager&&(this.manager=t.manager),t.sendData&&(this.sendData=t.sendData),t.historySessionId&&(this.historySessionId=t.historySessionId),t.tailLimit!==void 0){const r=Math.max(0,t.tailLimit);if(r!==this.snapshot.cursor.tailLimit){const n=Math.min(this.snapshot.cursor.knownMessageCount,this.snapshot.liveMessages.length);this.snapshot={...this.snapshot,cursor:{...this.snapshot.cursor,knownMessageCount:n,tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect())}}}getSnapshot(){return this.snapshot}hydrateLiveMessages(t){const r=Array.isArray(t)?t:[];if(r.length===0)return;const n=r,a=uc(n,this.snapshot.cursor.tailLimit);br(this.snapshot.liveMessages)===br(n)&&this.snapshot.cursor.knownMessageCount===a.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===a.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:n,cursor:a},this.emit())}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=await t(),a=Array.isArray(n.messages)?n.messages:[];this.snapshot={...this.snapshot,historyMessages:[...a,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+a.length,hasMoreHistory:n.hasMore===!0,historyError:null}}catch(n){this.snapshot={...this.snapshot,historyError:n instanceof Error?n.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=r,r}buildSubscribeRequest(){return{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},knownMessageCount:this.snapshot.cursor.knownMessageCount,lastMessageSignature:this.snapshot.cursor.lastMessageSignature,...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{}}}}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:Km}))}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=typeof t.lastMessageSignature=="string"?t.lastMessageSignature:"",n=ra(this.snapshot.liveMessages[this.snapshot.liveMessages.length-1]);if(t.syncMode!=="full"&&r&&n===r){const d={knownMessageCount:Math.max(this.snapshot.cursor.knownMessageCount,Number(t.totalMessages||0)),lastMessageSignature:r,tailLimit:this.snapshot.cursor.tailLimit};this.snapshot.cursor.knownMessageCount===d.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===d.lastMessageSignature||(this.snapshot={...this.snapshot,cursor:d},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:d.knownMessageCount,lastMessageSignature:d.lastMessageSignature}));return}const a=Wm(this.snapshot.liveMessages,t),i={knownMessageCount:a.length,lastMessageSignature:typeof t.lastMessageSignature=="string"?t.lastMessageSignature:ra(a[a.length-1]),tailLimit:this.snapshot.cursor.tailLimit};br(this.snapshot.liveMessages)===br(a)&&this.snapshot.cursor.knownMessageCount===i.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===i.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:a,cursor:i},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:i.knownMessageCount,lastMessageSignature:i.lastMessageSignature}),this.emit())}}function mc(e){const t=La(e.daemonId,e.sessionId),r=To.get(t);if(r)return r.updateOptions(e),r;const n=new Hm(e);return To.set(t,n),n}function Fm(e,t){return{...e,loadHistoryPage:t}}function Um(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function zm(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(Om.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??Ta)),i=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return i>0?n-i<=a:Array.isArray(e.messages)&&e.messages.length>0}function Vm(e=Ta){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Gm(e,t={}){const r=new Set,n=[];for(const a of e){if(!zm(a,t))continue;const i=Rs(a),c=a.sessionId||"";if(!i||!c)continue;const l=La(i,c);if(r.has(l))continue;r.add(l);const d=nr(a);n.push({daemonId:i,sessionId:c,historySessionId:d||c,subscriptionKey:`daemon:${i}:session:${c}`})}return n.sort(Um),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function qm(e,t){const{sendData:r,sendCommand:n}=wt(),a=(t==null?void 0:t.enabled)!==!1,i=Rs(e),c=e.sessionId||"",l=nr(e)||c,d=`daemon:${i}:session:${c}`,f=Math.max(0,(t==null?void 0:t.tailLimit)??or),u=o.useMemo(()=>!a||!i||!c?null:mc({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:d,sendData:r,tailLimit:f}),[i,a,l,r,c,d,f]),[x,m]=o.useState(()=>(u==null?void 0:u.getSnapshot())||sa(f));o.useEffect(()=>{if(!u){m(sa(f));return}u.retain(),m(u.getSnapshot());const S=u.subscribe(p=>{m(p)});return()=>{S(),u.release()}},[u,f]),o.useEffect(()=>{u&&(u.hydrateLiveMessages(e.messages),m(u.getSnapshot()))},[e.messages,u]);const v=o.useCallback(async()=>{!u||!i||!c||await u.loadHistoryPage(async()=>{const S=e.agentType,p=await n(i,"chat_history",{agentType:S,offset:u.getSnapshot().historyOffset,limit:30,targetSessionId:c,historySessionId:l}),h=p&&typeof p=="object"&&"result"in p?p.result||{}:p||{};return{messages:Array.isArray(h.messages)?h.messages:[],hasMore:h.hasMore===!0}})},[e.agentType,u,i,l,n,c]);return o.useMemo(()=>Fm(x,v),[v,x])}function Ym(e,t){const{sendData:r}=wt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??or),i=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Ta)),c=Vm(i),[l,d]=o.useState(0),[f,u]=o.useState(()=>new Map);o.useEffect(()=>{if(!n||e.length===0)return;const m=setInterval(()=>{d(v=>v+1)},c);return()=>{clearInterval(m)}},[e.length,n,c]);const x=o.useMemo(()=>Gm(e,{recentActivityMs:i}),[e,i,l]);return o.useEffect(()=>{if(!n||!r||x.descriptors.length===0){u(h=>h.size===0?h:new Map);return}const m=x.descriptors.map(h=>({key:La(h.daemonId,h.sessionId),controller:mc({...h,sendData:r,tailLimit:a})})),v=new Set(m.map(({key:h})=>h)),S=(h,j)=>{u(b=>{const N=new Map(b);for(const A of N.keys())v.has(A)||N.delete(A);return N.set(h,j),N})},p=m.map(({key:h,controller:j})=>(j.retain(),S(h,j.getSnapshot()),j.subscribe(b=>S(h,b))));return()=>{p.forEach(h=>h()),m.forEach(({controller:h})=>h.release())}},[x.signature,n,r,a]),f}function Lo(e,t){const r=e[e.length-1];if(!r)return`empty:${t||""}`;let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return[t||"",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function Ro(e){for(let t=e.length-1;t>=0;t-=1){const r=Ma(e[t]);if(r>0)return r}return 0}function Xm(e){const t=Rs(e),r=e.sessionId||"";return t&&r?`${t}::${r}`:""}function Jm(e,t){if(t.length===0)return!1;const r=Array.isArray(e.messages)?e.messages:[];if(r.length===0)return!0;const n=Ro(r),a=Ro(t);if(n>0&&a>0&&a<n)return!1;const i=Lo(r,e.status),c=Lo(t,e.status);return i!==c}function Qm(e,t){const r=t[t.length-1],n=Ma(r),a=Ss(r==null?void 0:r.content);return{...e,messages:t,...a?{lastMessagePreview:a}:{},...n>0?{lastMessageAt:n}:{}}}function Zm(e,t){const r=(t==null?void 0:t.liveMessages)||[];return r.length>0?r:e.messages}function ef(e){const{historyMessages:t,liveMessages:r,visibleLiveCount:n}=e,i=Math.max(0,r.length-n)>0?r.slice(-n):r;return t.length===0?i:[...t,...i]}function Po(e,t){if(t.size===0||e.length===0)return e;let r=!1;const n=e.map(a=>{var l;const i=Xm(a);if(!i)return a;const c=((l=t.get(i))==null?void 0:l.liveMessages)||[];return Jm(a,c)?(r=!0,Qm(a,c)):a});return r?n:e}function tf(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function sf(e){return tf(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const rf=60;function na({activeConv:e,ideEntry:t,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:l,userName:d,showMetaChips:f=!1,scrollToBottomRequestNonce:u,isInputActive:x=!0,isVisible:m=!0}){var we,ye,ve,V,H;const v=o.useRef(new Map),S=ar();rr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const p=kt.useMemo(()=>Ts(e),[e.status,e.connectionState]),h=o.useMemo(()=>gm(e,t),[e,t]),j=o.useMemo(()=>{var Z;return ka((Z=h.targetEntry)==null?void 0:Z.providerControls,{hostIdeType:e.hostIdeType,providerType:h.providerType})},[e.hostIdeType,h.providerType,(we=h.targetEntry)==null?void 0:we.providerControls]),b=dc({isCliLike:h.isCli||h.isAcp}),N=Bm({isCliLike:h.isCli||h.isAcp}),A=qm(e,{enabled:m&&!!e.sessionId,tailLimit:N}),[y,I]=o.useState(b),k=e.tabKey,w=A.historyMessages,g=A.hasMoreHistory,E=A.historyError,M=Zm(e,A);o.useEffect(()=>{I(b)},[b,k]);const C=Math.max(0,M.length-y),R=Sa(e),K=Rs(e),z=sf(e),T=Aa(e),L=a||T,Y=!!T,[O,D]=o.useState(!1);o.useEffect(()=>{const Z=h.targetEntry;K&&(!Z||Z.providerControls===void 0||Z.controlValues===void 0)&&S(K,{minFreshMs:3e4}).catch(()=>{})},[K,h.isAcp,(ye=h.targetEntry)==null?void 0:ye.providerControls,(ve=h.targetEntry)==null?void 0:ve.controlValues,S]);const W=o.useCallback(async()=>{if(!O){if(M.length>y){I(Z=>Math.min(M.length,Z+rf));return}D(!0);try{await A.loadHistoryPage()}finally{D(!1)}}},[A,O,M.length,y]),{allMessages:Q,receivedAtMap:be}=o.useMemo(()=>{const Z=ef({historyMessages:w,liveMessages:M,visibleLiveCount:y}),me={};return Z.forEach((ne,fe)=>{const se=`${e.tabKey}:${Kr(ne,fe)}`;let xe=Ma(ne)||v.current.get(se)||0;xe||(xe=Date.now(),v.current.set(se,xe)),me[Kr(ne,fe)]=xe}),{allMessages:Z,receivedAtMap:me}},[e.tabKey,C,w,M,y]),pe=o.useMemo(()=>l.filter(Z=>Z.routeId===e.tabKey).sort((Z,me)=>Z.timestamp-me.timestamp),[l,e.tabKey]),ue=o.useMemo(()=>{if(M.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((p.isGenerating||e.status==="streaming")&&D(!1),e.status==="not_monitored"&&z)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(Js,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Switching...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ns,{size:14})," Open ",R," 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"&&z)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(Pi,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Opening...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ns,{size:14})," Open ",R," 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"&&!O)return 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,z,i,c,O,M.length,R,p.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[f&&s.jsx(lc,{conversation:e,className:"chat-pane-meta-row"}),s.jsx(uu,{messages:Q,actionLogs:pe,agentName:Cs(e)||R||"Agent",userName:d,isCliMode:h.isCli||h.isAcp,isWorking:p.isGenerating,contextKey:e.tabKey,receivedAtMap:be,onLoadMore:W,isLoadingMore:O,hasMoreHistory:g,hiddenLiveCount:C,loadError:E??void 0,emptyState:ue,scrollToBottomRequestNonce:u,isVisible:m}),s.jsx(dm,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:h.providerType,displayLabel:h.displayLabel,controls:(V=h.targetEntry)==null?void 0:V.providerControls,controlValues:(H=h.targetEntry)==null?void 0:H.controlValues,isActive:x,isCliTerminal:h.isCliTerminal}),!h.isCliTerminal&&s.jsx(Qi,{contextKey:e.tabKey,panelLabel:R,isSending:n,isBusy:Y,statusMessage:L,onSend:r,isActive:x,showControlsToggle:j.length>0})]})}let fc=cs;function pc(){return fc()}class nf{constructor(){Ge(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 hc=new nf;class af{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){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let it=new af;function of(e){e.dashboardWS&&(hc=e.dashboardWS),e.connectionManager&&(it=e.connectionManager),e.useDaemonsHook&&(fc=e.useDaemonsHook)}const cf=.5,lf=1.25;function nt(e){return Sa(e)}function us(e){return rc(e).join(" · ")}function xc(e){const t=sc(e);return t||(e.title?e.title:us(e)||"No messages yet")}function bc(e,t){const{isReconnecting:r,isConnecting:n}=Ts(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function df(e,t){const r=["Chat",...rc(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function ts(e){return bc(e)||us(e)}function uf(e){return`${nt(e)} · ${xc(e)}`}function mf(e){const t=Hr(e),r=t?st(t):Cs(e);return`${nt(e)} — ${r||"Agent"}`}function ff(e){return Cs(e)||"CLI"}function gc(e){return tc(e)}function yc(e){return e?`Remote · ${nt(e)||e.workspaceName||"Session"}`:"Remote"}function pf({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0,isInputActive:l=!0}){var ae;cs();const{sendPtyInput:d}=wt(),[f,u]=o.useState(!1),x=o.useRef(!1);x.current=f;const[m,v]=o.useState("Runtime terminal unavailable"),[S,p]=o.useState(1),[h,j]=o.useState({width:0,height:0}),[b,N]=o.useState({width:0,height:0}),A=o.useRef(null),y=o.useRef(null),I=o.useRef(!1),k=o.useRef(!1),w=o.useRef(0),g=o.useRef(!1),E=o.useRef(""),M=o.useRef(null),C=o.useRef(!1),R=o.useRef(null),K=32*1024,z=()=>{var X,J,oe,P;return((J=(X=A.current)==null?void 0:X.ownerDocument)==null?void 0:J.defaultView)||((P=(oe=y.current)==null?void 0:oe.ownerDocument)==null?void 0:P.defaultView)||window},T=X=>{const J=z();return{ownerWindow:J,frameId:J.requestAnimationFrame(X)}},L=()=>{const X=R.current;if(X){try{X.ownerWindow.cancelAnimationFrame(X.frameId)}catch{}R.current=null}},Y=()=>{c&&R.current===null&&(R.current=T(()=>{se()}))},O=e.tabKey,D=e.sessionId||"",W=e.daemonId||((ae=e.routeId)==null?void 0:ae.split(":")[0])||e.routeId||"",Q=Aa(e),be=f?i||Q:m,pe=cf,ue=lf,we=.05,ye=()=>{const X=b.width,J=b.height;if(!Number.isFinite(h.width)||h.width<=0||!Number.isFinite(h.height)||h.height<=0||!Number.isFinite(X)||X<=0||!Number.isFinite(J)||J<=0)return 1;const oe=h.width/X,P=h.height/J;return Number(Math.min(ue,Math.max(pe,Math.min(oe,P))).toFixed(2))},ve=ye(),V=I.current&&S>ve,H=Number.isFinite(b.width)&&b.width>0?Math.max(h.width,Math.round(b.width*S)):h.width,Z=Number.isFinite(b.height)&&b.height>0?Math.max(h.height,Math.round(b.height*S)):h.height,me=()=>{T(()=>{const X=y.current;X&&(X.scrollLeft=0,X.scrollTop=X.scrollHeight-X.clientHeight)})},ne=()=>{var X,J;w.current=0,g.current=!1,E.current="",M.current=null,C.current=!1,I.current||(k.current=!1,p(1)),R.current!==null&&L(),u(!1),v("Runtime terminal unavailable"),(J=(X=r.current)==null?void 0:X.reset)==null||J.call(X)},fe=()=>{var X,J;w.current=0,g.current=!1,E.current="",M.current=null,C.current=!1,R.current!==null&&L(),u(!0),v(""),(J=(X=r.current)==null?void 0:X.reset)==null||J.call(X)},se=()=>{var oe;if(R.current=null,!c)return;const X=E.current;if(!X)return;const J=X.slice(0,K);E.current=X.slice(J.length),(oe=r.current)==null||oe.write(J),E.current.length>0&&Y()},xe=X=>{X&&(E.current+=X,Y())},ie=(X,J=0,oe,P)=>{var G,U,de,Ne;J>0&&w.current>=J||J===0&&g.current||(w.current=J,u(!0),v(""),typeof oe=="number"&&typeof P=="number"&&oe>0&&P>0&&((U=(G=r.current)==null?void 0:G.resize)==null||U.call(G,oe,P)),E.current="",(Ne=(de=r.current)==null?void 0:de.reset)==null||Ne.call(de),X&&xe(X))};o.useEffect(()=>{ne()},[D]),o.useEffect(()=>{var J;if(!D)return;const X=((J=it.onRuntimeEvent)==null?void 0:J.call(it,D,oe=>{if(!(!oe||oe.sessionId!==D)){if(oe.type==="runtime_snapshot"){if(!c){M.current={text:oe.text||"",seq:oe.seq||0,cols:oe.cols,rows:oe.rows};return}ie(oe.text||"",oe.seq||0,oe.cols,oe.rows);return}if(oe.type==="session_output"){g.current=!0,typeof oe.seq=="number"&&(w.current=Math.max(w.current,oe.seq)),x.current||u(!0),x.current||v(""),typeof oe.data=="string"&&xe(oe.data);return}if(oe.type==="session_cleared"){if(!c){C.current=!0,E.current="",M.current=null;return}fe();return}if(oe.type==="session_io_error"){const P=typeof oe.error=="string"&&oe.error?oe.error:typeof oe.reason=="string"&&oe.reason?oe.reason:"unknown error";u(!1),v(`Runtime input failed: ${P}`);return}}},W))||(()=>{});return()=>{X()}},[W,D,r,c]);const ce=async()=>{var X;if(!(!W||!D)){v("Loading runtime terminal...");try{const J=await((X=it.requestRuntimeSnapshot)==null?void 0:X.call(it,W,D));J&&J.success===!1&&(u(!1),v(`Runtime terminal unavailable: ${J.error}`))}catch(J){u(!1),v(`Runtime terminal unavailable: ${(J==null?void 0:J.message)||String(J)}`)}}};return o.useEffect(()=>{var J,oe;if(!D)return;W&&((J=it.getState)==null?void 0:J.call(it,W))==="connected"&&ce();const X=(oe=it.onStateChange)==null?void 0:oe.call(it,(P,G)=>{P!==W||G!=="connected"||ce()});return()=>{X==null||X()}},[W,D,r]),o.useEffect(()=>{t&&ne()},[t,O,r]),o.useEffect(()=>{var P,G;const X=A.current,J=(G=(P=X==null?void 0:X.ownerDocument)==null?void 0:P.defaultView)==null?void 0:G.ResizeObserver;if(!X||!J)return;const oe=new J(U=>{const de=U[0];if(!de)return;const{width:Ne,height:_e}=de.contentRect;j(ge=>{const Be=Math.round(Ne),Oe=Math.round(_e);return ge.width===Be&&ge.height===Oe?ge:{width:Be,height:Oe}})});return oe.observe(X),()=>oe.disconnect()},[]),o.useEffect(()=>{if(I.current)return;const X=ye();!Number.isFinite(X)||X<=0||p(J=>k.current?X<J-we?X:J:(k.current=!0,X))},[b.height,b.width,h.height,h.width]),o.useEffect(()=>{V&&me()},[V,Z,H]),o.useEffect(()=>{var J;if(!c)return;C.current&&(C.current=!1,fe());const X=M.current;X&&(M.current=null,ie(X.text,X.seq,X.cols,X.rows)),W&&D&&((J=it.getState)==null?void 0:J.call(it,W))==="connected"&&ce(),E.current&&R.current===null&&Y(),T(()=>{var oe;(oe=r.current)==null||oe.bumpResize()})},[W,c,D]),o.useEffect(()=>()=>{R.current!==null&&L()},[]),o.useEffect(()=>{const X=P=>{var U;const G=P.detail;G!=null&&G.sessionId&&G.sessionId!==D||f&&((U=r.current)==null||U.bumpResize())},J=z(),oe=J===window?[window]:[window,J];for(const P of oe)P.addEventListener("adhdev:fit-cli-terminal",X);return()=>{for(const P of oe)P.removeEventListener("adhdev:fit-cli-terminal",X)}},[f,D,r]),s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:A,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",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:()=>{I.current=!0,p(X=>{const J=Math.max(ve,Number((X-.1).toFixed(2)));return J>ve&&me(),J})},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:()=>{I.current=!0,p(X=>{const J=Math.min(ue,Number((X+.1).toFixed(2)));return J>ve&&me(),J})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:y,className:V?"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:H>0?`${H}px`:"100%",height:Z>0?`${Z}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:b.width>0?`${b.width}px`:"100%",height:b.height>0?`${b.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:S},children:s.jsx(Oi,{ref:r,readOnly:!f||!c,sizingMode:"measured",onViewportMetrics:N,onInput:X=>{!f||(d==null||d(W,D,X))}})})})}),!f&&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:m})]}),s.jsx(Qi,{contextKey:e.tabKey,panelLabel:nt(e),isSending:a,isBusy:!!Q,statusMessage:be,onSend:async X=>Q?!1:n(X),isActive:l&&c,showControlsToggle:!1,animateVisibility:!1})]})}const hf=2500;function xf(e){return e==="disconnected"||e==="reconnecting"}function bf({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=hf}){const i=xf(e),[c,l]=o.useState(()=>!i||a<=0),d=o.useRef(!1);o.useEffect(()=>{if(!i){l(!1);return}if(d.current=!1,a<=0){d.current=!0,l(!0);return}l(!1);const j=setTimeout(()=>{d.current=!0,l(!0)},a);return()=>clearTimeout(j)},[a,i]);const f=i?c:e==="offline"||e==="auth_failed",u=o.useMemo(()=>!t||e!=="connected"?!1:a<=0||d.current,[a,t,e]),x=e==="auth_failed"?"red":e==="offline"?"orange":"accent",m={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))"},v={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)"},S={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},p="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",h={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[f&&s.jsx("div",{className:p,style:h,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-4 py-3 text-[13px] font-semibold flex items-center gap-2.5 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:m[x],border:v[x],color:S[x]},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",children:[e==="offline"&&"Network offline — waiting for connection...",e==="disconnected"&&"Reconnecting to server...",e==="reconnecting"&&"Reconnecting to server...",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.")]}),n&&e!=="auth_failed"&&s.jsx("button",{type:"button",className:"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,disabled:e==="offline",children:"Reconnect now"})]})}),u&&s.jsx("div",{className:p,style:h,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 gf({terminalBackend:e,isStandalone:t=!1,machineLabel:r,machineKey:n}){const a=o.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[i,c]=o.useState(!1);if(o.useEffect(()=>{if(!a){c(!1);return}try{c(localStorage.getItem(a)==="1")}catch{c(!1)}},[a]),!t||!e||e.backend!=="xterm"||i)return null;const l=(r==null?void 0:r.trim())||"This machine",d=()=>{if(a)try{localStorage.setItem(a,"1")}catch{}c(!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:[l," 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 Ra({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(ga,{size:n}):s.jsx(Ut,{size:n})})}const $t="New session",vc="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 yf({wsStatus:e,isConnected:t,daemonCount:r,p2pStates:n={}}){if(e!=="connected")return{tone:"disconnected",title:"Disconnected",subtitle:null};const a=Object.values(n),i=a.filter(l=>l==="connected").length,c=a.filter(l=>l==="connecting"||l==="new"||l==="checking").length;return r>0&&c>0&&i===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 _o({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Do({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=Jr(e.updatedAt),l=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${l?"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",c].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[l?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(),i()},children:"Delete"})]})]})}function vf({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:i,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:d,onHideConversation:f,hiddenConversations:u=[],onShowConversation:x,onShowAllHidden:m,onResetPanelsToMain:v,inboxOpen:S,onInboxOpenChange:p,hiddenOpen:h,onHiddenOpenChange:j,onOpenNewSession:b,actionShortcuts:N,notifications:A,notificationUnreadCount:y,onOpenNotification:I,onMarkNotificationRead:k,onMarkNotificationUnread:w,onDeleteNotification:g}){const{ides:E,p2pStates:M={}}=cs(),C=!!e&&Ze(e)&&!Xe(e),R=!!e&&Xe(e),K=l||(e?Zi(e)?"terminal":"chat":null),[z,T]=o.useState(!1),L=o.useRef(null),Y=o.useRef(null),O=E.filter(V=>V.type==="adhdev-daemon"),D=yf({wsStatus:t,isConnected:r,daemonCount:O.length,p2pStates:M}),W=D.subtitle,Q=D.tone==="connected"?"#22c55e":D.tone==="limited"?"#eab308":"#ef4444",be=D.tone==="connected"?"0 0 4px #22c55e80":D.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",pe=o.useMemo(()=>A.filter(V=>!V.readAt),[A]),ue=o.useMemo(()=>A.filter(V=>!!V.readAt),[A]),we=o.useMemo(()=>pe.slice(0,9),[pe]),ye=y;o.useEffect(()=>{if(!S)return;const V=H=>{var Z;(Z=L.current)!=null&&Z.contains(H.target)||p(!1)};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[S,p]),o.useEffect(()=>{if(!h)return;const V=H=>{var Z;(Z=Y.current)!=null&&Z.contains(H.target)||j(!1)};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[h,j]),o.useEffect(()=>{if(!h&&!S)return;const V=H=>{if(!H.altKey)return;const Z=H.code.match(/^Digit([1-9])$/);if(!Z)return;const me=Number(Z[1])-1,ne=h?u[me]:void 0,fe=S?we[me]:void 0;if(!(!ne&&!fe)){if(H.preventDefault(),H.stopPropagation(),ne){x==null||x(ne),j(!1);return}fe&&(I(fe),p(!1))}};return window.addEventListener("keydown",V,!0),()=>window.removeEventListener("keydown",V,!0)},[u,h,S,we,j,p,I,x]);const ve=V=>{if(!V)return;const H=n.find(Z=>Z.tabKey===V);H&&(f==null||f(H))};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(Ut,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?nt(e):"Dashboard"}),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:Q,boxShadow:be}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[s.jsx("span",{title:D.title,className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:Q,boxShadow:be}}),W&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",W]}),b&&s.jsx("button",{type:"button",onClick:b,className:"btn btn-secondary btn-sm ml-2",title:$t,"aria-label":$t,children:s.jsx(Ei,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(C||R||!Xe(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:us(e)||nt(e),children:nt(e)}),(C||R)&&c&&s.jsxs(s.Fragment,{children:[C&&d&&K&&s.jsx(Ra,{mode:K,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>c(e),className:"btn btn-secondary btn-sm",title:R?"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(vt,{size:14})})]}),!Xe(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(ba,{size:14})}),!C&&!Xe(e)&&s.jsx("button",{onClick:i,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(Nt,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:L,children:[s.jsxs("div",{className:`dashboard-header-hidden${z?" is-drop-target":""}`,ref:Y,onDragEnter:V=>{V.dataTransfer.types.includes("text/tab-key")&&(V.preventDefault(),T(!0))},onDragOver:V=>{V.dataTransfer.types.includes("text/tab-key")&&(V.preventDefault(),V.dataTransfer.dropEffect="move",T(!0))},onDragLeave:V=>{V.currentTarget.contains(V.relatedTarget)||T(!1)},onDrop:V=>{const H=V.dataTransfer.getData("text/tab-key");V.preventDefault(),T(!1),ve(H)},children:[s.jsxs("button",{type:"button",onClick:()=>j(!h),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${N!=null&&N.toggleHiddenTabs?` (${N.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[s.jsx(_i,{size:16}),u.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:u.length})]}),h&&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(_o,{value:N==null?void 0:N.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[v&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:v,children:"Reset panels"}),u.length>0&&m&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{m(),j(!1)},children:"Restore all"})]})]}),e&&f&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>f(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(_o,{value:N==null?void 0:N.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:nt(e)})]}),u.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(V=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{x==null||x(V),j(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:nt(V)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(V)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(V)+1]}):null,us(V)]})]},V.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>p(!S),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(Xr,{size:16}),ye>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:ye})]}),S&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[pe.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),pe.map(V=>s.jsx(Do,{notification:V,shortcutIndex:we.indexOf(V)>=0?we.indexOf(V)+1:void 0,onOpen:()=>I(V),onMarkRead:()=>k(V.id),onMarkUnread:()=>w(V.id),onDelete:()=>g(V.id)},V.id))]}),ue.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),ue.map(V=>s.jsx(Do,{notification:V,onOpen:()=>I(V),onMarkRead:()=>k(V.id),onMarkUnread:()=>w(V.id),onDelete:()=>g(V.id)},V.id))]}),A.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function ht(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function wf(e,t){return String(e||"")!==String(t||"")}function jf(e,t={}){const r=String(t.textQuery||"").trim().toLowerCase(),n=String(t.workspaceQuery||"").trim().toLowerCase(),a=String(t.modelQuery||"").trim().toLowerCase(),i=!!t.resumableOnly;return!r&&!n&&!a&&!i?e:e.filter(c=>!(i&&!c.canResume||r&&![c.title,c.preview].map(d=>String(d||"").toLowerCase()).join(`
30
30
  `).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!Gi(c.summaryMetadata).map(d=>d.toLowerCase()).join(`
31
- `).includes(a)))}function kf(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 i=(Number(a.messageCount)||0)-(Number(n.messageCount)||0);if(i!==0)return i}return(Number(a.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function wc(e,t={}){return kf(jf(e,t),t.sortMode||"recent")}function Ur(e){return e?"Resume saved history":"Start fresh"}function Pa(e){return e?"Resuming saved history…":"Starting fresh…"}function Sf(){return"Start fresh"}function jc(e,t=!1){return e==="cli"?Ur(t):e==="ide"?"Start IDE":"Start ACP session"}function kc(e,t=!1){return e==="cli"?Pa(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Nf(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Cf(){return"Open saved history"}function If(){return"Saved History"}function _a(){return"Use saved history when you want continuity in the same provider conversation."}function Mf(){return"No saved history found yet."}function Af(){return"Refresh saved history"}function Tf(){return"Refreshing saved history…"}function ss(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function rs(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 Is(e){return e==="start-fresh"?"Start fresh":"Restart"}function Ms(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Da(e){return`Resume saved history with ${e}?`}function Ea(){return"Review or change the target workspace before resuming saved history."}function Lf(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 $a({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:d,onClose:f,onNewChat:u,onSwitchSession:x,onRefreshHistory:m,onResumeSavedSession:v}){var w;const S=t.find(g=>g.id===e.routeId),p=(S==null?void 0:S.chats)||[],h=(w=S==null?void 0:S.activeChat)==null?void 0:w.id,j=Ze(e)&&!Xe(e),[b,N]=o.useState(()=>ht()),A=l||b,y=g=>{if(d){d(g);return}N(g)},I=o.useMemo(()=>wc(a,{textQuery:A.textQuery,workspaceQuery:A.workspaceQuery,modelQuery:A.modelQuery,resumableOnly:A.resumableOnly,sortMode:A.sortMode}),[A.modelQuery,A.resumableOnly,A.sortMode,A.textQuery,A.workspaceQuery,a]),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:f,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:j?If():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:mf(e)}),j&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:_a()})]}),s.jsx("button",{onClick:f,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(vt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!j&&s.jsx("button",{onClick:u,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),j?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:A.textQuery,onChange:g=>y({...A,textQuery:g.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:A.workspaceQuery,onChange:g=>y({...A,workspaceQuery:g.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:A.modelQuery,onChange:g=>y({...A,modelQuery:g.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:A.sortMode,onChange:g=>y({...A,sortMode:g.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:A.resumableOnly,onChange:g=>y({...A,resumableOnly:g.target.checked})}),"Resume-ready only"]})]}),I.map(g=>{const E=e.providerSessionId===g.providerSessionId,M=E||!g.canResume||!!c;return s.jsxs("button",{type:"button",onClick:()=>{M||!v||v(g)},disabled:M,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${E?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${M?"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 ${E?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:g.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:g.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Lf(g.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:g.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:[g.workspace||"Workspace unknown",ds(g.summaryMetadata)?` · ${ds(g.summaryMetadata)}`:"",g.messageCount>0?` · ${g.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:E?"ACTIVE":g.canResume?c===g.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},g.id)})]}):p.map(g=>s.jsxs("div",{onClick:()=>{x(e.routeId,g.id),f()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${h===g.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 ${h===g.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:g.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:[g.id.substring(0,12),"..."]}),h===g.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},g.id)),(j&&!i&&I.length===0||!j&&p.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(Fd,{size:32})}),s.jsx("div",{className:"text-[13px]",children:j?a.length>0?"No saved history matches these filters.":Mf():"No recent chat sessions found."})]}),j&&i&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:Tf()})})]}),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:m,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(sr,{size:13})," ",j?Af():"Refresh History"]})})})]})]});return typeof document>"u"?k:qs.createPortal(k,document.body)}const Eo={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 Sc({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=Eo[n.type]||Eo.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 i;(i=n.actions)!=null&&i.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:i=>{i.stopPropagation(),t(n.id)},"aria-label":"Dismiss",children:s.jsx(vt,{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((i,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:l=>{l.stopPropagation(),i.onClick(),t(n.id)},children:i.label},c))})]})]},n.id)})})}const Rf=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Pf(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function _f(e){return e.sessionId||e.instanceId||e.agentType}function yn(e,t){return e||t}function Nc(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=At(r,{fallbackId:r.id}));return t}function Cc(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 Ba(e,t={}){return Df(e,Cc(e,t))}function Df(e,t={}){var u,x,m,v,S,p;const r=[],n=t.machineName,a=t.connectionState,i=Pf(e),c=Tu(e.type,{agentName:e.cliName}),l=Ze(e)||Xe(e)?c:st(e.type),d=Array.isArray(e.childSessions)?e.childSessions.map(h=>{var j,b;return{sessionId:h.id,instanceId:h.id,providerSessionId:h.providerSessionId,transport:h.transport,sessionCapabilities:h.capabilities,agentType:h.providerType,agentName:h.providerName||st(h.providerType),status:h.status,title:h.title,lastMessagePreview:h.lastMessagePreview,lastMessageRole:h.lastMessageRole,lastMessageAt:h.lastMessageAt,lastMessageHash:h.lastMessageHash,messages:((j=h.activeChat)==null?void 0:j.messages)||[],activeModal:((b=h.activeChat)==null?void 0:b.activeModal)||void 0,unread:h.unread,lastSeenAt:h.lastSeenAt,lastUpdated:h.lastUpdated,inboxBucket:h.inboxBucket,surfaceHidden:h.surfaceHidden}}):[],f=Rf(e);if(f){const h=e.sessionId||e.instanceId,j=c,b=(u=e.activeChat)==null?void 0:u.activeModal,N=b&&Array.isArray(b.buttons)&&b.buttons.length>0,A=bt((x=e.activeChat)==null?void 0:x.status,{activeModal:(m=e.activeChat)==null?void 0:m.activeModal})||bt((S=(v=e.agents)==null?void 0:v[0])==null?void 0:S.status)||"idle",y=e.activeChat||{title:"",messages:[]};let I=y.title&&String(y.title).trim()?String(y.title).trim():"";const k=(p=e.activeChat)==null?void 0:p.id,w=e.chats;if(k&&Array.isArray(w)&&w.length>0){const C=w.find(R=>R.id===k||R.id&&String(R.id)===String(k));C!=null&&C.title&&String(C.title).trim()&&(I=String(C.title).trim())}const g=(Ze(e)||Xe(e),e.type),E=(Ze(e)||Xe(e))&&jo(I,j,g)?"":I,M=y.messages||[];r.push({routeId:e.id,sessionId:h,providerSessionId:e.providerSessionId,nativeSessionId:h,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:Ze(e)?e.mode||"terminal":"chat",agentName:j,agentType:g,status:A,title:E,messages:M,resume:e.resume,hostIdeType:!Ze(e)&&!Xe(e)?e.type:void 0,workspaceName:i,displayPrimary:E||i||(Ze(e)?e.mode==="chat"?j:"Terminal":j),displaySecondary:l,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:N?b.buttons:void 0,modalMessage:N?b.message:void 0,streamSource:"native",tabKey:yn(h,e.id),machineName:n,connectionState:a})}if(f&&(Ze(e)||Xe(e)))return r;for(const h of d){const j=h.activeModal&&Array.isArray(h.activeModal.buttons)&&h.activeModal.buttons.length>0,b=Lu(h),N=_f(h),A=`${e.id}:${N}`,y=h.title&&String(h.title).trim()||"",I=jo(y,h.agentName,h.agentType)?"":y,k=h.messages||[];(h.transport==="cdp-webview"||h.sessionId||h.providerSessionId||k.length>0||j||I||!["idle","panel_hidden","disconnected","not_monitored"].includes(b))&&r.push({routeId:e.id,sessionId:h.sessionId||h.instanceId,providerSessionId:h.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:h.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:h.sessionCapabilities,mode:"chat",agentName:h.agentName,agentType:h.agentType,status:b,title:I,messages:k,hostIdeType:e.type,workspaceName:i,displayPrimary:I||i||h.agentName||l,displaySecondary:`${l} · ${h.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:h.lastMessagePreview,lastMessageRole:h.lastMessageRole,lastMessageAt:h.lastMessageAt,lastMessageHash:h.lastMessageHash,lastUpdated:h.lastUpdated||e.lastUpdated,modalButtons:j?h.activeModal.buttons:void 0,modalMessage:j?h.activeModal.message:void 0,streamSource:"agent-stream",tabKey:yn(h.sessionId||h.instanceId,A),machineName:n,connectionState:a})}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:i,displayPrimary:i||l,displaySecondary:l,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:yn(e.sessionId||e.instanceId,e.id),connectionState:a}),r}function Ef(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 Ic(e,t){const r=Ef(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Mc=[{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:"🏄"}],Ac=[{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:"🧩"}],Tc=[{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:"🟠"}],$f=Mc,Bf=Ac,Kf=Tc;function ms(...e){return rd(nd(e))}function Of({icon:e,title:t,subtitle:r,badge:n,actions:a,className:i}){return s.jsxs("div",{className:ms("dashboard-header",i),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 Lc({icon:e,title:t,subtitle:r,badge:n,actions:a,widthClassName:i="max-w-6xl",contentClassName:c,children:l}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(Of,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:ms("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}const aa="adhdev:themechange";function Wf(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function xs(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function bs(e){return e==="system"?Wf():e}function Rc(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Lr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(aa,{detail:{preference:e,theme:t}}))}function Hf(){const e=xs(),t=bs(e);Rc(t),Lr(e,t)}function Ka(){const[e,t]=o.useState(xs),[r,n]=o.useState(()=>bs(xs()));o.useEffect(()=>{Rc(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=d=>{if(e==="system"){const f=d.matches?"light":"dark";n(f),Lr("system",f)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=d=>{const f=d.detail||{},u=f.preference,x=f.theme;t(u==="dark"||u==="light"||u==="system"?u:xs()),n(x==="dark"||x==="light"?x:bs(xs()))},l=d=>{if(d.key!=="theme")return;const f=xs(),u=bs(f);t(f),n(u)};return window.addEventListener(aa,c),window.addEventListener("storage",l),()=>{window.removeEventListener(aa,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=bs(c);t(c),n(l);try{localStorage.setItem("theme",c)}catch{}Lr(c,l)},[]),i=o.useCallback(()=>{t(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",d=bs(l);n(d);try{localStorage.setItem("theme",l)}catch{}return Lr(l,d),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const $o={dark:"Dark",light:"Light",system:"System"};function Ff({collapsed:e}){const{preference:t,cycleTheme:r}=Ka(),n=t==="dark"?s.jsx(zd,{size:16}):t==="light"?s.jsx(Ud,{size:16}):s.jsx(Vd,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${$o[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:$o[t]})]})}function vn(e,t){return e?typeof e=="function"?e(t):e:null}function Uf({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:i,footerActions:c,preMainContent:l,collapsedStorageKey:d="sidebar-collapsed"}){const[f,u]=o.useState(!1),[x,m]=o.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),v=()=>u(!0),S=()=>u(!1),p=()=>{m(N=>{const A=!N;try{localStorage.setItem(d,A?"1":"0")}catch{}return A})},h=o.useMemo(()=>({collapsed:x,mobileMenuOpen:f,openMobileMenu:v,closeMobileMenu:S,toggleCollapsed:p}),[x,f]),j=N=>`nav-item${N.active?" active":""} cursor-pointer ${x?"justify-center py-2.5 px-0":""}${N.className?` ${N.className}`:""}`,b=N=>s.jsxs("div",{className:j(N),id:`nav-${N.id}`,onClick:()=>{N.onSelect(),S()},title:x?N.title??(typeof N.label=="string"?N.label:void 0):N.title,children:[s.jsx("span",{className:"nav-icon",children:N.icon}),!x&&N.label]},N.id);return s.jsxs("div",{className:`app-layout${f?" mobile-menu-open":""}${x?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:v,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),f&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:S,onKeyDown:N=>N.key==="Escape"&&S()}),s.jsxs("aside",{className:`sidebar ${f?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${x?"justify-center gap-0":""}`,children:vn(t,h)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:S,children:s.jsx(vt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(b)}),n.map(N=>s.jsxs("div",{className:N.className??"border-t border-border-subtle pt-2 mt-2",children:[!x&&N.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:N.title}):null,N.items.map(b)]},N.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(b),vn(i,h),s.jsx(Ff,{collapsed:x}),vn(c,h)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function St({title:e,icon:t,description:r,accentColor:n,className:a,children:i}){return s.jsxs("div",{className:ms("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})]}),i]})}function Pc({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:ms("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 zf={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"},Vf={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function gr({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:ms("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",zf[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Vf[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:"✕"})]})}const Gf={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"},qf={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Yf({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:ms("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Gf[e],r),children:[s.jsx("span",{className:ms("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",qf[e])}),n]})}function Qt({label:e,description:t,checked:r,disabled:n,onChange:a,extra:i}){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:[i,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 Xf({onPrefChange:e}){const[t,r]=Wu(),[n,a]=o.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);o.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,l)=>{r({[c]:l}),e==null||e(c,l)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Xr,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:c=>i("globalEnabled",c)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Nt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:c=>i("browserNotifications",c)}),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:()=>{Xi().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(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Gd,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(qd,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Js,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!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 zr(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function Jf(e,t){const r=zr(e),n=zr(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 _c(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function zs(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||Jf(r,t)>=0)return!1;const n=zr(r),a=zr(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Qf(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function wn(e,t){return e instanceof Error?e.message:t}function Zf({ides:e,emptyMessage:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?s.jsx(Pc,{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:i.map(c=>s.jsx(tp,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function Bo({title:e,message:t,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:i}){const c=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return qs.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,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:l=>l.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:i,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:"Cancel"}),s.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:n==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:r})]})]})}),document.body)}function ep(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...$f,...Bf,...Kf].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 tp({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var K,z;const[i,c]=o.useState("idle"),[l,d]=o.useState(""),[f,u]=o.useState(null),[x,m]=o.useState("idle"),[v,S]=o.useState(""),p=e.version||null,h=((K=e.machine)==null?void 0:K.platform)||((z=e.system)==null?void 0:z.platform)||"",j=At(e,{fallbackId:e.id}),b=h==="win32"?"🪟":h==="darwin"?"🍎":"🐧",N=t.filter(T=>T.daemonId===e.id&&T.transport==="cdp-page"),A=t.filter(T=>T.daemonId===e.id&&T.transport==="pty"),y=t.filter(T=>T.daemonId===e.id&&T.transport==="acp"),I=e.p2p,k=async()=>{if(r){c("upgrading"),d("Starting upgrade...");try{const T=Qf(await r(e.id,"daemon_upgrade",{}));T.alreadyLatest?(c("done"),d(`Already on v${T.version||"latest"}.`)):T.upgraded||T.success?(c("done"),d(`Upgrade to v${T.version||"latest"} started. Daemon is restarting...`)):(c("error"),d(T.error||"Upgrade failed"))}catch(T){c("error"),d(wn(T,"Connection lost during upgrade"))}}},w=async()=>{if(u(null),!!n){m("loading");try{await n(e.id),m("done"),S("Machine disconnected.")}catch(T){m("error"),S(wn(T,"Failed to disconnect"))}}},g=async()=>{if(u(null),!!a){m("loading");try{await a(e.id),m("done"),S("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(T){m("error"),S(wn(T,"Failed to revoke token"))}}},E="0.9.26",M=_c(e,E),C=zs(e,E),R=N.length+A.length+y.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:b}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:j}),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] ${M?"":"bg-bg-secondary"}`,style:M?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",p,!M&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&M&&s.jsx("button",{onClick:k,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${E}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${C?"↑ Update now":`↑ Update${` to v${E}`}`}`}),n&&s.jsx("button",{onClick:()=>u("disconnect"),disabled:x==="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:x==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(Yf,{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:[I&&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 ${I.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${I.state==="connecting"||I.state==="new"?"animate-pulse":""}`,style:I.state==="connecting"||I.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",I.state==="connected"?"connected":I.state==="connecting"||I.state==="new"?"connecting...":I.state||"off"]}),I.peers!==void 0&&I.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",I.peers," peer",I.peers!==1?"s":"",")"]})]}),I&&R>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),R>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[N.map(T=>{const L=ep(T.type),Y=T.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:L.icon}),s.jsx("span",{children:L.name}),Y!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Y?"bg-green-400":"animate-pulse"}`,style:Y?void 0:{background:"var(--status-warning)"},title:Y?"CDP connected":"CDP connecting..."})]},T.id)}),A.map(T=>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:T.cliName||"CLI"})]},T.id)),y.map(T=>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:T.cliName||"ACP"})]},T.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||v)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||x==="error"?"text-red-400":i==="done"||x==="done"?"text-green-400":"text-text-muted"}`,children:v||l})]}),f==="disconnect"&&s.jsx(Bo,{title:"🔌 Disconnect Machine",message:`Disconnect "${j}" from ADHDev?
31
+ `).includes(a)))}function kf(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 i=(Number(a.messageCount)||0)-(Number(n.messageCount)||0);if(i!==0)return i}return(Number(a.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function wc(e,t={}){return kf(jf(e,t),t.sortMode||"recent")}function Ur(e){return e?"Resume saved history":"Start fresh"}function Pa(e){return e?"Resuming saved history…":"Starting fresh…"}function Sf(){return"Start fresh"}function jc(e,t=!1){return e==="cli"?Ur(t):e==="ide"?"Start IDE":"Start ACP session"}function kc(e,t=!1){return e==="cli"?Pa(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Nf(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Cf(){return"Open saved history"}function If(){return"Saved History"}function _a(){return"Use saved history when you want continuity in the same provider conversation."}function Mf(){return"No saved history found yet."}function Af(){return"Refresh saved history"}function Tf(){return"Refreshing saved history…"}function ss(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function rs(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 Is(e){return e==="start-fresh"?"Start fresh":"Restart"}function Ms(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Da(e){return`Resume saved history with ${e}?`}function Ea(){return"Review or change the target workspace before resuming saved history."}function Lf(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 $a({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:d,onClose:f,onNewChat:u,onSwitchSession:x,onRefreshHistory:m,onResumeSavedSession:v}){var w;const S=t.find(g=>g.id===e.routeId),p=(S==null?void 0:S.chats)||[],h=(w=S==null?void 0:S.activeChat)==null?void 0:w.id,j=Ze(e)&&!Xe(e),[b,N]=o.useState(()=>ht()),A=l||b,y=g=>{if(d){d(g);return}N(g)},I=o.useMemo(()=>wc(a,{textQuery:A.textQuery,workspaceQuery:A.workspaceQuery,modelQuery:A.modelQuery,resumableOnly:A.resumableOnly,sortMode:A.sortMode}),[A.modelQuery,A.resumableOnly,A.sortMode,A.textQuery,A.workspaceQuery,a]),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:f,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:j?If():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:mf(e)}),j&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:_a()})]}),s.jsx("button",{onClick:f,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(vt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!j&&s.jsx("button",{onClick:u,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),j?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:A.textQuery,onChange:g=>y({...A,textQuery:g.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:A.workspaceQuery,onChange:g=>y({...A,workspaceQuery:g.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:A.modelQuery,onChange:g=>y({...A,modelQuery:g.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:A.sortMode,onChange:g=>y({...A,sortMode:g.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:A.resumableOnly,onChange:g=>y({...A,resumableOnly:g.target.checked})}),"Resume-ready only"]})]}),I.map(g=>{const E=e.providerSessionId===g.providerSessionId,M=E||!g.canResume||!!c;return s.jsxs("button",{type:"button",onClick:()=>{M||!v||v(g)},disabled:M,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${E?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${M?"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 ${E?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:g.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:g.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Lf(g.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:g.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:[g.workspace||"Workspace unknown",ds(g.summaryMetadata)?` · ${ds(g.summaryMetadata)}`:"",g.messageCount>0?` · ${g.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:E?"ACTIVE":g.canResume?c===g.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},g.id)})]}):p.map(g=>s.jsxs("div",{onClick:()=>{x(e.routeId,g.id),f()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${h===g.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 ${h===g.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:g.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:[g.id.substring(0,12),"..."]}),h===g.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},g.id)),(j&&!i&&I.length===0||!j&&p.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(Fd,{size:32})}),s.jsx("div",{className:"text-[13px]",children:j?a.length>0?"No saved history matches these filters.":Mf():"No recent chat sessions found."})]}),j&&i&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:Tf()})})]}),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:m,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(sr,{size:13})," ",j?Af():"Refresh History"]})})})]})]});return typeof document>"u"?k:qs.createPortal(k,document.body)}const Eo={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 Sc({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=Eo[n.type]||Eo.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 i;(i=n.actions)!=null&&i.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:i=>{i.stopPropagation(),t(n.id)},"aria-label":"Dismiss",children:s.jsx(vt,{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((i,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:l=>{l.stopPropagation(),i.onClick(),t(n.id)},children:i.label},c))})]})]},n.id)})})}const Rf=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Pf(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function _f(e){return e.sessionId||e.instanceId||e.agentType}function yn(e,t){return e||t}function Nc(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=At(r,{fallbackId:r.id}));return t}function Cc(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 Ba(e,t={}){return Df(e,Cc(e,t))}function Df(e,t={}){var u,x,m,v,S,p;const r=[],n=t.machineName,a=t.connectionState,i=Pf(e),c=Tu(e.type,{agentName:e.cliName}),l=Ze(e)||Xe(e)?c:st(e.type),d=Array.isArray(e.childSessions)?e.childSessions.map(h=>{var j,b;return{sessionId:h.id,instanceId:h.id,providerSessionId:h.providerSessionId,transport:h.transport,sessionCapabilities:h.capabilities,agentType:h.providerType,agentName:h.providerName||st(h.providerType),status:h.status,title:h.title,lastMessagePreview:h.lastMessagePreview,lastMessageRole:h.lastMessageRole,lastMessageAt:h.lastMessageAt,lastMessageHash:h.lastMessageHash,messages:((j=h.activeChat)==null?void 0:j.messages)||[],activeModal:((b=h.activeChat)==null?void 0:b.activeModal)||void 0,unread:h.unread,lastSeenAt:h.lastSeenAt,lastUpdated:h.lastUpdated,inboxBucket:h.inboxBucket,surfaceHidden:h.surfaceHidden}}):[],f=Rf(e);if(f){const h=e.sessionId||e.instanceId,j=c,b=(u=e.activeChat)==null?void 0:u.activeModal,N=b&&Array.isArray(b.buttons)&&b.buttons.length>0,A=bt((x=e.activeChat)==null?void 0:x.status,{activeModal:(m=e.activeChat)==null?void 0:m.activeModal})||bt((S=(v=e.agents)==null?void 0:v[0])==null?void 0:S.status)||"idle",y=e.activeChat||{title:"",messages:[]};let I=y.title&&String(y.title).trim()?String(y.title).trim():"";const k=(p=e.activeChat)==null?void 0:p.id,w=e.chats;if(k&&Array.isArray(w)&&w.length>0){const C=w.find(R=>R.id===k||R.id&&String(R.id)===String(k));C!=null&&C.title&&String(C.title).trim()&&(I=String(C.title).trim())}const g=(Ze(e)||Xe(e),e.type),E=(Ze(e)||Xe(e))&&jo(I,j,g)?"":I,M=y.messages||[];r.push({routeId:e.id,sessionId:h,providerSessionId:e.providerSessionId,nativeSessionId:h,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:Ze(e)?e.mode||"terminal":"chat",agentName:j,agentType:g,status:A,title:E,messages:M,resume:e.resume,hostIdeType:!Ze(e)&&!Xe(e)?e.type:void 0,workspaceName:i,displayPrimary:E||i||(Ze(e)?e.mode==="chat"?j:"Terminal":j),displaySecondary:l,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:N?b.buttons:void 0,modalMessage:N?b.message:void 0,streamSource:"native",tabKey:yn(h,e.id),machineName:n,connectionState:a})}if(f&&(Ze(e)||Xe(e)))return r;for(const h of d){const j=h.activeModal&&Array.isArray(h.activeModal.buttons)&&h.activeModal.buttons.length>0,b=Lu(h),N=_f(h),A=`${e.id}:${N}`,y=h.title&&String(h.title).trim()||"",I=jo(y,h.agentName,h.agentType)?"":y,k=h.messages||[];(h.transport==="cdp-webview"||h.sessionId||h.providerSessionId||k.length>0||j||I||!["idle","panel_hidden","disconnected","not_monitored"].includes(b))&&r.push({routeId:e.id,sessionId:h.sessionId||h.instanceId,providerSessionId:h.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:h.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:h.sessionCapabilities,mode:"chat",agentName:h.agentName,agentType:h.agentType,status:b,title:I,messages:k,hostIdeType:e.type,workspaceName:i,displayPrimary:I||i||h.agentName||l,displaySecondary:`${l} · ${h.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:h.lastMessagePreview,lastMessageRole:h.lastMessageRole,lastMessageAt:h.lastMessageAt,lastMessageHash:h.lastMessageHash,lastUpdated:h.lastUpdated||e.lastUpdated,modalButtons:j?h.activeModal.buttons:void 0,modalMessage:j?h.activeModal.message:void 0,streamSource:"agent-stream",tabKey:yn(h.sessionId||h.instanceId,A),machineName:n,connectionState:a})}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:i,displayPrimary:i||l,displaySecondary:l,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:yn(e.sessionId||e.instanceId,e.id),connectionState:a}),r}function Ef(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 Ic(e,t){const r=Ef(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Mc=[{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:"🏄"}],Ac=[{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:"🧩"}],Tc=[{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:"🟠"}],$f=Mc,Bf=Ac,Kf=Tc;function ms(...e){return rd(nd(e))}function Of({icon:e,title:t,subtitle:r,badge:n,actions:a,className:i}){return s.jsxs("div",{className:ms("dashboard-header",i),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 Lc({icon:e,title:t,subtitle:r,badge:n,actions:a,widthClassName:i="max-w-6xl",contentClassName:c,children:l}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(Of,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:ms("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}const aa="adhdev:themechange";function Wf(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function xs(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function bs(e){return e==="system"?Wf():e}function Rc(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Lr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(aa,{detail:{preference:e,theme:t}}))}function Hf(){const e=xs(),t=bs(e);Rc(t),Lr(e,t)}function Ka(){const[e,t]=o.useState(xs),[r,n]=o.useState(()=>bs(xs()));o.useEffect(()=>{Rc(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=d=>{if(e==="system"){const f=d.matches?"light":"dark";n(f),Lr("system",f)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=d=>{const f=d.detail||{},u=f.preference,x=f.theme;t(u==="dark"||u==="light"||u==="system"?u:xs()),n(x==="dark"||x==="light"?x:bs(xs()))},l=d=>{if(d.key!=="theme")return;const f=xs(),u=bs(f);t(f),n(u)};return window.addEventListener(aa,c),window.addEventListener("storage",l),()=>{window.removeEventListener(aa,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=bs(c);t(c),n(l);try{localStorage.setItem("theme",c)}catch{}Lr(c,l)},[]),i=o.useCallback(()=>{t(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",d=bs(l);n(d);try{localStorage.setItem("theme",l)}catch{}return Lr(l,d),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const $o={dark:"Dark",light:"Light",system:"System"};function Ff({collapsed:e}){const{preference:t,cycleTheme:r}=Ka(),n=t==="dark"?s.jsx(zd,{size:16}):t==="light"?s.jsx(Ud,{size:16}):s.jsx(Vd,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${$o[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:$o[t]})]})}function vn(e,t){return e?typeof e=="function"?e(t):e:null}function Uf({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:i,footerActions:c,preMainContent:l,collapsedStorageKey:d="sidebar-collapsed"}){const[f,u]=o.useState(!1),[x,m]=o.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),v=()=>u(!0),S=()=>u(!1),p=()=>{m(N=>{const A=!N;try{localStorage.setItem(d,A?"1":"0")}catch{}return A})},h=o.useMemo(()=>({collapsed:x,mobileMenuOpen:f,openMobileMenu:v,closeMobileMenu:S,toggleCollapsed:p}),[x,f]),j=N=>`nav-item${N.active?" active":""} cursor-pointer ${x?"justify-center py-2.5 px-0":""}${N.className?` ${N.className}`:""}`,b=N=>s.jsxs("div",{className:j(N),id:`nav-${N.id}`,onClick:()=>{N.onSelect(),S()},title:x?N.title??(typeof N.label=="string"?N.label:void 0):N.title,children:[s.jsx("span",{className:"nav-icon",children:N.icon}),!x&&N.label]},N.id);return s.jsxs("div",{className:`app-layout${f?" mobile-menu-open":""}${x?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:v,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),f&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:S,onKeyDown:N=>N.key==="Escape"&&S()}),s.jsxs("aside",{className:`sidebar ${f?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${x?"justify-center gap-0":""}`,children:vn(t,h)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:S,children:s.jsx(vt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(b)}),n.map(N=>s.jsxs("div",{className:N.className??"border-t border-border-subtle pt-2 mt-2",children:[!x&&N.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:N.title}):null,N.items.map(b)]},N.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(b),vn(i,h),s.jsx(Ff,{collapsed:x}),vn(c,h)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function St({title:e,icon:t,description:r,accentColor:n,className:a,children:i}){return s.jsxs("div",{className:ms("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})]}),i]})}function Pc({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:ms("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 zf={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"},Vf={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function gr({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:ms("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",zf[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Vf[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:"✕"})]})}const Gf={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"},qf={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Yf({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:ms("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Gf[e],r),children:[s.jsx("span",{className:ms("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",qf[e])}),n]})}function Qt({label:e,description:t,checked:r,disabled:n,onChange:a,extra:i}){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:[i,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 Xf({onPrefChange:e}){const[t,r]=Wu(),[n,a]=o.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);o.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,l)=>{r({[c]:l}),e==null||e(c,l)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Xr,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:c=>i("globalEnabled",c)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Nt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:c=>i("browserNotifications",c)}),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:()=>{Xi().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(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Gd,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(qd,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Js,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!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 zr(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function Jf(e,t){const r=zr(e),n=zr(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 _c(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function zs(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||Jf(r,t)>=0)return!1;const n=zr(r),a=zr(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Qf(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function wn(e,t){return e instanceof Error?e.message:t}function Zf({ides:e,emptyMessage:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?s.jsx(Pc,{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:i.map(c=>s.jsx(tp,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function Bo({title:e,message:t,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:i}){const c=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return qs.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,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:l=>l.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:i,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:"Cancel"}),s.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:n==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:r})]})]})}),document.body)}function ep(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...$f,...Bf,...Kf].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 tp({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var K,z;const[i,c]=o.useState("idle"),[l,d]=o.useState(""),[f,u]=o.useState(null),[x,m]=o.useState("idle"),[v,S]=o.useState(""),p=e.version||null,h=((K=e.machine)==null?void 0:K.platform)||((z=e.system)==null?void 0:z.platform)||"",j=At(e,{fallbackId:e.id}),b=h==="win32"?"🪟":h==="darwin"?"🍎":"🐧",N=t.filter(T=>T.daemonId===e.id&&T.transport==="cdp-page"),A=t.filter(T=>T.daemonId===e.id&&T.transport==="pty"),y=t.filter(T=>T.daemonId===e.id&&T.transport==="acp"),I=e.p2p,k=async()=>{if(r){c("upgrading"),d("Starting upgrade...");try{const T=Qf(await r(e.id,"daemon_upgrade",{}));T.alreadyLatest?(c("done"),d(`Already on v${T.version||"latest"}.`)):T.upgraded||T.success?(c("done"),d(`Upgrade to v${T.version||"latest"} started. Daemon is restarting...`)):(c("error"),d(T.error||"Upgrade failed"))}catch(T){c("error"),d(wn(T,"Connection lost during upgrade"))}}},w=async()=>{if(u(null),!!n){m("loading");try{await n(e.id),m("done"),S("Machine disconnected.")}catch(T){m("error"),S(wn(T,"Failed to disconnect"))}}},g=async()=>{if(u(null),!!a){m("loading");try{await a(e.id),m("done"),S("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(T){m("error"),S(wn(T,"Failed to revoke token"))}}},E="0.9.27",M=_c(e,E),C=zs(e,E),R=N.length+A.length+y.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:b}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:j}),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] ${M?"":"bg-bg-secondary"}`,style:M?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",p,!M&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&M&&s.jsx("button",{onClick:k,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${E}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${C?"↑ Update now":`↑ Update${` to v${E}`}`}`}),n&&s.jsx("button",{onClick:()=>u("disconnect"),disabled:x==="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:x==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(Yf,{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:[I&&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 ${I.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${I.state==="connecting"||I.state==="new"?"animate-pulse":""}`,style:I.state==="connecting"||I.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",I.state==="connected"?"connected":I.state==="connecting"||I.state==="new"?"connecting...":I.state||"off"]}),I.peers!==void 0&&I.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",I.peers," peer",I.peers!==1?"s":"",")"]})]}),I&&R>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),R>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[N.map(T=>{const L=ep(T.type),Y=T.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:L.icon}),s.jsx("span",{children:L.name}),Y!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Y?"bg-green-400":"animate-pulse"}`,style:Y?void 0:{background:"var(--status-warning)"},title:Y?"CDP connected":"CDP connecting..."})]},T.id)}),A.map(T=>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:T.cliName||"CLI"})]},T.id)),y.map(T=>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:T.cliName||"ACP"})]},T.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||v)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||x==="error"?"text-red-400":i==="done"||x==="done"?"text-green-400":"text-text-muted"}`,children:v||l})]}),f==="disconnect"&&s.jsx(Bo,{title:"🔌 Disconnect Machine",message:`Disconnect "${j}" from ADHDev?
32
32
 
33
33
  This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
34
34
 
@@ -39,7 +39,7 @@ This will:
39
39
  • Delete the machine registration
40
40
  • Require restarting ADHDev on that machine
41
41
 
42
- Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:g,onCancel:()=>u(null)})]})}const sp=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function rp(){const{preference:e,setPreference:t}=Ka();return s.jsx("div",{className:"flex gap-2",children:sp.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 np(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 ap(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function jn(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Ko(e){const{r:t,g:r,b:n}=ap(e);return .2126*jn(t)+.7152*jn(r)+.0722*jn(n)}function Oo(e,t){const r=Ko(e),n=Ko(t),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function Dc(e){const t=np(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return Oo(t,r)>=Oo(t,n)?r:n}const oa={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},ia={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},op=[{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"}}}],Ec="adhdev-chat-theme",$c="adhdev-chat-theme-custom";function Rr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Ec)||"ember"}catch{return"ember"}}function Pt(e){try{const t=localStorage.getItem($c);if(t){const r=JSON.parse(t);return{...e==="dark"?oa:ia,...r[e]}}}catch{}return e==="dark"?oa:ia}function yr(e,t){try{localStorage.setItem($c,JSON.stringify({dark:e,light:t}))}catch{}}function It(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 Vr(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 ip={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Vs(e,t){var a;const r=(a=ip[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",Vr(r,24)),n.style.setProperty("--accent-on-primary",Dc(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Vr(r,18)})`),n.style.setProperty("--border-accent",It(r,.35)),n.style.setProperty("--nav-active-bg",It(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${It(r,.06)}`)}function ns(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",It(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",It(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",It(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",It(e.borderSubtle,.5)),t.style.setProperty("--border-default",It(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Vr(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Dc(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Vr(e.accentColor,40)})`),t.style.setProperty("--border-accent",It(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",It(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${It(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 ${It(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 Oa(){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 cp(e){try{localStorage.setItem(Ec,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=as()?"dark":"light";ns(Pt(t))}else Oa(),Vs(e,as()?"dark":"light")}function lp(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Rr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=as()?"dark":"light";ns(Pt(t))}else Oa(),Vs(e,as()?"dark":"light")}function as(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function xt({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 Es({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 dp({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=o.useState(()=>Pt(r));o.useEffect(()=>{a(Pt(r))},[r]);const i=o.useCallback((c,l)=>{a(d=>{const f={...d,[c]:l},x=Pt(r==="dark"?"light":"dark");return r==="dark"?yr(f,x):yr(x,f),ns(f),t(f),f})},[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(Es,{title:"App Background",children:[s.jsx(xt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(xt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(xt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(Es,{title:"App Text",children:[s.jsx(xt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(xt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(xt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(Es,{title:"Borders & Accent",children:[s.jsx(xt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(xt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(xt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Es,{title:"Chat Bubbles",children:[s.jsx(xt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(xt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),s.jsx(xt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(xt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(Es,{title:"Chat Layout",children:[s.jsx(xt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(xt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(xt,{label:"Input border",value:n.inputBorder,onChange:c=>i("inputBorder",c)}),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:c=>i("bubbleRadius",Number(c.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 c=e?oa:ia,d=Pt(e?"light":"dark");e?yr(c,d):yr(d,c),a(c),ns(c),t(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:"Reset to defaults"})]})}function up(){const[e,t]=o.useState(Rr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Pt("dark"));o.useEffect(()=>{n(as());const d=new MutationObserver(()=>{const x=as();n(x);const m=Rr();m==="custom"?ns(Pt(x?"dark":"light")):Vs(m,x?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const f=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const x=as();n(x);const m=Rr();m==="custom"?ns(Pt(x?"dark":"light")):Vs(m,x?"dark":"light")};return f.addEventListener("change",u),()=>{d.disconnect(),f.removeEventListener("change",u)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?ns(Pt(r?"dark":"light")):(Oa(),Vs(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Pt(r?"dark":"light"))},[r]);const c=d=>{t(d),cp(d)},l=[...op,{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:l.map(d=>{const f=e===d.id,u=r?d.preview.dark:d.preview.light,x=d.id==="honey"||d.id==="ember"?"#1a1a1a":d.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>c(d.id),className:"text-left rounded-xl p-3 transition-all",style:{background:f?"var(--bg-glass-hover)":"var(--bg-glass)",border:f?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:f?1:.75},children:[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:x},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:[f&&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(dp,{dark:r,onColorsChange:d=>i(d)})]})}const Wa="adhdev_mobileDashboardMode_v1",ca="adhdev:mobile-dashboard-mode-change";function Ha(){try{return localStorage.getItem(Wa)==="workspace"?"workspace":"chat"}catch{return"chat"}}function mp(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??Ha())},r=a=>{const i=a.detail;t(i)},n=a=>{a.key&&a.key!==Wa||t()};return window.addEventListener(ca,r),window.addEventListener("storage",n),()=>{window.removeEventListener(ca,r),window.removeEventListener("storage",n)}}function fp(e){try{localStorage.setItem(Wa,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(ca,{detail:e}))}function pp(){const[e,t]=o.useState(!0);return o.useEffect(()=>{t(Ha()==="chat")},[]),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ut,{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),fp(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const kn=new Map,Wo=new Map;function hp(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 xp(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 Bc(){const{sendCommand:e}=wt(),{injectEntries:t,getIdes:r}=Ys();return o.useCallback(async(n,a)=>{if(!n)return;const i=(a==null?void 0:a.minFreshMs)??Mm,c=Wo.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<i)return;const l=kn.get(n);if(l)return l;const d=(async()=>{const f=await e(n,"get_machine_runtime_stats"),u=hp(f);if(!u)return;const x=r().find(v=>v.id===n),m=xp(x,n,u.machine,u.timestamp||Date.now());t([m]),Wo.set(n,Date.now())})().finally(()=>{kn.delete(n)});return kn.set(n,d),d},[r,t,e])}function bp(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 gp(e,t){const{sendData:r}=wt(),{injectEntries:n,getIdes:a}=Ys(),i=Array.from(new Set(e.filter(Boolean))).join("|");o.useEffect(()=>{if(!(t!=null&&t.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const l=c.map(d=>qt.subscribe({sendData:r},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const x=a().find(v=>v.id===d),m=bp(x,d,u);n([m])}));return()=>{l.forEach(d=>d())}},[i,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function yp(e,t){const{sendData:r}=wt(),[n,a]=o.useState(null),[i,c]=o.useState(!1);return o.useEffect(()=>{if(!e){a(null),c(!1);return}if(!(t!=null&&t.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const d=qt.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},f=>{l&&(clearTimeout(l),l=null),a(f.diagnostics),c(!1)});return d.initialSendAccepted?l=setTimeout(()=>{c(!1)},Rm):c(!1),()=>{l&&clearTimeout(l),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:i,applyDiagnostics:a}}function vp(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Kc(e){const{sendData:t}=wt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=vp(e);if(!a||!e.sessionId||!t){n({});return}const i=qt.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),ks.record({interactionId:c.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:c.status,modalButtonCount:Array.isArray(c.modalButtons)?c.modalButtons.length:0}})});return i.initialSendAccepted||n({}),()=>{i()}},[e.daemonId,e.routeId,e.sessionId,t]),r}const Oc="adhdev_hiddenTabs";function wp(){try{const e=localStorage.getItem(Oc);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ps(e){try{localStorage.setItem(Oc,JSON.stringify([...e]))}catch{}}function Sn(e){return Ca(e)}function Fa(e,t){return ws(t).some(r=>e.has(r))}function jp(){const[e,t]=o.useState(wp),r=o.useCallback(f=>{const u=Sn(f);t(x=>{const m=new Set(x);return m.has(u)?m.delete(u):m.add(u),ps(m),m})},[]),n=o.useCallback(f=>{const u=Sn(f);t(x=>{if(x.has(u))return x;const m=new Set(x);return m.add(u),ps(m),m})},[]),a=o.useCallback(f=>{const u=Sn(f);t(x=>{if(!x.has(u))return x;const m=new Set(x);return m.delete(u),ps(m),m})},[]),i=o.useCallback(()=>{t(f=>{if(f.size===0)return f;const u=new Set;return ps(u),u})},[]),c=o.useCallback((f,u)=>{t(x=>{const m=new Set(x);for(const v of u)m.add(v);return ps(m),m})},[]),l=o.useCallback((f,u)=>{t(x=>{const m=new Set(x);for(const v of u)m.delete(v);return ps(m),m})},[]),d=o.useCallback(f=>Fa(e,f),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:d}}function Wc(e){return e instanceof Error?e.message:String(e||"")}function Hc(e){const t=Wc(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 Fc(e){const t=Wc(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Uc({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!Ze(e)||Xe(e))return;const i=Ls(e);if(i===t)return;const c=e.sessionId;c&&a(l=>({...l,[c]:t}));try{await n(fs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Kt(e),mode:t})}catch(l){const d=Fc(l);c&&!d&&a(f=>{const u={...f};return i===zc(r,c)?delete u[c]:u[c]=i,u}),Hc(l)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",l instanceof Error?l.message:String(l)):console.error("Failed to switch CLI view mode:",l)}}function Ho(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 kp(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 i=Ho(a,t),c=Array.isArray(a.childSessions)?a.childSessions.map(d=>Ho(d,t)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function zc(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 Sp(e,t){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,i]of Object.entries(e))zc(t,a)===i&&(delete n[a],r=!0);return r?n:e}function Np({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{Xi()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:gc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Uu(a),o.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{r(l=>{const d=Date.now(),f={};for(const[u,x]of Object.entries(l))d-x<5e3&&(f[u]=x);return Object.keys(f).length===Object.keys(l).length?l:f})},5500);return()=>clearTimeout(c)},[t,r]),o.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const d=l.filter(f=>f.timestamp>c).slice(-100);return d.length===l.length?l:d})},6e4);return()=>clearInterval(i)},[n]),null}function Cp(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=r.get(n.id);if(!a){r.set(n.id,n);continue}const i=(a.workspace?1:0)+(a.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>i||(n.timestamp||0)>(a.timestamp||0))&&r.set(n.id,n)}return Array.from(r.values())}function Nn(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 Ip(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 Fo(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?Ip(Ss(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 Mp(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||""),Fo(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||""),Fo(r.activeChat)].join(":"))].join("|")}function Ap(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 Tp(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const i of ws({routeId:n.routeId}))r.set(i,a);for(const i of ws({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of ws({tabKey:n.tabKey}))r.set(i,n)}return r}function Lp(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Rp(e){const t=Lp(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=Ss(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Pp({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=o.useMemo(()=>Cp(e),[e]),i=o.useMemo(()=>Nc(e),[e]),c=o.useRef([]),l=o.useRef([]),d=o.useRef([]),f=o.useRef(new Map),u=o.useRef(new Map),x=o.useMemo(()=>{const A=new Map,y=[];for(const g of a){const{connectionState:E="new",machineName:M}=Cc(g,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),C=Mp(g),R=f.current.get(g.id);if(R&&R.ide===g&&R.sourceSignature===C&&R.connectionState===E&&R.machineName===M){A.set(g.id,R),y.push(...R.conversations);continue}const K=Ba(g,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),z={ide:g,sourceSignature:C,connectionState:E,machineName:M,conversations:K};A.set(g.id,z),y.push(...K)}f.current=A;const I=new Map,k=g=>{const E=Rp(g),M=u.current.get(g.tabKey);if(M&&M.signature===E)return I.set(g.tabKey,M),M.timestamp;const C={signature:E,timestamp:oc(g)||(M==null?void 0:M.timestamp)||0};return I.set(g.tabKey,C),C.timestamp},w=[...y].sort((g,E)=>ic(g,E,k));return u.current=I,w},[a,t,i]),m=o.useMemo(()=>{const A=Ap(x,r);return Nn(c.current,A)?c.current:(c.current=A,A)},[x,r]),v=o.useMemo(()=>{const A=new Map,y=Array.from(new Set(m.map(I=>I.routeId)));for(const I of y){const k=_t(m,I);k&&A.set(I,k)}return A},[m]),S=o.useMemo(()=>{const A=new Map;for(const y of m){const I=v.get(y.routeId),k=y.streamSource==="native"&&I?I:y;for(const w of ws({providerSessionId:y.providerSessionId,sessionId:y.sessionId}))A.set(w,k)}return A},[m,v]),p=o.useMemo(()=>Tp(m,v),[m,v]),h=o.useCallback(A=>{if(A)return S.get(A)},[S]),j=o.useCallback(A=>{if(A)return p.get(A)},[p]),b=o.useMemo(()=>{const A=m.filter(y=>!Fa(n,y));return Nn(l.current,A)?l.current:(l.current=A,A)},[m,n]),N=o.useMemo(()=>{const A=b.map(y=>y.tabKey);return Nn(d.current,A)?d.current:(d.current=A,A)},[b]);return{chatIdes:a,conversations:m,visibleConversations:b,visibleTabKeys:N,resolveConversationBySessionId:h,resolveConversationByTarget:j}}function _p({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:r,setSearchParams:n}){const a=o.useMemo(()=>{var l;return e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),i=o.useMemo(()=>{var l;return!e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),c=o.useCallback(()=>{t&&n(l=>{const d=new URLSearchParams(l);return d.delete("activeTab"),d},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function Dp({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){o.useEffect(()=>{lt.setIdes(e)},[e]),o.useEffect(()=>{lt.setResolveAction((a,i,c)=>{t(a,i,c).catch(()=>{})})},[t]),o.useEffect(()=>{const a=lt.onToast(i=>{r(l=>l.some(f=>f.message===i.message&&i.timestamp-f.timestamp<3e3)?l:[...l.slice(-4),{id:i.id,message:i.message,type:i.type,timestamp:i.timestamp,targetKey:i.targetKey,actions:i.actions}]);const c=i.duration||5e3;setTimeout(()=>r(l=>l.filter(d=>d.id!==i.id)),c)});return()=>{a()}},[r]),o.useEffect(()=>{const a=hc.on("status_event",i=>{lt.handleRawEvent(i,"ws")});return()=>{a()}},[]),o.useEffect(()=>{var i;const a=c=>{var p;const l=c.data;if((l==null?void 0:l.type)!=="notification_action"||typeof l.action!="string"||!l.action.startsWith("approval_")||!(l.daemonId||l.targetSessionId||l.targetKey))return;const d=l.targetSessionId||l.targetKey||l.daemonId,f=n(d),u=(f==null?void 0:f.routeId)||l.daemonId;if(!u)return;const x=Number(l.buttonIndex),m=l.button||((p=f==null?void 0:f.modalButtons)==null?void 0:p[x])||"Approve",v=String(m).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),S=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(v);t(u,"resolve_action",{action:S?"approve":"reject",button:m,...Number.isFinite(x)&&{buttonIndex:x},...(f==null?void 0:f.sessionId)&&{targetSessionId:f.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(h=>console.error("[SW Action] approval failed:",h))};return(i=navigator.serviceWorker)==null||i.addEventListener("message",a),()=>{var c;return(c=navigator.serviceWorker)==null?void 0:c.removeEventListener("message",a)}},[n,t])}const Ep="adhdev_dashboardLayout_v1",$p="adhdev_dashboardDockview_v1",Bp="adhdev_dashboardDockviewHiddenRestore_v1",$s={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Ua(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function Kp(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Vc(e){return`${Ep}:${e}`}function Op(e){const t=Vc(e);return Ua(t,null)}function Wp(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=Vc(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Gc(e){return`${$p}:${e}`}function Hp(e){const t=Gc(e);return Ua(t,null)}function Fp(e,t){try{const r=Gc(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function qc(e){return`${Bp}:${e}`}function Up(e){const t=qc(e);return Ua(t,{})}function zp(e,t){try{const r=qc(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Vp(){return{groupAssignments:[...$s.groupAssignments],focusedGroup:$s.focusedGroup,groupActiveTabIds:{...$s.groupActiveTabIds},groupTabOrders:{...$s.groupTabOrders},groupSizes:[...$s.groupSizes]}}function Gp(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function qp(){const[e]=o.useState(()=>Kp(typeof window<"u"?window.innerWidth:1280)),[t,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,d]=o.useState({}),[f,u]=o.useState([]),[x,m]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[v,S]=o.useState(!1),p=o.useCallback(()=>{if(v)return;const g=Op(e)??Vp();r(new Map(g.groupAssignments)),a(g.focusedGroup),c(g.groupActiveTabIds),d(g.groupTabOrders),u(g.groupSizes),S(!0)},[v,e]);o.useEffect(()=>{v&&Wp(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:f})},[v,e,t,n,i,l,f]),o.useEffect(()=>{const g=window.matchMedia("(max-width: 767px)"),E=M=>m(M.matches);return g.addEventListener("change",E),()=>g.removeEventListener("change",E)},[]);const h=o.useCallback(g=>{r(g)},[]),j=o.useCallback(g=>{a(g)},[]),b=o.useCallback(g=>{c(g)},[]),N=o.useCallback(g=>{d(g)},[]),A=o.useCallback(g=>{u(g)},[]),y=o.useCallback(g=>{j(g)},[j]),I=o.useCallback((g,E)=>{c(M=>(M[g]??null)===(E??null)?M:{...M,[g]:E})},[]),k=o.useCallback((g,E)=>{d(M=>{const C=M[g];return Gp(C,E)?M:{...M,[g]:E}})},[]),w=o.useCallback((g,E)=>{const M=E.get(g)??0;return I(M,g),y(M),M},[y,I]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:h,focusedGroup:n,updateFocusedGroup:j,focusGroup:y,groupActiveTabIds:i,updateGroupActiveTabIds:b,setGroupActiveTab:I,groupTabOrders:l,updateGroupTabOrders:N,setGroupTabOrder:k,groupSizes:f,updateGroupSizes:A,isMobile:x,hasHydratedStoredLayout:v,hydrateStoredLayout:p,focusConversationTab:w}}function Yp(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=Na(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Xp({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,focusConversationTab:c,setSearchParams:l,historyModalOpen:d,activeConv:f,isRefreshingHistory:u,ides:x,handleRefreshHistory:m}){const v=o.useRef(!1),S=o.useRef(!1),p=o.useRef(null),h=o.useRef(!1);o.useEffect(()=>{if(!e||v.current||t.length===0)return;if(!a){i();return}const j=r(e);j&&(c(j.tabKey,n),v.current=!0,S.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),l(b=>{const N=new URLSearchParams(b);return N.delete("activeTab"),N},{replace:!0}))},[e,t,r,n,a,i,c,l]),o.useEffect(()=>{if(!(S.current||a)&&t.length!==0){if(!e){i(),S.current=!0;return}if(v.current){S.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(S.current||a)&&(i(),S.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,t.length,a,i]),o.useEffect(()=>{if(!d){h.current=!1;return}if(!f||h.current||u)return;const j=x.find(b=>b.id===f.routeId);j&&(!j.chats||j.chats.length===0||Yp(j.chats,f))&&(h.current=!0,m())},[d,f,u,x,m]),o.useEffect(()=>{if(!f)return;let j=null,b=0,N=-1,A=0;const y=()=>{j=null;const I=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(w=>w.offsetParent!==null);if(I.length===0){b<18&&(b+=1,j=requestAnimationFrame(y));return}let k=0;for(const w of I)w.scrollTop=w.scrollHeight,k+=w.scrollHeight;k===N?A+=1:(A=0,N=k),b+=1,!(A>=2||b>=18)&&(j=requestAnimationFrame(y))};return j=requestAnimationFrame(y),()=>{j!=null&&cancelAnimationFrame(j)}},[f==null?void 0:f.tabKey])}function Cn(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=Na(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Yc({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:i}){const[c,l]=o.useState(!1),[d,f]=o.useState(!1),u=o.useCallback(async S=>{try{await e("standalone","launch_ide",{ideType:S,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),x=o.useCallback(async(S,p)=>{try{const h=S||(t==null?void 0:t.daemonId)||"",j=await e(h,"switch_chat",{id:p,sessionId:p,...js(t)}),b=j==null?void 0:j.result;if((j==null?void 0:j.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?Ds(a,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?Ds(a,`⚠️ Switch error: ${b}`):Ds(a,"⚠️ Session switch failed")}catch(h){console.error("Switch failed",h),Ds(a,`❌ Switch failed: ${h.message||"connection error"}`)}},[t,e,a]),m=o.useCallback(async()=>{if(!(!t||c)){l(!0);try{const S=Zs(t);await e(S,"new_chat",{...js(t)}),i(p=>({...p,[t.tabKey]:Date.now()}))}catch(S){console.error("New chat failed",S)}finally{l(!1)}}},[t,c,e,i]),v=o.useCallback(async()=>{var S,p;if(!(!t||d)){f(!0);try{const h=Zs(t),j=async()=>e(h,"list_chats",{forceExpand:!0,...js(t)});let b=await j(),N=(b==null?void 0:b.chats)||((S=b==null?void 0:b.result)==null?void 0:S.chats);Cn(N,t)&&(await new Promise(A=>setTimeout(A,450)),b=await j(),N=(b==null?void 0:b.chats)||((p=b==null?void 0:b.result)==null?void 0:p.chats)),b!=null&&b.success&&Array.isArray(N)&&(n(t.routeId,N),Cn(N,t)&&!Cn(r,t)&&Ds(a,"⚠️ History dialog did not fully open — try once more"))}catch(h){console.error("Refresh history failed",h)}finally{f(!1)}}},[t,r,d,e,n,a]);return{isCreatingChat:c,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:x,handleNewChat:m,handleRefreshHistory:v}}function Jp(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 Qp(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function Uo(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 vr(e,t){const r=new Set(t),n=t.length>0?[0]:[];for(const[c,l]of e)!r.has(c)||l<=0||n.includes(l)||n.push(l);n.sort((c,l)=>c-l);const a={};n.forEach((c,l)=>{a[c]=l}),n.length===0&&(a[0]=0);const i=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const d=a[l];typeof d=="number"&&d>0&&i.set(c,d)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function zo(e,t){const r={};for(const[n,a]of Object.entries(e)){const i=t[Number(n)];typeof i=="number"&&(r[i]=a)}return r}function Zp(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 eh(e,t,r){if(t.length<=1)return[];const n=t.map(c=>e[c]).filter(c=>Number.isFinite(c)),a=n.length===t.length?n:Array(r).fill(100/r),i=a.reduce((c,l)=>c+l,0);return i>0?a.map(c=>c/i*100):Array(r).fill(100/r)}function Vo(e,t){const r={};for(const[n,a]of Object.entries(e)){const i=Number(n);r[i>=t?i+1:i]=a}return r}function Go(e){return Array(e).fill(100/e)}function th({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:i,updateGroupSizes:c,isMobile:l,visibleConversations:d,visibleTabKeys:f}){const u=o.useRef(null),x=o.useMemo(()=>vr(e,f),[e,f]),m=x.assignments,v=o.useMemo(()=>l?1:x.groupCount,[x.groupCount,l]),S=v>1,p=o.useCallback((y,I)=>{t(k=>{const w=new Map(vr(k,f).assignments);return I===0?w.delete(y):w.set(y,I),w}),n(k=>({...k,[I]:y})),r(I)},[t,f,n,r]),h=o.useCallback(y=>{t(I=>{const k=vr(I,f).assignments,w=new Map;for(const[g,E]of k)E!==y&&(E>y?w.set(g,E-1):w.set(g,E));return w}),c(I=>{if(I.length<=1)return[];const k=[...I];k.splice(y,1);const w=k.reduce((g,E)=>g+E,0);return w>0?k.map(g=>g/w*100):[]}),r(0)},[t,f,c,r]),j=o.useCallback((y,I)=>{I.preventDefault();const k=u.current;if(!k)return;const w=I.clientX,g=k.offsetWidth,E=i.length===v?[...i]:Go(v),M=R=>{const z=(R.clientX-w)/g*100,T=[...E];T[y]=Math.max(15,E[y]+z),T[y+1]=Math.max(15,E[y+1]-z),c(T)},C=()=>{document.removeEventListener("mousemove",M),document.removeEventListener("mouseup",C),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",M),document.addEventListener("mouseup",C)},[i,v,c]),b=o.useCallback((y,I,k)=>{if(v>=4)return;const w=k==="left"?I:I+1;t(g=>{const E=vr(g,f).assignments,M=new Map;for(const C of d){const R=E.get(C.tabKey)??0,K=R>=w?R+1:R;K>0&&M.set(C.tabKey,K)}return w>0&&M.set(y,w),M}),c(g=>{const E=g.length===v?[...g]:Go(v),M=E[I]??100/v,C=Math.max(15,M/2),R=Math.max(15,M/2),K=[...E];K[I]=C,K.splice(w,0,R);const z=K.reduce((T,L)=>T+L,0);return K.map(T=>T/z*100)}),n(g=>{const E=Vo(g,w);return E[w]=y,E}),a(g=>{const E=Vo(g,w);return E[w]=[y],E}),r(w)},[v,t,f,d,c,n,a,r]);o.useEffect(()=>{Jp(e,m)||t(m)},[e,m,t]),o.useEffect(()=>{const{mapping:y,usedGroups:I}=x;n(k=>{const w=zo(k,y);return Uo(k,w)?k:w}),a(k=>{const w=zo(k,y);return Uo(k,w)?k:w}),r(k=>{const w=l?0:Zp(k,I,y);return k===w?k:w}),c(k=>{const w=l?[]:eh(k,I,x.groupCount);return Qp(k,w)?k:w})},[x,l,n,a,r,c]);const N=o.useMemo(()=>{const y=Array.from({length:v},()=>[]);for(const I of d){const k=m.get(I.tabKey)??0,w=Math.min(k,v-1);y[w].push(I)}return y},[d,m,v]),A=o.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:u,normalizedGroupAssignments:m,numGroups:v,isSplitMode:S,groupedConvs:N,moveTabToGroup:p,closeGroup:h,handleResizeStart:j,splitTabRelative:b,clearAllSplits:A}}function sh({ides:e,sendDaemonCommand:t}){const r="0.9.26",n=o.useMemo(()=>e.filter(u=>u.type!=="adhdev-daemon"?!1:_c(u,r)).sort((u,x)=>Number(zs(x,r))-Number(zs(u,r))),[r,e]),a=o.useMemo(()=>n.some(u=>zs(u,r)),[r,n]),[i,c]=o.useState(!1),[l,d]=o.useState({}),f=o.useCallback(async u=>{var x,m;d(v=>({...v,[u]:"upgrading"}));try{const v=await t(u,"daemon_upgrade",{});(x=v==null?void 0:v.result)!=null&&x.upgraded||(m=v==null?void 0:v.result)!=null&&m.success?d(S=>({...S,[u]:"done"})):d(S=>({...S,[u]:"error"}))}catch{d(v=>({...v,[u]:"error"}))}},[t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:f}}const Xc=80;function Pr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function rh(e){return{...e,createdAt:Pr(e.createdAt),updatedAt:Pr(e.updatedAt,e.createdAt),lastEventAt:Pr(e.lastEventAt,e.updatedAt||e.createdAt)}}function nh(e){const t=Ca(e);return t==="unknown:"?e.id:t}function ah(e){return[e.type,ac(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function oh(e,t=Xc){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=nh(n),i=r.get(a);if(!i){r.set(a,n);continue}(n.updatedAt>i.updatedAt||n.updatedAt===i.updatedAt&&n.createdAt>i.createdAt)&&r.set(a,n)}return Array.from(r.values()).sort((n,a)=>{const i=a.updatedAt-n.updatedAt;return i!==0?i:a.createdAt-n.createdAt}).slice(0,Math.max(0,t))}function ih(e,t){const r=Date.now(),n=[];for(const a of e){const i=a.sessionId?t.get(a.sessionId):void 0;if(i!=null&&i.surfaceHidden)continue;const c=Qr(a,t),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const d=Pr(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),f=ah({type:l,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(i==null?void 0:i.lastUpdated)||a.lastUpdated});n.push(rh({id:f,dedupKey:f,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:tc(a),preview:pm(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return oh(n)}function ch(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function lh(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=Xc}=e,a=o.useMemo(()=>ih(t,r).slice(0,Math.max(0,n)),[t,r,n]),i=o.useMemo(()=>ch(a),[a]);return{notifications:a,unreadCount:i}}function dh({notifications:e,sendDaemonCommand:t}){const r=o.useCallback(i=>{const c=e.find(d=>d.id===i),l=Math.max(Date.now(),(c==null?void 0:c.updatedAt)||0);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_session_seen",{sessionId:c.sessionId,seenAt:l}).catch(()=>{})},[e,t]),n=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_notification_unread",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]),a=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"delete_notification",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}function tn(...e){const t=new Set,r=[],n=a=>{const i=typeof a=="string"?a.trim():"";if(!i)return;const c=i.toLowerCase();t.has(c)||(t.add(c),r.push(i))};for(const a of e){if(Array.isArray(a)){for(const i of a)n(i);continue}n(a)}return r}function uh(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 sn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=uh(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 mh(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 fh(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function rn(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=fh(n);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(n==null?void 0:n.error)||"Could not browse folder");const i=typeof(a==null?void 0:a.path)=="string"?a.path:r,c=i.includes("\\")?"\\":"/",l=(f,u)=>/^[A-Za-z]:\\?$/.test(f)?`${f.replace(/\\?$/,"\\")}${u}`:f==="/"||f==="\\"?`${c}${u}`:`${f.replace(/[\\/]+$/,"")}${c}${u}`,d=Array.isArray(a==null?void 0:a.files)?a.files.filter(f=>(f==null?void 0:f.type)==="directory"&&typeof(f==null?void 0:f.name)=="string").map(f=>({name:f.name,path:typeof(f==null?void 0:f.path)=="string"&&f.path.trim()?f.path:l(i,f.name)})).sort((f,u)=>f.name.localeCompare(u.name)):[];return{path:i,directories:d}}function ph(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function qo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function hh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function xh({ides:e,conversations:t,onOpenSession:r}){const[n,a]=o.useState(null),i=o.useCallback(c=>{a(c)},[]);return o.useEffect(()=>{if(!n)return;const c=qo(n.workspacePath),l=e.find(f=>{var S,p,h,j;if(!f||f.type==="adhdev-daemon"||ph(f.daemonId||f.id)!==n.machineId||(Qs(f)?"cli":ys(f)?"acp":"ide")!==n.kind||String(f.agentType||f.type||"")!==n.providerType)return!1;if(n.resumeSessionId)return String(f.providerSessionId||"")===n.resumeSessionId;if(c){const b=qo(f.workspace||f.runtimeWorkspaceLabel);return b?b===c:!1}return Number(f.lastUpdated||f._lastUpdate||f.timestamp||((j=(h=(p=(S=f.activeChat)==null?void 0:S.messages)==null?void 0:p.at)==null?void 0:h.call(p,-1))==null?void 0:j.timestamp)||0)>=n.startedAt-5e3});if(!l)return;const d=cc({entrySessionId:l.sessionId,entryInstanceId:l.instanceId,entryRouteId:l.id,conversations:t});d&&(a(null),r(d))},[t,e,r,n]),o.useEffect(()=>{if(!n)return;const c=window.setTimeout(()=>{a(l=>!l||l.startedAt!==n.startedAt?l:null)},45e3);return()=>window.clearTimeout(c)},[n]),{trackPendingLaunch:i}}function bh({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:i}){const c=o.useCallback(async(m,v)=>rn(e,m,v),[e]),l=o.useCallback(async(m,v)=>{if(!v.trim())return{ok:!1,error:"Choose a workspace path first."};try{const S=await e(m,"workspace_add",{path:v.trim()});return S!=null&&S.success?{ok:!0}:{ok:!1,error:(S==null?void 0:S.error)||"Could not save workspace"}}catch(S){return{ok:!1,error:S instanceof Error?S.message:"Could not save workspace"}}},[e]),d=o.useCallback(async(m,v,S)=>{var p;try{const h={ideType:v,enableCdp:!0};(p=S==null?void 0:S.workspacePath)!=null&&p.trim()&&(h.workspace=S.workspacePath.trim());const j=await e(m,"launch_ide",h);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:m,kind:"ide",providerType:v,workspacePath:(S==null?void 0:S.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(h){return{ok:!1,error:h instanceof Error?h.message:"Could not launch IDE"}}},[e,t]),f=o.useCallback(async(m,v,S,p)=>{var j,b,N;const h=Date.now();try{const A={cliType:S};(j=p==null?void 0:p.workspacePath)!=null&&j.trim()?A.dir=p.workspacePath.trim():p!=null&&p.workspaceId&&(A.workspaceId=p.workspaceId),(b=p==null?void 0:p.resumeSessionId)!=null&&b.trim()&&(A.resumeSessionId=p.resumeSessionId.trim()),Array.isArray(p==null?void 0:p.cliArgs)&&p.cliArgs.length>0&&(A.cliArgs=p.cliArgs),(N=p==null?void 0:p.initialModel)!=null&&N.trim()&&(A.initialModel=p.initialModel.trim());const y=await e(m,"launch_cli",A),I=(y==null?void 0:y.result)||y,k=(I==null?void 0:I.sessionId)||(I==null?void 0:I.id);return y!=null&&y.success&&k?(r(k),{ok:!0}):y!=null&&y.success?(t({machineId:m,kind:v,providerType:S,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:h}),{ok:!0}):{ok:!1,error:(y==null?void 0:y.error)||(I==null?void 0:I.error)||`Could not launch ${v.toUpperCase()} session`}}catch(A){return hh(A)?(t({machineId:m,kind:v,providerType:S,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:h}),{ok:!0}):{ok:!1,error:A instanceof Error?A.message:`Could not launch ${v.toUpperCase()} session`}}},[r,e,t]),u=o.useCallback(async(m,v)=>{if(!m||!v)return[];try{const S=await e(m,"list_saved_sessions",{providerType:v,kind:"cli",limit:30}),p=(S==null?void 0:S.result)??S;return Array.isArray(p==null?void 0:p.sessions)?p.sessions:[]}catch(S){return console.error("List saved sessions failed",S),[]}},[e]),x=o.useCallback(async m=>{await Uc({conversation:n,mode:m,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:i})},[n,a,e,i]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:l,handleLaunchMachineIde:d,handleLaunchMachineProvider:f,handleListMachineSavedSessions:u,setActiveCliViewMode:x}}function gh(e){switch(e){case"notification-open":case"toast-open":case"conversation-open":case"requested-tab":case"dockview-shortcut":case"dockview-focus":case"dockview-move":case"dockview-split":return!0;case"stored-layout-restore":case"passive-tab-sync":return!1;default:return!1}}function yh(e,t,r=Date.now()){return!e||!gh(t)?null:{tabKey:e,nonce:r}}function vh({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:i,setSearchParams:c}){const[l,d]=o.useState(null),[f,u]=o.useState(null),x=o.useMemo(()=>{var h,j;if(!e){if(l){const b=t.find(N=>N.tabKey===l);if(b)return b}return r[0]}const p=n[a];if(p){const b=t.find(N=>N.tabKey===p);if(b)return b}return((h=i[a])==null?void 0:h[0])||((j=i[0])==null?void 0:j[0])},[t,l,a,n,i,e,r]),m=o.useCallback(p=>{d(p)},[]),v=o.useCallback(p=>{d(p.tabKey),c(h=>{const j=new URLSearchParams(h),b=xm(p);return b?j.set("activeTab",b):j.delete("activeTab"),j},{replace:!0})},[c]),S=o.useCallback((p,h)=>{const j=yh(p,h);j&&u(j)},[]);return{activeConv:x,openDesktopConversation:v,requestScrollToBottom:S,scrollToBottomRequest:f,setDesktopActiveTab:m}}function wh({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:i,setToasts:c,setClearedTabs:l,setSearchParams:d}){var T;const[f,u]=o.useState(!1),[x,m]=o.useState([]),[v,S]=o.useState(()=>ht()),[p,h]=o.useState(!1),[j,b]=o.useState(null),N=o.useRef(null),A=o.useMemo(()=>r||t||e,[e,r,t]),y=!!A&&Ze(A)&&!Xe(A),I=o.useMemo(()=>{if(!A||!y)return null;const L=A.daemonId||A.routeId||"",Y=Kt(A);return`${L}:${Y}`},[A,y]),{isCreatingChat:k,isRefreshingHistory:w,handleSwitchSession:g,handleNewChat:E,handleRefreshHistory:M}=Yc({sendDaemonCommand:a,activeConv:A,chats:(T=n.find(L=>L.id===(A==null?void 0:A.routeId)))==null?void 0:T.chats,updateRouteChats:i,setToasts:c,setClearedTabs:l}),C=o.useCallback(()=>{u(!0)},[]),R=o.useCallback(()=>{u(!1)},[]),K=o.useCallback(async()=>{if(!(!A||!y||p)){h(!0);try{const L=A.daemonId||A.routeId,Y=Kt(A),O=await a(L,"list_saved_sessions",{agentType:Y,providerType:Y,kind:"cli",limit:50}),D=(O==null?void 0:O.result)??O;m(Array.isArray(D==null?void 0:D.sessions)?D.sessions:[])}catch(L){console.error("Refresh saved sessions failed",L),m([])}finally{h(!1)}}},[A,p,y,a]);o.useEffect(()=>{if(!f){N.current=null;return}if(!y){N.current=null,m([]),h(!1);return}!I||p||N.current!==I&&(N.current=I,K())},[K,f,p,y,I]);const z=o.useCallback(async L=>{if(!A||!y||!L.providerSessionId||!L.workspace)return;const Y=A.daemonId||A.routeId,O=Kt(A);try{b(L.providerSessionId);const D=await a(Y,"launch_cli",{cliType:O,dir:L.workspace,resumeSessionId:L.providerSessionId,initialModel:qi(L.summaryMetadata,"model",{preferShortValue:!0})||void 0}),W=(D==null?void 0:D.result)??D,Q=typeof(W==null?void 0:W.sessionId)=="string"?W.sessionId:typeof(W==null?void 0:W.id)=="string"?W.id:"";Q&&d(be=>{const pe=new URLSearchParams(be);return pe.set("activeTab",Q),pe},{replace:!0}),R()}catch(D){console.error("Resume saved session failed",D)}finally{b(null)}},[R,A,y,a,d]);return{historyModalOpen:f,openHistoryModal:C,closeHistoryModal:R,historyTargetConv:A,isSavedSessionHistoryTarget:y,isHistoryCreatingChat:k,isHistoryRefreshingHistory:w,handleHistorySwitchSession:g,handleHistoryNewChat:E,handleHistoryRefresh:M,savedHistorySessions:x,savedHistoryFilters:v,setSavedHistoryFilters:S,isSavedHistoryLoading:p,resumingSavedHistorySessionId:j,handleRefreshSavedHistory:K,handleResumeSavedHistorySession:z}}function jh({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[d,f]=o.useState(null),[u,x]=o.useState(null),m=o.useMemo(()=>{if(e||!n)return null;const j=l(n);return j&&!Ze(j)&&!Xe(j)?j:null},[e,n,l]),v=o.useMemo(()=>{const j=d==null?void 0:d.routeId;if(!j)return null;const b=d!=null&&d.tabKey?i.find(N=>N.tabKey===d.tabKey):a?i.find(N=>N.tabKey===a):null;return(b==null?void 0:b.routeId)===j?b:_t(i,j)},[i,d,a]),S=o.useMemo(()=>{if(v)return c.find(j=>j.id===v.routeId)},[c,v]);o.useEffect(()=>{m&&(f({routeId:m.routeId,tabKey:Co(m)}),x(m),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,m]);const p=o.useCallback(j=>{j&&(f({routeId:j.routeId,tabKey:Co(j)}),x(j))},[]),h=o.useCallback(()=>{f(null),x(null)},[]);return{remoteDialogConv:v,remoteDialogIdeEntry:S,remoteDialogActiveConv:u,setRemoteDialogActiveConv:x,openRemoteDialog:p,closeRemoteDialog:h}}function kh({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l,activeConv:d,sendDaemonCommand:f}){const{remoteDialogConv:u,remoteDialogIdeEntry:x,remoteDialogActiveConv:m,setRemoteDialogActiveConv:v,openRemoteDialog:S,closeRemoteDialog:p}=jh({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}),[h,j]=o.useState(!1),[b,N]=o.useState(null),A=o.useCallback(async k=>{const w=k||d;!w||!Ze(w)&&!Xe(w)||(N(w),j(!0))},[d]),y=o.useCallback(()=>{j(!1),N(null)},[]),I=o.useCallback(async k=>{const w=b||d;if(!w||!Ze(w)&&!Xe(w)){y();return}j(!1);try{const g=Kt(w),E=w.routeId||w.daemonId||"";await f(E,"stop_cli",{cliType:g,targetSessionId:w.sessionId,mode:k})}catch(g){console.error("Stop CLI failed:",g)}finally{N(null)}},[d,y,b,f]);return{remoteDialogConv:u,remoteDialogIdeEntry:x,remoteDialogActiveConv:m,setRemoteDialogActiveConv:v,openRemoteDialog:S,closeRemoteDialog:p,cliStopDialogOpen:h,cliStopTargetConv:b,requestCliStop:A,cancelCliStop:y,confirmCliStop:I}}function Jc(){return"select_session"}function Sh(){return"open_panel"}function Nh({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function Ch(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function Yo(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function Xo(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function za(e){return e instanceof Error?e.message:String(e||"")}function Jo(e){const t=za(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Qo(e,t){const r=za(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function nn({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,i]=o.useState(!1),[c,l]=o.useState(!1),[d,f]=o.useState(null),u=o.useRef(!1),x=o.useRef(null);o.useEffect(()=>{f(null)},[t==null?void 0:t.tabKey]);const m=o.useCallback(async h=>{if(!t)return!1;const j=h.trim(),b=Aa(t);if(Nh({hasMessage:!!j,blockedMessage:b,sendInFlight:u.current}))return b&&f(b),!1;const N=Date.now(),A={tabKey:t.tabKey,message:j,timestamp:N};if(Ch(x.current,A))return f(null),!0;u.current=!0,l(!0),f(null),x.current=A;try{const y=Zs(t);if(!y)return x.current=Yo(x.current,A),f("Unable to send message right now."),!1;const I=await e(y,"send_chat",{message:j,...js(t)}),k=Xo(I);if(k!=null&&k.deduplicated)return f(null),!0;if((k==null?void 0:k.sent)===!1)throw new Error((k==null?void 0:k.error)||"Send failed");if((k==null?void 0:k.success)===!1)throw new Error((k==null?void 0:k.error)||"Send failed");return f(null),!0}catch(y){const I=za(y);return I.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",I):console.warn("Send blocked/failed",y),x.current=Yo(x.current,A),f(Dm(y)),!1}finally{u.current=!1,l(!1)}},[t,e]),v=o.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(h){console.error("Relaunch failed",h)}},[t,e]),S=o.useCallback(async h=>{if(t)try{const b=(t.modalButtons||[]).indexOf(h),N=h.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),A=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(N),y=Zs(t);if(!y)return;const I=await e(y,"resolve_action",{button:h,action:A?"approve":"reject",...b>=0&&{buttonIndex:b},...js(t)}),k=Xo(I);k.success||r(w=>[...w,{routeId:t.tabKey,text:Qo(h,k==null?void 0:k.error),timestamp:Date.now()}])}catch(j){Jo(j)||console.error("[ModalButton] Error:",j),r(b=>[...b,{routeId:t.tabKey,text:Jo(j)?Qo(h,j):`❌ **${h}** error`,timestamp:Date.now()}])}},[t,e,r]),p=o.useCallback(async()=>{if(!(!t||a)){i(!0);try{await e(t.routeId,Sh(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(h){console.error("Focus agent failed",h)}finally{i(!1)}}},[t,a,e]);return{isSendingChat:c,sendFeedbackMessage:d,isFocusingAgent:a,handleSendChat:m,handleRelaunch:v,handleModalButton:S,handleFocusAgent:p}}function In(e,t=!0){return(e??!0)&&t}const Va=o.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u=null,handleFocusAgent:x,isFocusingAgent:m,actionLogs:v,userName:S,scrollToBottomRequestNonce:p,isInputActive:h=!0,isVisible:j=!0}){const[b,N]=o.useState(n),A=o.useRef(n);o.useEffect(()=>{const C=A.current;if(A.current=n,!n){N(!1);return}if(C){N(!0);return}N(!1);let R=0,K=0;return R=window.requestAnimationFrame(()=>{K=window.requestAnimationFrame(()=>{N(!0)})}),()=>{window.cancelAnimationFrame(R),window.cancelAnimationFrame(K)}},[n]);const y=n&&b,I=!n||!b,k=In(j,n),w=In(j,I),g=In(j),E=Kc(t),M=E.status||E.modalMessage||E.modalButtons?{...t,...E.status?{status:E.status}:{},...E.modalMessage!==void 0?{modalMessage:E.modalMessage}:{},...E.modalButtons!==void 0?{modalButtons:E.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(Fi,{activeConv:M,onModalButton:c}),M.transport!=="pty"&&M.transport!=="acp"&&M.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(Xs,{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:l,children:"Relaunch with CDP"})]})}):null,M.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:y?"visible":"hidden",pointerEvents:y?"auto":"none"},children:s.jsx(pf,{activeConv:M,clearToken:r,terminalRef:i,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u,isVisible:k,isInputActive:h&&k})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:I?"visible":"hidden",pointerEvents:I?"auto":"none"},children:s.jsx(na,{activeConv:M,ideEntry:a,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u,handleFocusAgent:x,isFocusingAgent:m,actionLogs:v,userName:S,scrollToBottomRequestNonce:p,isInputActive:h&&w,isVisible:w})})]}):s.jsx(na,{activeConv:M,ideEntry:a,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u,handleFocusAgent:x,isFocusingAgent:m,actionLogs:v,userName:S,scrollToBottomRequestNonce:p,isInputActive:h&&g,isVisible:g})]})},(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 Ih({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:d,onBack:f,onOpenNativeConversation:u,onOpenMachine:x,onOpenHistory:m,onOpenRemote:v,onHideConversation:S,onStopCli:p,cliViewMode:h,onSetCliViewMode:j,handleSendChat:b,handleFocusAgent:N,handleModalButton:A,handleRelaunch:y}){const I=o.useRef(null),k=Ze(e)&&!t,w=k&&h==="terminal",g=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${g} 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(xa,{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:nt(e)}),s.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:s.jsx(lc,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>x(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[k&&h&&s.jsx(Ra,{mode:h,onChange:j,compact:!0}),k&&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(vt,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>m(e),type:"button",children:s.jsx(ba,{size:14})}),!t&&!k&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>v(e),type:"button",children:s.jsx(Nt,{size:14})}),S&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(e),type:"button",title:"Close chat",children:s.jsx(vt,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(Va,{activeConv:e,clearToken:0,isCliTerminal:w,ideEntry:n,terminalRef:I,handleModalButton:A,handleRelaunch:y,handleSendChat:b,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:N,isFocusingAgent:d,actionLogs:a,userName:i})})]})}const Mn={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 Mh(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Qc(){const[e,t]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{t(Mh())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(Mn[c].cmd).catch(()=>{}),i(!0),setTimeout(()=>i(!1),2e3)},[c]);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:l,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:Mn[c].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Mn[c].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 Zc({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Nt},{key:"chats",label:"Chats",icon:Ut}];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:i})=>{const c=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 ${c?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(n),type:"button","aria-pressed":c,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(i,{size:15})}),s.jsx("span",{children:a})]},n)})})})}function wr({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 hs({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 Bs({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 jr({item:e,type:t,getAvatarText:r,onOpenConversation:n}){const a=t==="needs_attention"||t==="task_complete",i=t==="working",c=t==="earlier",l=t==="task_complete",{isReconnecting:d,isConnecting:f}=Ts(e.conversation),u=nt(e.conversation),x=us(e.conversation),m=bc(e.conversation,{requiresAction:t==="needs_attention"}),v=a?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":i?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",S=a?"bg-accent-primary shadow-glow":i?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":c?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",p=c?"text-text-secondary":"text-text-primary",h=c?"text-text-muted":"text-text-secondary",j=c?"text-text-secondary opacity-80":"text-text-muted",b=c?"text-text-muted opacity-80":"text-text-muted",N="text-[color:var(--status-warning)]";return s.jsxs("button",{className:`group flex items-start gap-3.5 px-4 py-3.5 w-full text-left relative overflow-hidden transition-colors active:scale-[0.995] ${v}`,onClick:()=>n(e.conversation),type:"button",children:[a||i?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.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${S}`,style:a?{color:"var(--accent-on-primary)"}:void 0,children:r(u)}),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 truncate tracking-tight ${p}`,children:u}),!i&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${b}`,children:Hi(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${h}`,children:[x,d?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${N} animate-pulse`,children:"Reconnecting…"})]}):f?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):m==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:N,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${j}`,children:e.preview})]}),a&&!l&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),l&&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"}),i&&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 Zo({size:e=32,label:t}){return s.jsxs("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}}),t&&s.jsx("div",{className:"text-xs font-semibold text-accent-primary-light tracking-tight",children:t})]})}function Ah({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:d,onShowConversation:f,onShowAllHidden:u,onOpenNewSession:x,onOpenMachine:m,onOpenSettings:v,onSectionChange:S,wsStatus:p="connected",isStandalone:h=!1}){const j=p==="disconnected"||p==="reconnecting"||p==="offline"||p==="auth_failed",b=c.length>0,N=t.length>0||r.length>0||n.length>0||a.length>0,A=e==="machines"?"Machines":"Chats",y=h?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",I=h?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]";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 ${y}`,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:A}),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(Xr,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:v,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(Yr,{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] ${I}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:j?s.jsx(Bs,{icon:s.jsx(Zo,{label:"Reconnecting…"}),title:"Connecting to server",subtitle:p==="offline"?"Your device appears to be offline. Waiting for network…":p==="auth_failed"?"Session expired. Please log in again.":"Establishing connection to the server. This usually takes a moment."}):c.length===0?s.jsx(Bs,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:h?"Waiting for your daemon":"Connect your machines",subtitle:h?"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:!h&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(Qc,{})})}):s.jsx(hs,{children:c.map((k,w)=>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] ${w>0?"border-t border-border-subtle/70":""}`,onClick:()=>m(k.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:l(k.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:k.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:k.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[k.unread," new"]}):k.total>0?`${k.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:k.subtitle}),k.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[k.total," chat",k.total!==1?"s":"",k.unread>0?` · ${k.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},k.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(wr,{title:"Needs attention",className:"mb-0"}),s.jsx(hs,{children:t.map((k,w)=>s.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"needs_attention",getAvatarText:l,onOpenConversation:d})},k.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(wr,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(hs,{children:r.map((k,w)=>s.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"task_complete",getAvatarText:l,onOpenConversation:d})},k.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(wr,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(hs,{children:n.map((k,w)=>s.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"working",getAvatarText:l,onOpenConversation:d})},k.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(wr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(hs,{children:a.map((k,w)=>s.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"earlier",getAvatarText:l,onOpenConversation:d})},k.conversation.tabKey))}):N?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):j?s.jsx(Bs,{icon:s.jsx(Zo,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):b?s.jsx(Bs,{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(Ut,{size:20})}),title:"No conversations yet",subtitle:vc,children:x&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:x,"aria-label":$t,title:$t,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:$t})]})}):s.jsx(Bs,{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"&&i.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsxs("div",{className:"mx-1 mt-4 mb-1 flex items-center justify-between gap-2 px-1 py-1 text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:[s.jsx("span",{children:"Hidden"}),s.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:u,children:"Restore all"})]}),s.jsx(hs,{className:"bg-bg-secondary/25",children:i.map((k,w)=>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] opacity-50 saturate-0 ${w>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(k),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-bg-primary border border-border-subtle text-text-secondary",children:l(nt(k))}),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:nt(k)}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:us(k)}),s.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},k.tabKey))})]})]}),e==="chats"&&x&&N&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:x,"aria-label":$t,title:$t,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"})]})}),s.jsx(Zc,{section:e,onSectionChange:S})]})}function Th(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 el(e){const t=[e.workspace||"Workspace unknown"],r=ds(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=Th(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function an({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:d,onConfirm:f}){const[u,x]=o.useState(r);o.useEffect(()=>{x(r)},[r]);const m=mh(r),v=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:l,"aria-label":"Close folder browser",children:s.jsx(vt,{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:()=>{!m||a||d(m)},disabled:!m||a,children:[s.jsx(xa,{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:S=>x(S.target.value),onKeyDown:S=>{S.key!=="Enter"||!v||a||(S.preventDefault(),d(v))},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:()=>{!v||a||d(v)},disabled:!v||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…"}):i?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):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(S=>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(S.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(Ns,{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:S.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:S.path})]})]},S.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:l,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>f(v||r),disabled:!v&&!r||a,children:c})]})]})})}function Ga({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:d=!1,showArgsInput:f,argsValue:u,onArgsChange:x,showModelInput:m,modelValue:v,onModelChange:S,historyProviderNode:p,onConfirm:h,onCancel:j}){const b=n==null?void 0:n.find(N=>N.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:j,"aria-label":"Close launch confirmation",children:s.jsx(vt,{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&&i&&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:N=>i(N.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(N=>s.jsx("option",{value:N.key,children:N.label},N.key))}),(b==null?void 0:b.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:b.description})]}),p,r.map(N=>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:N.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:N.value})]},`${N.label}:${N.value}`)),m&&S&&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:v||"",onChange:N=>S(N.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})]}),f&&x&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:u||"",onChange:N=>x(N.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:j,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:h,disabled:d,children:[s.jsx(ya,{size:14}),d?l:c]})]})]})})}function ei(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function os(e){const{machine:t,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,i=[];a&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const d of t.workspaces||[])i.push({key:`saved:${d.id}`,label:`${d.id===t.defaultWorkspaceId?"⭐ ":""}${ei(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const c=(r==null?void 0:r.trim())||"",l=c?(t.workspaces||[]).find(d=>d.path===c):null;if(c&&!l&&i.push({key:`custom:${c}`,label:ei(c),description:c,workspaceId:null,workspacePath:c}),n){const d=`saved:${n}`;if(i.some(f=>f.key===d))return{options:i,selectedKey:d}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function Lh(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Rh(e){return[Lh(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Ph(e){return e.lastLaunchedAt?Jr(e.lastLaunchedAt):""}function tl(e){return{metaText:Rh(e),updatedLabel:Ph(e)}}function An(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function _h({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var dt,mt,ot,ut;const c=ar(),[l,d]=o.useState(!1),f=(((dt=e.detectedIdes)==null?void 0:dt.length)||0)>0,u=o.useMemo(()=>(e.workspaces||[]).map(Ie=>({id:Ie.id,path:Ie.path,label:Ie.label})),[e]),x=e.defaultWorkspaceId||null,[m,v]=o.useState(x||((mt=u[0])==null?void 0:mt.id)||""),[S,p]=o.useState(""),[h,j]=o.useState(""),[b,N]=o.useState([]),[A,y]=o.useState(!1),[I,k]=o.useState(""),[w,g]=o.useState(!1),[E,M]=o.useState(An(f,t.length,r.length)),C=o.useRef(null),[R,K]=o.useState(null),z=o.useRef("__home__"),[T,L]=o.useState("__home__"),[Y,O]=o.useState(""),[D,W]=o.useState(""),[Q,be]=o.useState(""),[pe,ue]=o.useState([]),[we,ye]=o.useState(()=>ht().textQuery),[ve,V]=o.useState(()=>ht().workspaceQuery),[H,Z]=o.useState(()=>ht().modelQuery),[me,ne]=o.useState(()=>ht().resumableOnly),[fe,se]=o.useState(()=>ht().sortMode),[xe,ie]=o.useState(!1),[ce,ae]=o.useState(!1),X=o.useRef(null),J=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const oe=m==="__custom__"?S.trim():((ot=u.find(Ie=>Ie.id===m))==null?void 0:ot.path)||"",P=m==="__custom__"&&!!oe&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),G=m!=="__custom__"&&((ut=u.find(Ie=>Ie.id===m))==null?void 0:ut.path)||"",U=o.useMemo(()=>(e.recentLaunches||[]).map(Ie=>Ie.workspace),[e]),de=o.useCallback(async Ie=>{y(!0),k("");try{const $e=await a(Ie);j($e.path),p($e.path),N($e.directories)}catch($e){k($e instanceof Error?$e.message:"Could not load folder")}finally{y(!1)}},[a]),Ne=o.useCallback(()=>{var $e;v("__custom__"),g(!0);const Ie=sn(e.platform,tn(S.trim(),G,U,e.defaultWorkspacePath,($e=u.find(Ue=>Ue.id===x))==null?void 0:$e.path,u.map(Ue=>Ue.path)));de(Ie)},[S,x,de,U,G,e.platform,u]),_e=o.useCallback(Ie=>{if(Ie!=null&&Ie.workspaceId){v(Ie.workspaceId),p("");return}if(Ie!=null&&Ie.workspacePath){v("__custom__"),p(Ie.workspacePath);return}v(""),p("")},[]),ge=o.useCallback(Ie=>{if(v(Ie),Ie==="__custom__"){Ne();return}p("")},[Ne]),Be=o.useCallback(Ie=>{v("__custom__"),p(Ie)},[]),Oe=o.useCallback((Ie,$e)=>{C.current=$e,z.current=Ie.selectedWorkspaceKey||"__home__",L(Ie.selectedWorkspaceKey||"__home__"),O(Ie.initialArgs||""),W(Ie.initialModel||""),be(""),ue([]);const Ue=Ie.providerType?`${e.id}:${Ie.providerType}`:null;if(wf(J.current,Ue)){const Ve=ht();ye(Ve.textQuery),V(Ve.workspaceQuery),Z(Ve.modelQuery),ne(Ve.resumableOnly),se(Ve.sortMode)}J.current=Ue,K(Ie),Ie.providerType&&i&&(ie(!0),i(Ie.providerType).then(Ve=>ue(Ve||[])).catch(Ve=>console.warn("Failed to load saved sessions",Ve)).finally(()=>ie(!1)))},[i,e.id]),Ke=o.useMemo(()=>wc(pe,{textQuery:we,workspaceQuery:ve,modelQuery:H,resumableOnly:me,sortMode:fe}),[H,me,pe,fe,we,ve]);o.useEffect(()=>{Q&&(Ke.some(Ie=>Ie.providerSessionId===Q)||be(""))},[Ke,Q]);const et=o.useCallback(()=>{C.current&&(ae(!0),C.current().finally(()=>{C.current=null,ae(!1),K(null)}))},[]),Je=o.useCallback(()=>{C.current=null,K(null)},[]),at=o.useCallback(Ie=>{z.current=Ie,L(Ie)},[]);return o.useEffect(()=>{var Ie;X.current!==e.id&&(X.current=e.id,v(x||((Ie=u[0])==null?void 0:Ie.id)||"__custom__"),p(""),j(""),N([]),k(""),g(!1),ye(ht().textQuery),V(ht().workspaceQuery),Z(ht().modelQuery),ne(ht().resumableOnly),se(ht().sortMode),J.current=null,M(An(f,t.length,r.length)))},[r.length,t.length,x,f,e.id,u]),o.useEffect(()=>{var Ie;m!=="__custom__"&&(m&&u.some($e=>$e.id===m)||v(x||((Ie=u[0])==null?void 0:Ie.id)||"__custom__"))},[x,m,u]),o.useEffect(()=>{E==="ide"&&f||E==="cli"&&t.length>0||E==="acp"&&r.length>0||M(An(f,t.length,r.length))},[E,r.length,t.length,f]),{showAllRecent:l,setShowAllRecent:d,hasIdeOptions:f,workspaceRows:u,defaultWorkspaceId:x,workspaceChoice:m,customWorkspacePath:S,browseCurrentPath:h,browseDirectories:b,browseBusy:A,browseError:I,browseDialogOpen:w,activeLauncherKind:E,launchConfirm:R,launchConfirmWorkspaceKeyRef:z,launchConfirmWorkspaceKey:T,launchConfirmArgs:Y,launchConfirmModel:D,launchConfirmResumeId:Q,launchConfirmSavedSessions:pe,launchConfirmTextFilter:we,launchConfirmWorkspaceFilter:ve,launchConfirmModelFilter:H,launchConfirmResumableOnly:me,launchConfirmSortMode:fe,filteredLaunchConfirmSavedSessions:Ke,launchConfirmSessionsLoading:xe,launchConfirmBusy:ce,resolvedWorkspacePath:oe,canCreateMissingWorkspace:P,openBrowseDialog:Ne,loadBrowsePath:de,handleWorkspaceChoiceChange:ge,chooseCustomWorkspacePath:Be,setCustomWorkspacePath:p,setBrowseDialogOpen:g,setActiveLauncherKind:M,openLaunchConfirm:Oe,handleConfirmLaunch:et,closeLaunchConfirm:Je,setWorkspaceSelectionFromOption:_e,setLaunchConfirmWorkspaceKeyAndSync:at,setLaunchConfirmArgs:O,setLaunchConfirmModel:W,setLaunchConfirmResumeId:be,setLaunchConfirmTextFilter:ye,setLaunchConfirmWorkspaceFilter:V,setLaunchConfirmModelFilter:Z,setLaunchConfirmResumableOnly:ne,setLaunchConfirmSortMode:se}}function Dh({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:d,section:f,showBottomNav:u,onBack:x,onSectionChange:m,onOpenConversation:v,onOpenRecent:S,onOpenMachineDetails:p,onMachineUpgrade:h,onLaunchDetectedIde:j,onAddWorkspace:b,onBrowseDirectory:N,onLaunchWorkspaceProvider:A,onListSavedSessions:y}){const I=T=>T==="ide"?"IDE":T==="cli"?"CLI":"ACP",k=r.slice(0,4),w=t.slice(0,3),g=_h({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:N,onListSavedSessions:y}),E=o.useMemo(()=>k.map(T=>{const{metaText:L,updatedLabel:Y}=tl(T);return{key:`recent-launch:${T.id}`,primary:T.label,secondary:L,updatedLabel:Y,onClick:()=>{const{options:O,selectedKey:D}=os({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspacePath:T.workspace});g.openLaunchConfirm({title:T.kind==="ide"?ss("restart-ide",T.label):T.providerSessionId?Da(T.label):ss("start-fresh",T.label),description:T.kind==="ide"?rs("restart-ide"):T.providerSessionId?Ea():rs("start-fresh"),confirmLabel:T.kind==="ide"?Is("restart-ide"):T.providerSessionId?Ur(!0):Is("start-fresh"),busyLabel:T.kind==="ide"?Ms("restart-ide"):T.providerSessionId?Pa(!0):Ms("start-fresh"),workspaceOptions:O,selectedWorkspaceKey:D,details:[{label:"Mode",value:I(T.kind)},...T.providerType?[{label:"Provider",value:T.providerType}]:[]]},async()=>{const W=O.find(Q=>Q.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(W),await S({...T,workspace:(W==null?void 0:W.workspacePath)??null})})}}}),[g,S,k]),M=o.useMemo(()=>w.map(T=>({key:`recent-chat:${T.conversation.tabKey}`,primary:nt(T.conversation),secondary:df(T.conversation,{timestampLabel:T.timestamp?Hi(T.timestamp):null}),unread:T.unread,onClick:()=>v(T.conversation)})),[v,w]),C=g.showAllRecent?E:E.slice(0,4),R=E.length>0,K=M.length>0,z=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 ${z} 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:x,type:"button","aria-label":"Back",children:s.jsx(xa,{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:At(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:[K&&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:M.map(T=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${T.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:T.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:T.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:T.secondary})]},T.key))})]}),R&&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:C.map(T=>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:T.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:T.primary}),T.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:T.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:T.secondary})]},T.key))}),E.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:()=>g.setShowAllRecent(T=>!T),children:g.showAllRecent?"Show fewer":`Show ${E.length-4} more`})})]}),(g.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:g.workspaceChoice,onChange:T=>g.handleWorkspaceChoiceChange(T.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:g.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[g.workspaceRows.map(T=>s.jsxs("option",{value:T.id,children:[T.id===g.defaultWorkspaceId?"⭐ ":"",Zr(T.path,T.label)||T.path]},T.id)),s.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):s.jsx("option",{value:"__custom__",children:"Select workspace…"})}),g.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(Ns,{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:g.resolvedWorkspacePath||g.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:g.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:()=>{g.resolvedWorkspacePath&&b(g.resolvedWorkspacePath)},disabled:!g.resolvedWorkspacePath||g.browseBusy,children:"Save as workspace"})]})]}),g.resolvedWorkspacePath&&s.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:g.resolvedWorkspacePath})]})}),s.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[g.hasIdeOptions&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${g.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:()=>g.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${g.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:()=>g.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${g.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:()=>g.setActiveLauncherKind("acp"),children:"ACP"})]}),g.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:g.activeLauncherKind==="ide"?"Choose an IDE":g.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),s.jsx("div",{className:"grid grid-cols-1 gap-2",children:g.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(T=>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:L,selectedKey:Y}=os({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspaceId:g.workspaceChoice!=="__custom__"?g.workspaceChoice:null,currentWorkspacePath:g.resolvedWorkspacePath});g.openLaunchConfirm({title:`Launch ${T.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:L,selectedWorkspaceKey:Y,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:T.name}]},async()=>{const O=L.find(D=>D.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(O),j(T.type,{workspacePath:(O==null?void 0:O.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:T.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:g.resolvedWorkspacePath||"Use selected workspace"})]},T.type)):(g.activeLauncherKind==="cli"?n:a).map(T=>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 L=g.activeLauncherKind==="cli"?"cli":"acp",{options:Y,selectedKey:O}=os({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspaceId:g.workspaceChoice!=="__custom__"?g.workspaceChoice:null,currentWorkspacePath:g.resolvedWorkspacePath});g.openLaunchConfirm({title:`Launch ${T.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${L.toUpperCase()}`,workspaceOptions:Y,selectedWorkspaceKey:O,details:[{label:"Mode",value:L.toUpperCase()},{label:"Provider",value:T.displayName}],showArgsInput:!0,showModelInput:L==="acp",initialArgs:"",initialModel:"",providerType:T.type},async()=>{const D=Y.find(W=>W.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(D),A(L,T.type,{workspaceId:(D==null?void 0:D.workspaceId)??null,workspacePath:(D==null?void 0:D.workspacePath)??null,args:g.launchConfirmArgs,model:g.launchConfirmModel,resumeSessionId:g.launchConfirmResumeId||null})})},children:[s.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[T.icon?`${T.icon} `:"",T.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:g.resolvedWorkspacePath||"Use selected workspace"})]},T.type))})]}),l.message&&s.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${l.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[l.message,g.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:()=>b(g.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:[i&&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:h,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),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"})]})]})]})]}),g.browseDialogOpen&&s.jsx(an,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:g.browseCurrentPath,directories:g.browseDirectories,busy:g.browseBusy,error:g.browseError,confirmLabel:"Use this folder",onClose:()=>g.setBrowseDialogOpen(!1),onNavigate:T=>{g.loadBrowsePath(T)},onConfirm:T=>{g.chooseCustomWorkspacePath(T),g.setBrowseDialogOpen(!1)}}),g.launchConfirm&&s.jsx(Ga,{title:g.launchConfirm.title,description:g.launchConfirm.description,details:g.launchConfirm.details,workspaceOptions:g.launchConfirm.workspaceOptions,selectedWorkspaceKey:g.launchConfirmWorkspaceKey,onWorkspaceChange:g.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:g.launchConfirm.providerType?Ur(!!g.launchConfirmResumeId):g.launchConfirm.confirmLabel,busyLabel:g.launchConfirm.providerType?void 0:g.launchConfirm.busyLabel,busy:g.launchConfirmBusy,showArgsInput:g.launchConfirm.showArgsInput,argsValue:g.launchConfirmArgs,onArgsChange:g.setLaunchConfirmArgs,showModelInput:g.launchConfirm.showModelInput,modelValue:g.launchConfirmModel,onModelChange:g.setLaunchConfirmModel,historyProviderNode:g.launchConfirm.providerType&&(g.launchConfirmSessionsLoading||g.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"}),g.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:_a()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:g.launchConfirmTextFilter,onChange:T=>g.setLaunchConfirmTextFilter(T.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:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:g.launchConfirmWorkspaceFilter,onChange:T=>g.setLaunchConfirmWorkspaceFilter(T.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:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:g.launchConfirmModelFilter,onChange:T=>g.setLaunchConfirmModelFilter(T.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:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),s.jsxs("select",{value:g.launchConfirmSortMode,onChange:T=>g.setLaunchConfirmSortMode(T.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:g.launchConfirmBusy||g.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:g.launchConfirmResumableOnly,onChange:T=>g.setLaunchConfirmResumableOnly(T.target.checked),disabled:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:g.launchConfirmResumeId,onChange:T=>g.setLaunchConfirmResumeId(T.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:g.launchConfirmBusy||g.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Sf()}),g.filteredLaunchConfirmSavedSessions.map(T=>s.jsxs("option",{value:T.providerSessionId,disabled:!T.canResume,children:[T.title||T.providerSessionId," ",T.canResume?"":"(workspace missing)"]},T.providerSessionId))]}),!g.launchConfirmSessionsLoading&&g.launchConfirmSavedSessions.length>0&&g.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),g.launchConfirmResumeId&&(()=>{const T=g.filteredLaunchConfirmSavedSessions.find(Y=>Y.providerSessionId===g.launchConfirmResumeId);if(!T)return null;const L=el(T);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:L.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:L.providerSessionId}),s.jsx("div",{className:"mt-1",children:L.metaLine}),L.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:L.updatedLabel}),L.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:L.preview})]})})()]}),onConfirm:g.handleConfirmLaunch,onCancel:g.closeLaunchConfirm}),u&&s.jsx(Zc,{section:f,onSectionChange:m})]})}function Eh(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 $h(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:ds(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 c,l,d,f,u;const a=Qs(n)?"cli":ys(n)?"acp":"ide",i=ds(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(Qs(n)?n.cliName||n.type:ys(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:ys(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((u=(f=(d=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:d.at)==null?void 0:f.call(d,-1))==null?void 0:u.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function Bh(e,t){const r=new Map;for(const n of t){const a=fs(n.conversation),i=r.get(a);i?i.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],i=[...a].sort((x,m)=>m.timestamp-x.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=Jn(n),d=a.filter(x=>x.unread||x.requiresAction).length,f=Eh(n),u=[n.platform||"machine",f].filter(Boolean);return{id:n.id,label:At(n,{fallbackId:n.id}),subtitle:u.join(" · "),unread:d,total:a.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?uf(c):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((n,a)=>{const i=n.latestTimestamp||n.fallbackActivityAt||0,c=a.latestTimestamp||a.fallbackActivityAt||0;return c!==i?c-i:n.label.localeCompare(a.label)})}function Kh(e){return e==="chat"}function kr(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 Oh({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:f,requestedMachineId:u,onRequestedMachineConsumed:x,requestedMobileSection:m,onRequestedMobileSectionConsumed:v,setSelectedTabKey:S,setScreen:p,setSelectedMachineId:h,setSection:j,setMachineBackTarget:b,resetMachineAction:N}){const A=o.useRef(null),y=o.useCallback(I=>{if(!(I!=null&&I.sessionId))return;const k=Or(I,c),w=Math.max(Date.now(),es(I),k.lastUpdated||0);kr("mark_read:start",{tabKey:I.tabKey,sessionId:I.sessionId,displayPrimary:nt(I),inboxBucket:k.inboxBucket,unread:k.unread,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,activityAt:es(I),readAt:w}),l(fs(I)||I.routeId,"mark_session_seen",{sessionId:I.sessionId,seenAt:w}).then(g=>{kr("mark_read:result",{tabKey:I.tabKey,sessionId:I.sessionId,result:g})}).catch(g=>{kr("mark_read:error",{tabKey:I.tabKey,sessionId:I.sessionId,error:g instanceof Error?g.message:String(g)})})},[c,l]);return o.useEffect(()=>{var k;if(!n){Kh(i)&&p("inbox"),S(((k=e[0])==null?void 0:k.tabKey)||null),A.current=null;return}if(i!=="chat"){A.current=null;return}const I=`${n.tabKey}:${n.sessionId||""}`;A.current!==I&&(A.current=I,y(n))},[e,y,i,n,p,S]),o.useEffect(()=>{if(!d)return;const I=e.find(k=>k.tabKey===d);I&&(S(I.tabKey),p("chat"),f==null||f())},[e,f,d,p,S]),o.useEffect(()=>{if(!u)return;const I=t.find(k=>k.id===u);I&&(h(I.id),N(),j("machines"),b("inbox"),p("machine"),x==null||x())},[t,x,u,N,b,p,j,h]),o.useEffect(()=>{m&&(j(m),p("inbox"),v==null||v())},[v,m,p,j]),o.useEffect(()=>{const I=r.filter(k=>k.inboxBucket==="task_complete"||k.unread);I.length!==0&&kr("inbox_state",{screen:i,selectedTabKey:a,items:I.map(k=>{const w=Or(k.conversation,c);return{liveState:w,tabKey:k.conversation.tabKey,sessionId:k.conversation.sessionId,displayPrimary:nt(k.conversation),serverBucket:w.inboxBucket,computedBucket:k.inboxBucket,serverUnread:w.unread,computedUnread:k.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,activityAt:es(k.conversation)}})})},[r,c,i,a]),{markConversationRead:y}}function Wh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function ti(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Hh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Fh({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[d,f]=o.useState(null),u=o.useCallback(()=>{i("idle"),l(""),f(null)},[]),x=o.useCallback(async(b,N,A)=>{var y;try{i("loading"),l(`Launching ${N}…`);const I={ideType:N,enableCdp:!0};(y=A==null?void 0:A.workspacePath)!=null&&y.trim()&&(I.workspace=A.workspacePath.trim()),await e(b,"launch_ide",I),i("done"),l(`${N} launch requested`)}catch(I){i("error"),l(I instanceof Error?I.message:"Launch IDE failed"),console.error("Launch IDE failed",I)}},[e]),m=o.useCallback(async(b,N,A)=>{if(N.trim())try{i("loading"),l(A!=null&&A.createIfMissing?"Creating folder…":"Saving workspace…");const y=await e(b,"workspace_add",{path:N.trim(),createIfMissing:(A==null?void 0:A.createIfMissing)===!0});if(y!=null&&y.success){i("done"),l(A!=null&&A.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((y==null?void 0:y.error)||"Could not save workspace")}catch(y){i("error"),l(y instanceof Error?y.message:"Could not save workspace")}},[e]),v=o.useCallback(async b=>{var N,A,y,I,k,w;try{i("loading"),l("Starting daemon upgrade…");const g=await e(b,"daemon_upgrade",{});if((N=g==null?void 0:g.result)!=null&&N.alreadyLatest){i("done"),l(`Already on v${((A=g==null?void 0:g.result)==null?void 0:A.version)||"latest"}.`);return}if((y=g==null?void 0:g.result)!=null&&y.upgraded||(I=g==null?void 0:g.result)!=null&&I.success){i("done"),l(`Upgrade to v${((k=g==null?void 0:g.result)==null?void 0:k.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((w=g==null?void 0:g.result)==null?void 0:w.error)||"Upgrade failed")}catch(g){i("error"),l(g instanceof Error?g.message:"Upgrade failed")}},[e]),S=o.useCallback(async(b,N,A,y)=>{var w,g,E;const I=Date.now(),k={machineId:b,kind:N,providerType:A,workspaceId:(y==null?void 0:y.workspaceId)||null,workspacePath:(y==null?void 0:y.workspacePath)||null,resumeSessionId:(y==null?void 0:y.resumeSessionId)||null,startedAt:I};try{i("loading"),l(`Launching ${A}…`),f(k);const M={cliType:A};(w=y==null?void 0:y.workspacePath)!=null&&w.trim()?M.dir=y.workspacePath.trim():y!=null&&y.workspaceId&&(M.workspaceId=y.workspaceId),y!=null&&y.resumeSessionId&&(M.resumeSessionId=y.resumeSessionId),(g=y==null?void 0:y.args)!=null&&g.trim()&&(M.cliArgs=y.args.trim().split(/\s+/).filter(Boolean)),(E=y==null?void 0:y.model)!=null&&E.trim()&&(M.initialModel=y.model.trim());const C=await e(b,"launch_cli",M),R=(C==null?void 0:C.result)||C,K=(R==null?void 0:R.sessionId)||(R==null?void 0:R.id);if(C!=null&&C.success&&K){f(null),i("done"),l(`${A} launched`),t(Gt(K));return}if(C!=null&&C.success){i("loading"),l(`${A} launch requested — waiting for session…`);return}f(null),i("error"),l((C==null?void 0:C.error)||(R==null?void 0:R.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(M){if(Hh(M)){i("loading"),l(`${A} launch requested — waiting for session…`);return}f(null),i("error"),l(M instanceof Error?M.message:`Could not launch ${N.toUpperCase()} workspace`)}},[t,e]),p=o.useCallback(async(b,N)=>{try{const A=await e(b,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),y=(A==null?void 0:A.result)??A;return Array.isArray(y==null?void 0:y.sessions)?y.sessions:[]}catch(A){return console.error("Failed to list saved sessions on mobile:",A),[]}},[e]),h=o.useCallback(async(b,N)=>rn(e,b,N),[e]);o.useEffect(()=>{if(!d)return;const b=ti(d.workspacePath),N=r.find(y=>{var M,C,R,K;if(!y||y.type==="adhdev-daemon"||Wh(y.daemonId||y.id)!==d.machineId||(y.transport==="acp"?"acp":y.transport==="pty"?"cli":null)!==d.kind||String(y.agentType||y.type||"")!==d.providerType)return!1;const g=String(y.providerSessionId||"");if(d.resumeSessionId&&g)return g===d.resumeSessionId;if(b){const z=ti(y.workspace||y.runtimeWorkspaceLabel);return z?z===b:!1}return Number(y.lastUpdated||y._lastUpdate||y.timestamp||((K=(R=(C=(M=y.activeChat)==null?void 0:M.messages)==null?void 0:C.at)==null?void 0:R.call(C,-1))==null?void 0:K.timestamp)||0)>=d.startedAt-5e3});if(!N)return;const A=cc({entrySessionId:N.sessionId,entryInstanceId:N.instanceId,entryRouteId:N.id,conversations:n});A&&(f(null),i("done"),l(`${d.providerType} launched`),t(Gt(A)))},[n,r,t,d]),o.useEffect(()=>{if(!d)return;const b=window.setTimeout(()=>{f(N=>!N||N.startedAt!==d.startedAt?N:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(b)},[d]);const j=o.useCallback(async(b,N)=>{if(N.kind==="ide"&&N.providerType){await x(b,N.providerType,{workspacePath:N.workspace||null});return}(N.kind==="cli"||N.kind==="acp")&&N.providerType&&await S(b,N.kind,N.providerType,{workspacePath:N.workspace||null,resumeSessionId:N.providerSessionId||null})},[x,S]);return{machineAction:{state:a,message:c},resetMachineAction:u,handleLaunchDetectedIde:x,handleAddWorkspace:m,handleMachineUpgrade:v,handleLaunchWorkspaceProvider:S,handleListSavedSessions:p,handleBrowseDirectory:h,handleOpenRecent:j}}function Uh({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:d,setMachineBackTarget:f}){const u=o.useCallback(j=>{i(j.tabKey),c("chat"),n(j)},[n,c,i]),x=o.useCallback(j=>{const b=e.find(N=>N.routeId===j.routeId&&N.streamSource==="native");b&&(i(b.tabKey),c("chat"),n(b))},[e,n,c,i]),m=o.useCallback(()=>{n(t),c("inbox")},[n,t,c]),v=o.useCallback((j,b="inbox")=>{l(j),a(),d("machines"),f(b),c("machine")},[a,f,c,d,l]),S=o.useCallback(j=>{const b=fs(j);b&&v(b,"chat")},[v]),p=o.useCallback(()=>{a(),c(r)},[r,a,c]),h=o.useCallback(j=>{d(j),c("inbox")},[c,d]);return{openConversation:u,openNativeConversation:x,backFromConversation:m,openMachine:v,openConversationMachine:S,backFromMachine:p,changeMachineSection:h}}function zh(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function Sr(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Vh({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,userName:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:f,requestedMachineId:u,onRequestedMachineConsumed:x,requestedMobileSection:m,onRequestedMobileSectionConsumed:v,onOpenHistory:S,onOpenRemote:p,onStopCli:h,wsStatus:j,isConnected:b,onShowHiddenConversation:N,onShowAllHiddenConversations:A,onHideConversation:y,onOpenNewSession:I,liveSessionInboxState:k,setCliViewModeOverrides:w}){const[g,E]=o.useState(()=>{var G;return((G=e[0])==null?void 0:G.tabKey)||null}),[M,C]=o.useState(()=>e[0]?"chat":"inbox"),[R,K]=o.useState("chats"),[z,T]=o.useState(null),[L,Y]=o.useState("inbox"),O=As(),D="0.9.26",W=o.useMemo(()=>e.find(G=>G.tabKey===g)||e[0]||null,[e,g]),Q=o.useMemo(()=>W?r.find(G=>G.id===W.routeId):void 0,[r,W]),be=o.useMemo(()=>!W||Xe(W)||!Ze(W)?null:Ls(W),[W]),pe=o.useMemo(()=>r.filter(G=>G.type==="adhdev-daemon").sort(wa),[r]),ue=o.useMemo(()=>pe.find(G=>G.id===z)||null,[pe,z]),we=nn({sendDaemonCommand:a,activeConv:W||void 0,setActionLogs:i,isStandalone:c}),ye=Fh({sendDaemonCommand:a,navigate:O,ides:r,conversations:e}),ve=o.useMemo(()=>e.map(G=>{const U=M==="chat"&&(W==null?void 0:W.tabKey)===G.tabKey,de=Qr(G,k,{hideOpenTaskCompleteUnread:!0,isOpenConversation:U}),Ne=es(G),_e=xc(G);return{conversation:G,timestamp:Ne,preview:_e,unread:de.unread,requiresAction:de.requiresAction,isWorking:de.isWorking,inboxBucket:de.inboxBucket}}),[e,k,M,W]),{markConversationRead:V}=Oh({conversations:e,machineEntries:pe,items:ve,selectedConversation:W,selectedTabKey:g,screen:M,liveSessionInboxState:k,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:f,requestedMachineId:u,onRequestedMachineConsumed:x,requestedMobileSection:m,onRequestedMobileSectionConsumed:v,setSelectedTabKey:E,setScreen:C,setSelectedMachineId:T,setSection:K,setMachineBackTarget:Y,resetMachineAction:ye.resetMachineAction}),H=Uh({conversations:e,selectedConversation:W,machineBackTarget:L,markConversationRead:V,resetMachineAction:ye.resetMachineAction,setSelectedTabKey:E,setScreen:C,setSelectedMachineId:T,setSection:K,setMachineBackTarget:Y}),Z=o.useMemo(()=>Sr(ve.filter(G=>G.requiresAction)),[ve]),me=o.useMemo(()=>Sr(ve.filter(G=>G.unread&&!G.requiresAction)),[ve]),ne=o.useMemo(()=>Sr(ve.filter(G=>!G.unread&&!G.requiresAction&&G.isWorking)),[ve]),fe=o.useMemo(()=>Sr(ve.filter(G=>!G.unread&&!G.requiresAction&&!G.isWorking)),[ve]),se=o.useMemo(()=>ue?ve.filter(G=>fs(G.conversation)===ue.id):[],[ve,ue]),xe=o.useMemo(()=>$h(ue,r),[r,ue]),ie=(ue==null?void 0:ue.version)||null,ce=!!ue&&!!ie&&!0&&ie!==D,ae=o.useMemo(()=>(ue==null?void 0:ue.availableProviders)||[],[ue]),X=o.useMemo(()=>ae.filter(G=>G.category==="cli"&&G.installed!==!1).map(G=>({type:G.type,displayName:G.displayName||G.type,icon:G.icon})),[ae]),J=o.useMemo(()=>ae.filter(G=>G.category==="acp"&&G.installed!==!1).map(G=>({type:G.type,displayName:G.displayName||G.type,icon:G.icon})),[ae]),oe=o.useMemo(()=>Bh(pe,ve),[ve,pe]),P=o.useCallback(async G=>{ue&&await ye.handleOpenRecent(ue.id,G)},[ye,ue]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:M==="chat"&&W?s.jsx(Ih,{selectedConversation:W,isAcp:Xe(W),isStandalone:c,selectedIdeEntry:Q,actionLogs:n,userName:l,isSendingChat:we.isSendingChat,sendFeedbackMessage:we.sendFeedbackMessage,isFocusingAgent:we.isFocusingAgent,handleModalButton:we.handleModalButton,handleRelaunch:we.handleRelaunch,onBack:H.backFromConversation,onOpenNativeConversation:H.openNativeConversation,onOpenMachine:H.openConversationMachine,onHideConversation:y,onOpenHistory:S,onOpenRemote:p,onStopCli:h,cliViewMode:be,onSetCliViewMode:async G=>{await Uc({conversation:W,mode:G,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:w})},handleSendChat:we.handleSendChat,handleFocusAgent:we.handleFocusAgent}):M==="machine"&&ue?s.jsx(Dh,{selectedMachineEntry:ue,selectedMachineConversations:se,selectedMachineRecentLaunches:xe,cliProviders:X,acpProviders:J,selectedMachineNeedsUpgrade:ce,appVersion:D,machineAction:ye.machineAction,isStandalone:c,section:R,showBottomNav:L==="inbox",onBack:H.backFromMachine,onSectionChange:H.changeMachineSection,onOpenConversation:H.openConversation,onOpenRecent:P,onOpenMachineDetails:()=>O(`/machines/${ue.id}`),onMachineUpgrade:()=>ye.handleMachineUpgrade(ue.id),onLaunchDetectedIde:(G,U)=>ye.handleLaunchDetectedIde(ue.id,G,U),onAddWorkspace:(G,U)=>ye.handleAddWorkspace(ue.id,G,U),onBrowseDirectory:G=>ye.handleBrowseDirectory(ue.id,G),onLaunchWorkspaceProvider:(G,U,de)=>ye.handleLaunchWorkspaceProvider(ue.id,G,U,de),onListSavedSessions:G=>ye.handleListSavedSessions(ue.id,G)}):s.jsx(Ah,{section:R,attentionItems:Z,unreadItems:me,workingItems:ne,completedItems:fe,hiddenConversations:t,machineCards:oe,getAvatarText:zh,onOpenConversation:H.openConversation,onShowConversation:N,onShowAllHidden:A,onOpenNewSession:I,onOpenMachine:H.openMachine,onOpenSettings:()=>O("/settings"),onSectionChange:K,wsStatus:j,isConnected:b,isStandalone:c})})}function Tn(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function Gh({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,d]=o.useState(!1),[f,u]=o.useState(null),x=o.useCallback(()=>{c.current=0,d(!1),u(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",x),window.addEventListener("drop",x),()=>{window.removeEventListener("dragend",x),window.removeEventListener("drop",x)}),[x]);const m=o.useCallback(h=>{h.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,d(!0))},[]),v=o.useCallback(h=>{if(!h.dataTransfer.types.includes("text/tab-key"))return;if(h.preventDefault(),!Tn(t,r)){u("merge");return}const j=h.currentTarget.getBoundingClientRect(),b=h.clientX-j.left,N=j.width/3;b<N?u("split-left"):b>N*2?u("split-right"):u("merge")},[t,r]),S=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,d(!1),u(null))},[]),p=o.useCallback(h=>{c.current=0,d(!1);const j=h.dataTransfer.getData("text/tab-key"),b=j?e.some(A=>A.tabKey===j):!1,N=f;if(u(null),i(),!!j){if(h.preventDefault(),N==="split-left"&&Tn(t,r)){r==null||r(j,"split-left");return}if(N==="split-right"&&Tn(t,r)){r==null||r(j,"split-right");return}if(b){a(j);return}n==null||n(j)}},[e,f,t,r,n,a,i]);return{dragOver:l,dropAction:f,resetDragState:x,handleDragEnter:m,handleDragOver:v,handleDragLeave:S,handleDrop:p}}function qh(e,t){const r=new Set(t.map(i=>i.tabKey)),n=e.filter(i=>r.has(i)),a=t.filter(i=>!e.includes(i.tabKey)).map(i=>i.tabKey);return[...n,...a]}function Yh({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(t??null),[l,d]=o.useState(r??[]),[f,u]=o.useState(null),x=o.useRef(null),m=o.useRef(null),v=o.useRef(n),S=o.useRef(a);o.useEffect(()=>{v.current=n},[n]),o.useEffect(()=>{S.current=a},[a]),o.useEffect(()=>{t&&t!==i&&c(t)},[t,i]),o.useEffect(()=>{d(k=>{const w=qh(k,e);return w.length===k.length&&w.every((g,E)=>g===k[E])?k:w})},[e]);const p=o.useMemo(()=>{const k=f??l;if(k.length===0)return e;const w=new Map(k.map((g,E)=>[g,E]));return[...e].sort((g,E)=>{const M=w.get(g.tabKey)??999,C=w.get(E.tabKey)??999;return M-C})},[e,f,l]);o.useEffect(()=>{var w,g;if(p.length===0){i!==null&&(c(null),(w=v.current)==null||w.call(v,null));return}if(i&&p.some(E=>E.tabKey===i))return;const k=p[0].tabKey;k!==i&&(c(k),(g=v.current)==null||g.call(v,k))},[p,i]);const h=o.useMemo(()=>p.find(k=>k.tabKey===i),[p,i]),j=o.useCallback(k=>{var w;c(k),(w=v.current)==null||w.call(v,k)},[]),b=o.useCallback((k,w,g)=>{d(E=>{var K;const M=E.filter(z=>z!==k),C=M.indexOf(w);if(C<0)return E;const R=g==="left"?C:C+1;return M.splice(R,0,k),(K=S.current)==null||K.call(S,M),M}),u(null)},[]),N=o.useCallback((k,w,g)=>{const M=(l.length>0?l:e.map(K=>K.tabKey)).filter(K=>K!==k),C=M.indexOf(w);if(C<0)return;const R=g==="left"?C:C+1;M.splice(R,0,k),x.current=M,u(M)},[l,e]),A=o.useCallback(()=>{var w;const k=x.current;k&&(d(k),(w=S.current)==null||w.call(S,k))},[]),y=o.useCallback(()=>{x.current=null,u(null)},[]),I=o.useCallback(k=>{d(w=>{var E;const g=w.filter(M=>M!==k);return g.push(k),(E=S.current)==null||E.call(S,g),g})},[]);return{activeTabId:i,activeConv:h,sortedConversations:p,previewOrderRef:x,draggingTabRef:m,selectTab:j,handleTabReorder:b,updatePreviewOrder:N,commitPreviewOrder:A,clearPreviewOrder:y,moveTabToEnd:I,setDraggingTabKey:k=>{m.current=k}}}function Xh({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 qa({conversationsCount:e,isSplitMode:t,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession:i}){if(a)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const c=!r&&!n,l=n&&!!i,d=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",f=n?vc: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:f}),l&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:i,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:$t,"aria-label":$t,children:[s.jsx(Ei,{size:14}),s.jsx("span",{children:$t})]})}),c&&s.jsx(Qc,{}),c&&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 sl="adhdev-tab-shortcuts";function rl(){try{return JSON.parse(localStorage.getItem(sl)||"{}")}catch{return{}}}function nl({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>rl()),[l,d]=o.useState(null),f=o.useCallback(x=>{const m=[];return x.metaKey&&m.push(a?"⌘":"Meta"),x.ctrlKey&&m.push("Ctrl"),x.altKey&&m.push(a?"⌥":"Alt"),x.shiftKey&&m.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(x.key)?null:(m.push(x.key.length===1?x.key.toUpperCase():x.key),m.join("+"))},[a]),u=o.useCallback(x=>{c(x);try{localStorage.setItem(sl,JSON.stringify(x))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const x=m=>{if(m.preventDefault(),m.stopPropagation(),m.key==="Escape"){d(null);return}const v=f(m);if(!v)return;const S={...i};for(const[p,h]of Object.entries(S))h===v&&delete S[p];S[l]=v,u(S),d(null)};return window.addEventListener("keydown",x,!0),()=>window.removeEventListener("keydown",x,!0)},[e,l,i,u,f]),o.useEffect(()=>{if(!e)return;const x=m=>{if(!(!m.ctrlKey&&!m.metaKey&&!m.altKey)){for(const[v,S]of Object.entries(i))if(t.includes(v)&&f(m)===S){m.preventDefault(),r(),n(v);return}}};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[e,i,t,r,n,f]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:d,saveShortcuts:u}}const Jh=o.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:d,onSelectTab:f,onConversationActivated:u,onPreviewReorder:x,onReorderTab:m,onCommitPreviewOrder:v,onClearPreviewOrder:S,onDragStateReset:p,onDragTabKeyChange:h,onReceiveTab:j,onOpenContextMenu:b,longPressTimer:N,isGroupActive:A}){const y=Ts(t),I=y.isGenerating?"agent-tab-generating":y.isWaiting?"agent-tab-waiting":"",k=y.isReconnecting,w=o.useCallback(L=>{l.current=t.tabKey,h(t.tabKey),L.dataTransfer.setData("text/tab-key",t.tabKey),L.dataTransfer.effectAllowed="move"},[t.tabKey,l,h]),g=o.useCallback(()=>{l.current=null,h(null),v(),S(),p()},[l,h,v,S,p]),E=o.useCallback(L=>{const Y=l.current;if(!(!Y||Y===t.tabKey)&&L.dataTransfer.types.includes("text/tab-key")){L.preventDefault(),L.stopPropagation();const O=L.currentTarget.getBoundingClientRect(),D=L.clientX<O.left+O.width/2?"left":"right";x(Y,t.tabKey,D)}},[t.tabKey,l,x]),M=o.useCallback(L=>{L.preventDefault(),L.stopPropagation();const Y=L.dataTransfer.getData("text/tab-key");if(Y&&Y!==t.tabKey){const O=L.currentTarget.getBoundingClientRect(),D=L.clientX<O.left+O.width/2?"left":"right";c.includes(Y)?m(Y,t.tabKey,D):j&&j(Y)}S()},[t.tabKey,c,m,j,S]),C=o.useCallback(L=>{L.stopPropagation(),d(),f(t.tabKey),u(t)},[t,u,d,f]),R=o.useCallback(L=>{L.preventDefault(),b(L.clientX,L.clientY,t.tabKey)},[t.tabKey,b]),K=o.useCallback(L=>{const Y=L.touches[0];N.current=setTimeout(()=>{b(Y.clientX,Y.clientY,t.tabKey)},600)},[t.tabKey,N,b]),z=o.useCallback(()=>{N.current&&clearTimeout(N.current)},[N]),T=["adhdev-dockview-tab",I,r&&"is-active",A&&"is-group-active",k&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:T,draggable:!0,onDragStart:w,onDragEnd:g,onDragOver:E,onDrop:M,onClick:C,onContextMenu:R,onTouchStart:K,onTouchEnd:z,onTouchMove:z,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:y.isGenerating?s.jsx("div",{className:"tab-spinner"}):y.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):k?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):y.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:nt(t),children:nt(t)}),s.jsx("span",{className:"adhdev-dockview-tab-meta",children:k?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ts(t)}):y.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[ts(t),s.jsx("span",{className:"connecting-dots"})]}):ts(t)})]}),i&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${i}`,children:i})]})},(e,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 Qh({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:f,onCommitPreviewOrder:u,onClearPreviewOrder:x,onDragStateReset:m,onDragTabKeyChange:v,onReceiveTab:S,onHideTab:p,isGroupActive:h,allowTabShortcuts:j=!0}){const[b,N]=o.useState(null),A=o.useRef(null),y=o.useRef(null),I=o.useMemo(()=>e.map(R=>R.tabKey),[e]);rr("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(b==null?void 0:b.tabKey)||null});const{isMac:k,tabShortcuts:w,shortcutListening:g,setShortcutListening:E,saveShortcuts:M}=nl({enabled:j,sortedTabKeys:e.map(R=>R.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!b)return;const R=K=>{const z=document.querySelector("[data-pane-context-menu]");z&&z.contains(K.target)||N(null)};return window.addEventListener("mousedown",R,!0),()=>window.removeEventListener("mousedown",R,!0)},[b]),o.useEffect(()=>{const R=y.current;if(!R)return;const K=z=>{Math.abs(z.deltaY)<=Math.abs(z.deltaX)||(z.preventDefault(),R.scrollLeft+=z.deltaY)};return R.addEventListener("wheel",K,{passive:!1}),()=>R.removeEventListener("wheel",K)},[]);const C=o.useCallback((R,K,z)=>{N({x:R,y:K,tabKey:z})},[]);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:y,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(R=>s.jsx(Jh,{conv:R,isActive:t===R.tabKey,isDraggedTab:a.current===R.tabKey,isTaskCompleteUnread:n.has(R.tabKey),shortcut:j?w[R.tabKey]:void 0,conversationKeys:I,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:f,onCommitPreviewOrder:u,onClearPreviewOrder:x,onDragStateReset:m,onDragTabKeyChange:v,onReceiveTab:S,onOpenContextMenu:C,longPressTimer:A,isGroupActive:h},R.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),b&&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:b.x,top:b.y},children:[j&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:R=>{R.stopPropagation(),E(b.tabKey),N(null)},children:["⌨ ",w[b.tabKey]?`Change shortcut (${w[b.tabKey]})`:"Set shortcut"]}),w[b.tabKey]&&s.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onClick:()=>{const R={...w};delete R[b.tabKey],M(R),N(null)},children:"✕ Remove shortcut"})]}),p&&s.jsxs(s.Fragment,{children:[j&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onClick:()=>{p(b.tabKey),N(null)},children:"🚫 Hide from Dashboard"})]})]}),j&&g&&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:()=>E(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:R=>R.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. ",k?"⌘+1":"Ctrl+1",", ",k?"⌥+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 Zh({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,userName:d,groupIndex:f,onFocus:u,isSplitMode:x,numGroups:m,onMoveTab:v,onReceiveTab:S,style:p,onActiveTabChange:h,initialActiveTabId:j,initialTabOrder:b,onTabOrderChange:N,onHideTab:A,isFocused:y,allowTabShortcuts:I=!0,onOpenNewSession:k,liveSessionInboxState:w}){const{sendCommand:g}=wt(),E=o.useRef(null),{activeTabId:M,activeConv:C,sortedConversations:R,draggingTabRef:K,selectTab:z,handleTabReorder:T,updatePreviewOrder:L,commitPreviewOrder:Y,clearPreviewOrder:O,moveTabToEnd:D,setDraggingTabKey:W}=Yh({conversations:e,initialActiveTabId:j,initialTabOrder:b,onActiveTabChange:h,onTabOrderChange:N}),Q=nn({sendDaemonCommand:a,activeConv:C,setActionLogs:i,isStandalone:c}),{dragOver:be,dropAction:pe,resetDragState:ue,handleDragEnter:we,handleDragOver:ye,handleDragLeave:ve,handleDrop:V}=Gh({conversations:e,numGroups:m,onMoveTab:v,onReceiveTab:S,onOwnTabDrop:D,onClearPreviewOrder:O}),H=C&&!Xe(C)&&Ls(C)==="terminal",Z=o.useMemo(()=>C?t.find(se=>se.id===C.routeId):void 0,[t,C]),me=o.useMemo(()=>C?n.filter(se=>se.routeId===C.tabKey):[],[n,C]),ne=o.useMemo(()=>new Set(R.filter(se=>ju(se,w,{isOpenConversation:se.tabKey===M})).map(se=>se.tabKey)),[M,w,R]);rr("PaneGroup",{groupIndex:f,conversationCount:e.length,activeTabId:M,dragOver:be});const fe=o.useCallback(se=>{se.streamSource==="agent-stream"&&se.agentType&&g(se.routeId,Jc(),{agentType:se.agentType,...se.sessionId&&{targetSessionId:se.sessionId}}).catch(()=>{})},[g]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...p,outline:be?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(Qh,{conversations:R,activeTabId:M,groupIndex:f,numGroups:m,unreadTabKeys:ne,draggingTabRef:K,onFocus:u,onSelectTab:z,onConversationActivated:fe,onPreviewReorder:L,onReorderTab:T,onCommitPreviewOrder:Y,onClearPreviewOrder:O,onDragStateReset:ue,onDragTabKeyChange:W,onMoveTab:v,onReceiveTab:S,onHideTab:A,isGroupActive:y??!1,allowTabShortcuts:I}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:we,onDragOver:ye,onDragLeave:ve,onDrop:V,children:[be&&s.jsx(Xh,{dropAction:pe,canSplit:!!(m<4&&v)}),C?s.jsx(Va,{activeConv:C,clearToken:r[C.tabKey]||0,isCliTerminal:!!H,ideEntry:Z,terminalRef:E,handleModalButton:Q.handleModalButton,handleRelaunch:Q.handleRelaunch,handleSendChat:Q.handleSendChat,isSendingChat:Q.isSendingChat,sendFeedbackMessage:Q.sendFeedbackMessage,handleFocusAgent:Q.handleFocusAgent,isFocusingAgent:Q.isFocusingAgent,actionLogs:me,userName:d,isInputActive:!x||!!y}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(qa,{conversationsCount:e.length,isSplitMode:x,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:k})})]})]})}function ex({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:f,isStandalone:u,hasRegisteredMachines:x,userName:m,focusedGroup:v,focusGroup:S,moveTabToGroup:p,splitTabRelative:h,closeGroup:j,handleResizeStart:b,groupActiveTabIds:N,setGroupActiveTab:A,groupTabOrders:y,setGroupTabOrder:I,toggleHiddenTab:k,onOpenNewSession:w,allowTabShortcuts:g=!0,liveSessionInboxState:E}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((M,C)=>{const R=t&&n.length===r?`${n[C]}%`:void 0;return s.jsxs(kt.Fragment,{children:[t&&C>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:K=>b(C-1,K),onDoubleClick:()=>j(C),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(Zh,{style:t?{flexBasis:R??`${100/r}%`,flexGrow:R?0:1,flexShrink:R?0:1}:void 0,conversations:M,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:f,isStandalone:u,hasRegisteredMachines:x,userName:m,groupIndex:C,isFocused:t&&v===C,onFocus:()=>S(C),isSplitMode:t,numGroups:r,onMoveTab:(K,z)=>{z==="left"&&C>0?p(K,C-1):z==="right"&&C<r-1?p(K,C+1):z==="split-left"&&r<4?h(K,C,"left"):z==="split-right"&&r<4&&h(K,C,"right")},onReceiveTab:K=>p(K,C),onActiveTabChange:K=>A(C,K),initialActiveTabId:N[C],initialTabOrder:y[C],onTabOrderChange:K=>I(C,K),onHideTab:k,onOpenNewSession:w,allowTabShortcuts:g,liveSessionInboxState:E})]},C)})})}function al({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?it.onScreenshot("ide-page",(u,x)=>{if(u!==e)return;const m=new FileReader;m.onload=()=>i(m.result),m.readAsDataURL(x)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var u;return e?((u=it.onStatus)==null?void 0:u.call(it,(x,m)=>{x===e&&m!=null&&m.screenshotUsage&&l(m.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,t]),o.useEffect(()=>{const f=e?it.get(e):null;if(!(!f||r!=="connected"))return n!=="chat"&&t?f.startScreenshots(t):f.stopScreenshots(t),()=>{f.stopScreenshots(t)}},[n,r,t,e]);const d=o.useCallback(async(f,u)=>{const x=e?it.get(e):null;return!x||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):x.sendInput(f,u,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:d}}const ol="adhdev-dashboard-action-shortcuts",tx=1200,sx={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function rx(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function tt(e,t){switch(e){case"openShortcutHelp":return"?";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+Alt+\\";case"splitActiveTabDown":return t?"⌘+⌥+-":"Ctrl+Alt+-";case"focusLeftPane":return t?"⌘+⌥+[":"Ctrl+Alt+←";case"focusRightPane":return t?"⌘+⌥+]":"Ctrl+Alt+→";case"focusUpPane":return t?"⌘+⌥+U":"Ctrl+Alt+↑";case"focusDownPane":return t?"⌘+⌥+J":"Ctrl+Alt+↓";case"moveActiveTabToLeftPane":return t?"⌘+⌥+,":"Ctrl+Alt+Shift+←";case"moveActiveTabToRightPane":return t?"⌘+⌥+.":"Ctrl+Alt+Shift+→";case"moveActiveTabToUpPane":return t?"⌘+⌥+I":"Ctrl+Alt+Shift+↑";case"moveActiveTabToDownPane":return t?"⌘+⌥+K":"Ctrl+Alt+Shift+↓";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+Alt+[";case"selectNextGroupTab":return t?"⌥+]":"Ctrl+Alt+]";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function il(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:tt("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:tt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:tt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:tt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:tt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:tt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:tt("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:tt("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:tt("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:tt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:tt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:tt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:tt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:tt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:tt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:tt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:tt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:tt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:tt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:tt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:tt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:tt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:tt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:tt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:tt("toggleCliView",e)}]}function la(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Gr(e){const t=Object.fromEntries(il(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(ol)||"{}"),n={...t,...r};for(const[a,i]of Object.entries(sx))n[a]===i&&(n[a]=t[a]);return n}catch{return t}}function cl(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function nx({enabled:e=!0,onTrigger:t}){const r=rx(),[n,a]=o.useState(()=>Gr(r)),[i,c]=o.useState(null),[l,d]=o.useState([]),f=o.useRef({parts:[],timer:null}),u=o.useCallback(p=>{const h=[];return p.metaKey&&h.push(r?"⌘":"Meta"),p.ctrlKey&&h.push("Ctrl"),p.altKey&&h.push(r?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&h.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(h.push(cl(p.key)),h.join("+"))},[r]),x=o.useCallback(p=>{a(p);try{localStorage.setItem(ol,JSON.stringify(p))}catch{}},[]);o.useEffect(()=>{const p=Gr(r),h=Object.entries(n),j=Object.entries(p);h.length===j.length&&h.every(([b,N])=>p[b]===N)||x(p)},[n,r,x]);const m=o.useCallback(()=>{typeof window<"u"&&f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current={parts:[],timer:null}},[]),v=o.useCallback(()=>{typeof window>"u"||(f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current.timer=window.setTimeout(()=>{f.current={parts:[],timer:null}},tx))},[]);o.useEffect(()=>{if(!i)return;const p=h=>{if(h.preventDefault(),h.stopPropagation(),h.key==="Escape"){c(null),d([]);return}const j=u(h);if(!j)return;const N=!(h.metaKey||h.ctrlKey||h.altKey)&&/^[A-Z0-9]$/.test(j);if(l.length===0&&N){d([j]);return}const y=[...l,j].slice(0,2).join(" "),I={...n};for(const[k,w]of Object.entries(I))w===y&&delete I[k];I[i]=y,x(I),c(null),d([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,u,x,i,l]),o.useEffect(()=>{if(!e||i)return;const p=h=>{if(h.defaultPrevented)return;const j=u(h);if(!j)return;const b=h.metaKey||h.ctrlKey||h.altKey;if(la(h.target)&&!b)return;const N=f.current.parts,A=b?[j]:[...N.slice(-1),j].slice(-2),y=A.join(" "),I=A[A.length-1],k=Object.entries(n).filter(([,C])=>!!C),w=k.find(([,C])=>C===y);if(w){h.preventDefault(),m(),t(w[0]);return}if(k.some(([,C])=>C.startsWith(`${y} `))){h.preventDefault(),f.current.parts=A,v();return}const E=k.find(([,C])=>C===I);if(E){h.preventDefault(),m(),t(E[0]);return}if(k.some(([,C])=>C.startsWith(`${I} `))){h.preventDefault(),f.current.parts=[I],v();return}m()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,v,e,u,t,m,i]),o.useEffect(()=>()=>m(),[m]);const S=o.useMemo(()=>il(r),[r]);return{isMac:r,actionDefinitions:S,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:d,saveShortcuts:x}}function ax({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 ll(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function si({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!ll(n):!0}function ox({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:ll(r)}const dl=o.createContext(null);function on(){const e=o.useContext(dl);if(!e)throw new Error("DashboardDockviewContext missing");return e}function _r(e){return nt(e)||e.tabKey}function ix(e){return`remote:${e}`}function Lt(e){return e.startsWith("remote:")}function ri(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Ln(e){var r,n,a,i,c;const t=e==null?void 0:e.defaultView;if(t)try{t.focus(),(n=(r=e==null?void 0:e.body)==null?void 0:r.focus)==null||n.call(r),(i=(a=e==null?void 0:e.documentElement)==null?void 0:a.focus)==null||i.call(a),(c=t.requestAnimationFrame)==null||c.call(t,()=>{var l,d;try{t.focus(),(d=(l=e==null?void 0:e.body)==null?void 0:l.focus)==null||d.call(l)}catch{}})}catch{}}function Nr(e,t){e.classList.remove(Un.className,zn.className),e.classList.add(t==="light"?Un.className:zn.className)}function ni(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 cx(e){const[,t]=o.useState(0);o.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 lx(e,t,r){var c;const n=[t];let a;for(const l of n){let d;for(const f of l){const u=e.addPanel({id:f.tabKey,component:"conversation",title:_r(f),params:{kind:"conversation",tabKey:f.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??((c=t[0])==null?void 0:c.tabKey)??null}function ai(e,t){const r=new Set(t.map(n=>n.tabKey));for(const n of[...e.panels])Lt(n.id)||r.has(n.id)||e.removePanel(n);for(const n of t){const a=e.getPanel(n.tabKey);if(a){a.update({params:{tabKey:n.tabKey}}),a.title!==_r(n)&&a.api.setTitle(_r(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:_r(n),params:{kind:"conversation",tabKey:n.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function oi(e,t,r){var d,f;const n=r?ix(r):null;for(const u of[...e.panels])Lt(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=_t(t,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=yc(a);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((f=e.panels.find(u=>!Lt(u.id)))==null?void 0:f.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function dx({params:e,api:t}){var x;const r=on(),n=o.useRef(null),[a,i]=o.useState(t.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=nn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(t.isActive);const m=[t.onDidActiveChange(v=>i(v.isActive)),t.onDidActiveGroupChange(v=>{if(!t.isActive&&!v.isActive){i(!1);return}i(t.isActive)})];return()=>{for(const v of m)v.dispose()}},[t]);const d=o.useMemo(()=>c?r.ides.find(m=>m.id===c.routeId):void 0,[r.ides,c]),f=o.useMemo(()=>c?r.actionLogs.filter(m=>m.routeId===c.tabKey):[],[r.actionLogs,c]);if(!c)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(qa,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const u=!Xe(c)&&Ls(c)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(Va,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:u,ideEntry:d,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:f,userName:r.userName,scrollToBottomRequestNonce:((x=r.scrollToBottomRequest)==null?void 0:x.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:a})})}function ux({params:e}){var d;const t=on(),r=o.useMemo(()=>_t([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=o.useMemo(()=>t.ides.find(f=>f.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:i,screenshotUsage:c,handleRemoteAction:l}=al({doId:a,targetSessionId:r?nc(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(Wi,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:c,transportType:r.transport,onAction:l})}):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 mx(){const e=on();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(qa,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function fx(e){var v,S;cx(e);const t=on(),r=o.useCallback(p=>{"button"in p&&p.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const p=_t([...t.conversationsByTabKey.values()],e.params.routeId),h=((v=e.api.group.activePanel)==null?void 0:v.id)===e.api.id,j=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${h?" is-active":""}${j?" 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=((S=e.api.group.activePanel)==null?void 0:S.id)===e.api.id,i=e.api.isGroupActive,c=Qr(n,t.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,d=c.isConnecting,f=c.isGenerating,u=c.isWaiting,x=c.unread,m=t.tabShortcuts[n.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:nt(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:p=>{var h;p.preventDefault(),r(p),t.openTabContextMenu({x:p.clientX,y:p.clientY,tabKey:n.tabKey,sourceDocument:((h=p.target)==null?void 0:h.ownerDocument)??document})},children:[x&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:f?s.jsx("div",{className:"tab-spinner"}):u?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?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:nt(n)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ts(n)}):d?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ts(n)}):s.jsx("span",{children:ts(n)})})]}),m&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:m,children:m})]})}function px({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:d,userName:f,toggleHiddenTab:u,actionShortcuts:x,registerActionHandlers:m,onActiveTabChange:v,onOpenNewSession:S,onRequestScrollToBottom:p,requestedActiveTabKey:h,requestedRemoteIdeId:j,onRequestedActiveTabConsumed:b,scrollToBottomRequest:N,liveSessionInboxState:A,layoutProfile:y}){var ft,Tt,yt;const{theme:I}=Ka(),{sendCommand:k}=wt(),w=o.useRef(null),g=o.useRef(null),E=o.useRef(!1),M=o.useRef(!1),C=o.useRef(!1),R=o.useRef(null),K=o.useRef([]),[z,T]=o.useState(null),[L,Y]=o.useState(!1),[O,D]=o.useState(!1),[W,Q]=o.useState(0),be=o.useRef(null),pe=o.useRef(typeof window>"u"?{}:Up(y)),ue=o.useMemo(()=>new Map(e.map(B=>[B.tabKey,B])),[e]),we=o.useMemo(()=>{const B=w.current;return B?B.groups.some($=>{try{const F=$.model.location.type;return F!=="floating"&&F!=="popout"?!1:$.panels.some(q=>ue.has(q.id))}catch{return!1}}):!1},[ue,W,e]),ye=o.useCallback(()=>{var B;(B=w.current)==null||B.focus()},[]),ve=o.useCallback((B,$)=>{p==null||p(B,$)},[p]),V=o.useCallback(B=>{const $=document,F=B.document;for(const Ce of $.querySelectorAll('link[rel="stylesheet"]')){const re=F.createElement("link");re.rel="stylesheet",re.href=Ce.href,Ce.crossOrigin&&(re.crossOrigin=Ce.crossOrigin),F.head.appendChild(re)}for(const Ce of $.querySelectorAll("style")){const re=F.createElement("style");re.textContent=Ce.textContent,F.head.appendChild(re)}const q=[];for(const Ce of $.styleSheets)try{for(const re of Ce.cssRules)re instanceof CSSStyleRule&&(re.selectorText===":root"||re.selectorText==="html")&&q.push(re.cssText)}catch{}if(q.length>0){const Ce=F.createElement("style");Ce.textContent=q.join(`
42
+ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:g,onCancel:()=>u(null)})]})}const sp=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function rp(){const{preference:e,setPreference:t}=Ka();return s.jsx("div",{className:"flex gap-2",children:sp.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 np(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 ap(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function jn(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Ko(e){const{r:t,g:r,b:n}=ap(e);return .2126*jn(t)+.7152*jn(r)+.0722*jn(n)}function Oo(e,t){const r=Ko(e),n=Ko(t),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function Dc(e){const t=np(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return Oo(t,r)>=Oo(t,n)?r:n}const oa={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},ia={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},op=[{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"}}}],Ec="adhdev-chat-theme",$c="adhdev-chat-theme-custom";function Rr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Ec)||"ember"}catch{return"ember"}}function Pt(e){try{const t=localStorage.getItem($c);if(t){const r=JSON.parse(t);return{...e==="dark"?oa:ia,...r[e]}}}catch{}return e==="dark"?oa:ia}function yr(e,t){try{localStorage.setItem($c,JSON.stringify({dark:e,light:t}))}catch{}}function It(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 Vr(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 ip={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Vs(e,t){var a;const r=(a=ip[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",Vr(r,24)),n.style.setProperty("--accent-on-primary",Dc(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Vr(r,18)})`),n.style.setProperty("--border-accent",It(r,.35)),n.style.setProperty("--nav-active-bg",It(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${It(r,.06)}`)}function ns(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",It(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",It(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",It(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",It(e.borderSubtle,.5)),t.style.setProperty("--border-default",It(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Vr(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Dc(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Vr(e.accentColor,40)})`),t.style.setProperty("--border-accent",It(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",It(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${It(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 ${It(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 Oa(){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 cp(e){try{localStorage.setItem(Ec,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=as()?"dark":"light";ns(Pt(t))}else Oa(),Vs(e,as()?"dark":"light")}function lp(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Rr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=as()?"dark":"light";ns(Pt(t))}else Oa(),Vs(e,as()?"dark":"light")}function as(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function xt({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 Es({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 dp({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=o.useState(()=>Pt(r));o.useEffect(()=>{a(Pt(r))},[r]);const i=o.useCallback((c,l)=>{a(d=>{const f={...d,[c]:l},x=Pt(r==="dark"?"light":"dark");return r==="dark"?yr(f,x):yr(x,f),ns(f),t(f),f})},[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(Es,{title:"App Background",children:[s.jsx(xt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(xt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(xt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(Es,{title:"App Text",children:[s.jsx(xt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(xt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(xt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(Es,{title:"Borders & Accent",children:[s.jsx(xt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(xt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(xt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Es,{title:"Chat Bubbles",children:[s.jsx(xt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(xt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),s.jsx(xt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(xt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(Es,{title:"Chat Layout",children:[s.jsx(xt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(xt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(xt,{label:"Input border",value:n.inputBorder,onChange:c=>i("inputBorder",c)}),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:c=>i("bubbleRadius",Number(c.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 c=e?oa:ia,d=Pt(e?"light":"dark");e?yr(c,d):yr(d,c),a(c),ns(c),t(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:"Reset to defaults"})]})}function up(){const[e,t]=o.useState(Rr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Pt("dark"));o.useEffect(()=>{n(as());const d=new MutationObserver(()=>{const x=as();n(x);const m=Rr();m==="custom"?ns(Pt(x?"dark":"light")):Vs(m,x?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const f=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const x=as();n(x);const m=Rr();m==="custom"?ns(Pt(x?"dark":"light")):Vs(m,x?"dark":"light")};return f.addEventListener("change",u),()=>{d.disconnect(),f.removeEventListener("change",u)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?ns(Pt(r?"dark":"light")):(Oa(),Vs(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Pt(r?"dark":"light"))},[r]);const c=d=>{t(d),cp(d)},l=[...op,{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:l.map(d=>{const f=e===d.id,u=r?d.preview.dark:d.preview.light,x=d.id==="honey"||d.id==="ember"?"#1a1a1a":d.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>c(d.id),className:"text-left rounded-xl p-3 transition-all",style:{background:f?"var(--bg-glass-hover)":"var(--bg-glass)",border:f?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:f?1:.75},children:[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:x},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:[f&&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(dp,{dark:r,onColorsChange:d=>i(d)})]})}const Wa="adhdev_mobileDashboardMode_v1",ca="adhdev:mobile-dashboard-mode-change";function Ha(){try{return localStorage.getItem(Wa)==="workspace"?"workspace":"chat"}catch{return"chat"}}function mp(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??Ha())},r=a=>{const i=a.detail;t(i)},n=a=>{a.key&&a.key!==Wa||t()};return window.addEventListener(ca,r),window.addEventListener("storage",n),()=>{window.removeEventListener(ca,r),window.removeEventListener("storage",n)}}function fp(e){try{localStorage.setItem(Wa,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(ca,{detail:e}))}function pp(){const[e,t]=o.useState(!0);return o.useEffect(()=>{t(Ha()==="chat")},[]),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ut,{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),fp(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const kn=new Map,Wo=new Map;function hp(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 xp(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 Bc(){const{sendCommand:e}=wt(),{injectEntries:t,getIdes:r}=Ys();return o.useCallback(async(n,a)=>{if(!n)return;const i=(a==null?void 0:a.minFreshMs)??Mm,c=Wo.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<i)return;const l=kn.get(n);if(l)return l;const d=(async()=>{const f=await e(n,"get_machine_runtime_stats"),u=hp(f);if(!u)return;const x=r().find(v=>v.id===n),m=xp(x,n,u.machine,u.timestamp||Date.now());t([m]),Wo.set(n,Date.now())})().finally(()=>{kn.delete(n)});return kn.set(n,d),d},[r,t,e])}function bp(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 gp(e,t){const{sendData:r}=wt(),{injectEntries:n,getIdes:a}=Ys(),i=Array.from(new Set(e.filter(Boolean))).join("|");o.useEffect(()=>{if(!(t!=null&&t.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const l=c.map(d=>qt.subscribe({sendData:r},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const x=a().find(v=>v.id===d),m=bp(x,d,u);n([m])}));return()=>{l.forEach(d=>d())}},[i,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function yp(e,t){const{sendData:r}=wt(),[n,a]=o.useState(null),[i,c]=o.useState(!1);return o.useEffect(()=>{if(!e){a(null),c(!1);return}if(!(t!=null&&t.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const d=qt.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},f=>{l&&(clearTimeout(l),l=null),a(f.diagnostics),c(!1)});return d.initialSendAccepted?l=setTimeout(()=>{c(!1)},Rm):c(!1),()=>{l&&clearTimeout(l),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:i,applyDiagnostics:a}}function vp(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Kc(e){const{sendData:t}=wt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=vp(e);if(!a||!e.sessionId||!t){n({});return}const i=qt.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),ks.record({interactionId:c.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:c.status,modalButtonCount:Array.isArray(c.modalButtons)?c.modalButtons.length:0}})});return i.initialSendAccepted||n({}),()=>{i()}},[e.daemonId,e.routeId,e.sessionId,t]),r}const Oc="adhdev_hiddenTabs";function wp(){try{const e=localStorage.getItem(Oc);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ps(e){try{localStorage.setItem(Oc,JSON.stringify([...e]))}catch{}}function Sn(e){return Ca(e)}function Fa(e,t){return ws(t).some(r=>e.has(r))}function jp(){const[e,t]=o.useState(wp),r=o.useCallback(f=>{const u=Sn(f);t(x=>{const m=new Set(x);return m.has(u)?m.delete(u):m.add(u),ps(m),m})},[]),n=o.useCallback(f=>{const u=Sn(f);t(x=>{if(x.has(u))return x;const m=new Set(x);return m.add(u),ps(m),m})},[]),a=o.useCallback(f=>{const u=Sn(f);t(x=>{if(!x.has(u))return x;const m=new Set(x);return m.delete(u),ps(m),m})},[]),i=o.useCallback(()=>{t(f=>{if(f.size===0)return f;const u=new Set;return ps(u),u})},[]),c=o.useCallback((f,u)=>{t(x=>{const m=new Set(x);for(const v of u)m.add(v);return ps(m),m})},[]),l=o.useCallback((f,u)=>{t(x=>{const m=new Set(x);for(const v of u)m.delete(v);return ps(m),m})},[]),d=o.useCallback(f=>Fa(e,f),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:d}}function Wc(e){return e instanceof Error?e.message:String(e||"")}function Hc(e){const t=Wc(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 Fc(e){const t=Wc(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Uc({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!Ze(e)||Xe(e))return;const i=Ls(e);if(i===t)return;const c=e.sessionId;c&&a(l=>({...l,[c]:t}));try{await n(fs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Kt(e),mode:t})}catch(l){const d=Fc(l);c&&!d&&a(f=>{const u={...f};return i===zc(r,c)?delete u[c]:u[c]=i,u}),Hc(l)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",l instanceof Error?l.message:String(l)):console.error("Failed to switch CLI view mode:",l)}}function Ho(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 kp(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 i=Ho(a,t),c=Array.isArray(a.childSessions)?a.childSessions.map(d=>Ho(d,t)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function zc(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 Sp(e,t){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,i]of Object.entries(e))zc(t,a)===i&&(delete n[a],r=!0);return r?n:e}function Np({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{Xi()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:gc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Uu(a),o.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{r(l=>{const d=Date.now(),f={};for(const[u,x]of Object.entries(l))d-x<5e3&&(f[u]=x);return Object.keys(f).length===Object.keys(l).length?l:f})},5500);return()=>clearTimeout(c)},[t,r]),o.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const d=l.filter(f=>f.timestamp>c).slice(-100);return d.length===l.length?l:d})},6e4);return()=>clearInterval(i)},[n]),null}function Cp(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=r.get(n.id);if(!a){r.set(n.id,n);continue}const i=(a.workspace?1:0)+(a.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>i||(n.timestamp||0)>(a.timestamp||0))&&r.set(n.id,n)}return Array.from(r.values())}function Nn(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 Ip(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 Fo(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?Ip(Ss(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 Mp(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||""),Fo(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||""),Fo(r.activeChat)].join(":"))].join("|")}function Ap(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 Tp(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const i of ws({routeId:n.routeId}))r.set(i,a);for(const i of ws({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of ws({tabKey:n.tabKey}))r.set(i,n)}return r}function Lp(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Rp(e){const t=Lp(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=Ss(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Pp({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=o.useMemo(()=>Cp(e),[e]),i=o.useMemo(()=>Nc(e),[e]),c=o.useRef([]),l=o.useRef([]),d=o.useRef([]),f=o.useRef(new Map),u=o.useRef(new Map),x=o.useMemo(()=>{const A=new Map,y=[];for(const g of a){const{connectionState:E="new",machineName:M}=Cc(g,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),C=Mp(g),R=f.current.get(g.id);if(R&&R.ide===g&&R.sourceSignature===C&&R.connectionState===E&&R.machineName===M){A.set(g.id,R),y.push(...R.conversations);continue}const K=Ba(g,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),z={ide:g,sourceSignature:C,connectionState:E,machineName:M,conversations:K};A.set(g.id,z),y.push(...K)}f.current=A;const I=new Map,k=g=>{const E=Rp(g),M=u.current.get(g.tabKey);if(M&&M.signature===E)return I.set(g.tabKey,M),M.timestamp;const C={signature:E,timestamp:oc(g)||(M==null?void 0:M.timestamp)||0};return I.set(g.tabKey,C),C.timestamp},w=[...y].sort((g,E)=>ic(g,E,k));return u.current=I,w},[a,t,i]),m=o.useMemo(()=>{const A=Ap(x,r);return Nn(c.current,A)?c.current:(c.current=A,A)},[x,r]),v=o.useMemo(()=>{const A=new Map,y=Array.from(new Set(m.map(I=>I.routeId)));for(const I of y){const k=_t(m,I);k&&A.set(I,k)}return A},[m]),S=o.useMemo(()=>{const A=new Map;for(const y of m){const I=v.get(y.routeId),k=y.streamSource==="native"&&I?I:y;for(const w of ws({providerSessionId:y.providerSessionId,sessionId:y.sessionId}))A.set(w,k)}return A},[m,v]),p=o.useMemo(()=>Tp(m,v),[m,v]),h=o.useCallback(A=>{if(A)return S.get(A)},[S]),j=o.useCallback(A=>{if(A)return p.get(A)},[p]),b=o.useMemo(()=>{const A=m.filter(y=>!Fa(n,y));return Nn(l.current,A)?l.current:(l.current=A,A)},[m,n]),N=o.useMemo(()=>{const A=b.map(y=>y.tabKey);return Nn(d.current,A)?d.current:(d.current=A,A)},[b]);return{chatIdes:a,conversations:m,visibleConversations:b,visibleTabKeys:N,resolveConversationBySessionId:h,resolveConversationByTarget:j}}function _p({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:r,setSearchParams:n}){const a=o.useMemo(()=>{var l;return e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),i=o.useMemo(()=>{var l;return!e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),c=o.useCallback(()=>{t&&n(l=>{const d=new URLSearchParams(l);return d.delete("activeTab"),d},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function Dp({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){o.useEffect(()=>{lt.setIdes(e)},[e]),o.useEffect(()=>{lt.setResolveAction((a,i,c)=>{t(a,i,c).catch(()=>{})})},[t]),o.useEffect(()=>{const a=lt.onToast(i=>{r(l=>l.some(f=>f.message===i.message&&i.timestamp-f.timestamp<3e3)?l:[...l.slice(-4),{id:i.id,message:i.message,type:i.type,timestamp:i.timestamp,targetKey:i.targetKey,actions:i.actions}]);const c=i.duration||5e3;setTimeout(()=>r(l=>l.filter(d=>d.id!==i.id)),c)});return()=>{a()}},[r]),o.useEffect(()=>{const a=hc.on("status_event",i=>{lt.handleRawEvent(i,"ws")});return()=>{a()}},[]),o.useEffect(()=>{var i;const a=c=>{var p;const l=c.data;if((l==null?void 0:l.type)!=="notification_action"||typeof l.action!="string"||!l.action.startsWith("approval_")||!(l.daemonId||l.targetSessionId||l.targetKey))return;const d=l.targetSessionId||l.targetKey||l.daemonId,f=n(d),u=(f==null?void 0:f.routeId)||l.daemonId;if(!u)return;const x=Number(l.buttonIndex),m=l.button||((p=f==null?void 0:f.modalButtons)==null?void 0:p[x])||"Approve",v=String(m).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),S=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(v);t(u,"resolve_action",{action:S?"approve":"reject",button:m,...Number.isFinite(x)&&{buttonIndex:x},...(f==null?void 0:f.sessionId)&&{targetSessionId:f.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(h=>console.error("[SW Action] approval failed:",h))};return(i=navigator.serviceWorker)==null||i.addEventListener("message",a),()=>{var c;return(c=navigator.serviceWorker)==null?void 0:c.removeEventListener("message",a)}},[n,t])}const Ep="adhdev_dashboardLayout_v1",$p="adhdev_dashboardDockview_v1",Bp="adhdev_dashboardDockviewHiddenRestore_v1",$s={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Ua(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function Kp(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Vc(e){return`${Ep}:${e}`}function Op(e){const t=Vc(e);return Ua(t,null)}function Wp(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=Vc(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Gc(e){return`${$p}:${e}`}function Hp(e){const t=Gc(e);return Ua(t,null)}function Fp(e,t){try{const r=Gc(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function qc(e){return`${Bp}:${e}`}function Up(e){const t=qc(e);return Ua(t,{})}function zp(e,t){try{const r=qc(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Vp(){return{groupAssignments:[...$s.groupAssignments],focusedGroup:$s.focusedGroup,groupActiveTabIds:{...$s.groupActiveTabIds},groupTabOrders:{...$s.groupTabOrders},groupSizes:[...$s.groupSizes]}}function Gp(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function qp(){const[e]=o.useState(()=>Kp(typeof window<"u"?window.innerWidth:1280)),[t,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,d]=o.useState({}),[f,u]=o.useState([]),[x,m]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[v,S]=o.useState(!1),p=o.useCallback(()=>{if(v)return;const g=Op(e)??Vp();r(new Map(g.groupAssignments)),a(g.focusedGroup),c(g.groupActiveTabIds),d(g.groupTabOrders),u(g.groupSizes),S(!0)},[v,e]);o.useEffect(()=>{v&&Wp(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:f})},[v,e,t,n,i,l,f]),o.useEffect(()=>{const g=window.matchMedia("(max-width: 767px)"),E=M=>m(M.matches);return g.addEventListener("change",E),()=>g.removeEventListener("change",E)},[]);const h=o.useCallback(g=>{r(g)},[]),j=o.useCallback(g=>{a(g)},[]),b=o.useCallback(g=>{c(g)},[]),N=o.useCallback(g=>{d(g)},[]),A=o.useCallback(g=>{u(g)},[]),y=o.useCallback(g=>{j(g)},[j]),I=o.useCallback((g,E)=>{c(M=>(M[g]??null)===(E??null)?M:{...M,[g]:E})},[]),k=o.useCallback((g,E)=>{d(M=>{const C=M[g];return Gp(C,E)?M:{...M,[g]:E}})},[]),w=o.useCallback((g,E)=>{const M=E.get(g)??0;return I(M,g),y(M),M},[y,I]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:h,focusedGroup:n,updateFocusedGroup:j,focusGroup:y,groupActiveTabIds:i,updateGroupActiveTabIds:b,setGroupActiveTab:I,groupTabOrders:l,updateGroupTabOrders:N,setGroupTabOrder:k,groupSizes:f,updateGroupSizes:A,isMobile:x,hasHydratedStoredLayout:v,hydrateStoredLayout:p,focusConversationTab:w}}function Yp(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=Na(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Xp({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,focusConversationTab:c,setSearchParams:l,historyModalOpen:d,activeConv:f,isRefreshingHistory:u,ides:x,handleRefreshHistory:m}){const v=o.useRef(!1),S=o.useRef(!1),p=o.useRef(null),h=o.useRef(!1);o.useEffect(()=>{if(!e||v.current||t.length===0)return;if(!a){i();return}const j=r(e);j&&(c(j.tabKey,n),v.current=!0,S.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),l(b=>{const N=new URLSearchParams(b);return N.delete("activeTab"),N},{replace:!0}))},[e,t,r,n,a,i,c,l]),o.useEffect(()=>{if(!(S.current||a)&&t.length!==0){if(!e){i(),S.current=!0;return}if(v.current){S.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(S.current||a)&&(i(),S.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,t.length,a,i]),o.useEffect(()=>{if(!d){h.current=!1;return}if(!f||h.current||u)return;const j=x.find(b=>b.id===f.routeId);j&&(!j.chats||j.chats.length===0||Yp(j.chats,f))&&(h.current=!0,m())},[d,f,u,x,m]),o.useEffect(()=>{if(!f)return;let j=null,b=0,N=-1,A=0;const y=()=>{j=null;const I=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(w=>w.offsetParent!==null);if(I.length===0){b<18&&(b+=1,j=requestAnimationFrame(y));return}let k=0;for(const w of I)w.scrollTop=w.scrollHeight,k+=w.scrollHeight;k===N?A+=1:(A=0,N=k),b+=1,!(A>=2||b>=18)&&(j=requestAnimationFrame(y))};return j=requestAnimationFrame(y),()=>{j!=null&&cancelAnimationFrame(j)}},[f==null?void 0:f.tabKey])}function Cn(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=Na(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Yc({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:i}){const[c,l]=o.useState(!1),[d,f]=o.useState(!1),u=o.useCallback(async S=>{try{await e("standalone","launch_ide",{ideType:S,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),x=o.useCallback(async(S,p)=>{try{const h=S||(t==null?void 0:t.daemonId)||"",j=await e(h,"switch_chat",{id:p,sessionId:p,...js(t)}),b=j==null?void 0:j.result;if((j==null?void 0:j.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?Ds(a,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?Ds(a,`⚠️ Switch error: ${b}`):Ds(a,"⚠️ Session switch failed")}catch(h){console.error("Switch failed",h),Ds(a,`❌ Switch failed: ${h.message||"connection error"}`)}},[t,e,a]),m=o.useCallback(async()=>{if(!(!t||c)){l(!0);try{const S=Zs(t);await e(S,"new_chat",{...js(t)}),i(p=>({...p,[t.tabKey]:Date.now()}))}catch(S){console.error("New chat failed",S)}finally{l(!1)}}},[t,c,e,i]),v=o.useCallback(async()=>{var S,p;if(!(!t||d)){f(!0);try{const h=Zs(t),j=async()=>e(h,"list_chats",{forceExpand:!0,...js(t)});let b=await j(),N=(b==null?void 0:b.chats)||((S=b==null?void 0:b.result)==null?void 0:S.chats);Cn(N,t)&&(await new Promise(A=>setTimeout(A,450)),b=await j(),N=(b==null?void 0:b.chats)||((p=b==null?void 0:b.result)==null?void 0:p.chats)),b!=null&&b.success&&Array.isArray(N)&&(n(t.routeId,N),Cn(N,t)&&!Cn(r,t)&&Ds(a,"⚠️ History dialog did not fully open — try once more"))}catch(h){console.error("Refresh history failed",h)}finally{f(!1)}}},[t,r,d,e,n,a]);return{isCreatingChat:c,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:x,handleNewChat:m,handleRefreshHistory:v}}function Jp(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 Qp(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function Uo(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 vr(e,t){const r=new Set(t),n=t.length>0?[0]:[];for(const[c,l]of e)!r.has(c)||l<=0||n.includes(l)||n.push(l);n.sort((c,l)=>c-l);const a={};n.forEach((c,l)=>{a[c]=l}),n.length===0&&(a[0]=0);const i=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const d=a[l];typeof d=="number"&&d>0&&i.set(c,d)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function zo(e,t){const r={};for(const[n,a]of Object.entries(e)){const i=t[Number(n)];typeof i=="number"&&(r[i]=a)}return r}function Zp(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 eh(e,t,r){if(t.length<=1)return[];const n=t.map(c=>e[c]).filter(c=>Number.isFinite(c)),a=n.length===t.length?n:Array(r).fill(100/r),i=a.reduce((c,l)=>c+l,0);return i>0?a.map(c=>c/i*100):Array(r).fill(100/r)}function Vo(e,t){const r={};for(const[n,a]of Object.entries(e)){const i=Number(n);r[i>=t?i+1:i]=a}return r}function Go(e){return Array(e).fill(100/e)}function th({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:i,updateGroupSizes:c,isMobile:l,visibleConversations:d,visibleTabKeys:f}){const u=o.useRef(null),x=o.useMemo(()=>vr(e,f),[e,f]),m=x.assignments,v=o.useMemo(()=>l?1:x.groupCount,[x.groupCount,l]),S=v>1,p=o.useCallback((y,I)=>{t(k=>{const w=new Map(vr(k,f).assignments);return I===0?w.delete(y):w.set(y,I),w}),n(k=>({...k,[I]:y})),r(I)},[t,f,n,r]),h=o.useCallback(y=>{t(I=>{const k=vr(I,f).assignments,w=new Map;for(const[g,E]of k)E!==y&&(E>y?w.set(g,E-1):w.set(g,E));return w}),c(I=>{if(I.length<=1)return[];const k=[...I];k.splice(y,1);const w=k.reduce((g,E)=>g+E,0);return w>0?k.map(g=>g/w*100):[]}),r(0)},[t,f,c,r]),j=o.useCallback((y,I)=>{I.preventDefault();const k=u.current;if(!k)return;const w=I.clientX,g=k.offsetWidth,E=i.length===v?[...i]:Go(v),M=R=>{const z=(R.clientX-w)/g*100,T=[...E];T[y]=Math.max(15,E[y]+z),T[y+1]=Math.max(15,E[y+1]-z),c(T)},C=()=>{document.removeEventListener("mousemove",M),document.removeEventListener("mouseup",C),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",M),document.addEventListener("mouseup",C)},[i,v,c]),b=o.useCallback((y,I,k)=>{if(v>=4)return;const w=k==="left"?I:I+1;t(g=>{const E=vr(g,f).assignments,M=new Map;for(const C of d){const R=E.get(C.tabKey)??0,K=R>=w?R+1:R;K>0&&M.set(C.tabKey,K)}return w>0&&M.set(y,w),M}),c(g=>{const E=g.length===v?[...g]:Go(v),M=E[I]??100/v,C=Math.max(15,M/2),R=Math.max(15,M/2),K=[...E];K[I]=C,K.splice(w,0,R);const z=K.reduce((T,L)=>T+L,0);return K.map(T=>T/z*100)}),n(g=>{const E=Vo(g,w);return E[w]=y,E}),a(g=>{const E=Vo(g,w);return E[w]=[y],E}),r(w)},[v,t,f,d,c,n,a,r]);o.useEffect(()=>{Jp(e,m)||t(m)},[e,m,t]),o.useEffect(()=>{const{mapping:y,usedGroups:I}=x;n(k=>{const w=zo(k,y);return Uo(k,w)?k:w}),a(k=>{const w=zo(k,y);return Uo(k,w)?k:w}),r(k=>{const w=l?0:Zp(k,I,y);return k===w?k:w}),c(k=>{const w=l?[]:eh(k,I,x.groupCount);return Qp(k,w)?k:w})},[x,l,n,a,r,c]);const N=o.useMemo(()=>{const y=Array.from({length:v},()=>[]);for(const I of d){const k=m.get(I.tabKey)??0,w=Math.min(k,v-1);y[w].push(I)}return y},[d,m,v]),A=o.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:u,normalizedGroupAssignments:m,numGroups:v,isSplitMode:S,groupedConvs:N,moveTabToGroup:p,closeGroup:h,handleResizeStart:j,splitTabRelative:b,clearAllSplits:A}}function sh({ides:e,sendDaemonCommand:t}){const r="0.9.27",n=o.useMemo(()=>e.filter(u=>u.type!=="adhdev-daemon"?!1:_c(u,r)).sort((u,x)=>Number(zs(x,r))-Number(zs(u,r))),[r,e]),a=o.useMemo(()=>n.some(u=>zs(u,r)),[r,n]),[i,c]=o.useState(!1),[l,d]=o.useState({}),f=o.useCallback(async u=>{var x,m;d(v=>({...v,[u]:"upgrading"}));try{const v=await t(u,"daemon_upgrade",{});(x=v==null?void 0:v.result)!=null&&x.upgraded||(m=v==null?void 0:v.result)!=null&&m.success?d(S=>({...S,[u]:"done"})):d(S=>({...S,[u]:"error"}))}catch{d(v=>({...v,[u]:"error"}))}},[t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:f}}const Xc=80;function Pr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function rh(e){return{...e,createdAt:Pr(e.createdAt),updatedAt:Pr(e.updatedAt,e.createdAt),lastEventAt:Pr(e.lastEventAt,e.updatedAt||e.createdAt)}}function nh(e){const t=Ca(e);return t==="unknown:"?e.id:t}function ah(e){return[e.type,ac(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function oh(e,t=Xc){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=nh(n),i=r.get(a);if(!i){r.set(a,n);continue}(n.updatedAt>i.updatedAt||n.updatedAt===i.updatedAt&&n.createdAt>i.createdAt)&&r.set(a,n)}return Array.from(r.values()).sort((n,a)=>{const i=a.updatedAt-n.updatedAt;return i!==0?i:a.createdAt-n.createdAt}).slice(0,Math.max(0,t))}function ih(e,t){const r=Date.now(),n=[];for(const a of e){const i=a.sessionId?t.get(a.sessionId):void 0;if(i!=null&&i.surfaceHidden)continue;const c=Qr(a,t),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const d=Pr(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),f=ah({type:l,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(i==null?void 0:i.lastUpdated)||a.lastUpdated});n.push(rh({id:f,dedupKey:f,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:tc(a),preview:pm(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return oh(n)}function ch(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function lh(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=Xc}=e,a=o.useMemo(()=>ih(t,r).slice(0,Math.max(0,n)),[t,r,n]),i=o.useMemo(()=>ch(a),[a]);return{notifications:a,unreadCount:i}}function dh({notifications:e,sendDaemonCommand:t}){const r=o.useCallback(i=>{const c=e.find(d=>d.id===i),l=Math.max(Date.now(),(c==null?void 0:c.updatedAt)||0);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_session_seen",{sessionId:c.sessionId,seenAt:l}).catch(()=>{})},[e,t]),n=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_notification_unread",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]),a=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"delete_notification",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}function tn(...e){const t=new Set,r=[],n=a=>{const i=typeof a=="string"?a.trim():"";if(!i)return;const c=i.toLowerCase();t.has(c)||(t.add(c),r.push(i))};for(const a of e){if(Array.isArray(a)){for(const i of a)n(i);continue}n(a)}return r}function uh(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 sn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=uh(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 mh(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 fh(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function rn(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=fh(n);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(n==null?void 0:n.error)||"Could not browse folder");const i=typeof(a==null?void 0:a.path)=="string"?a.path:r,c=i.includes("\\")?"\\":"/",l=(f,u)=>/^[A-Za-z]:\\?$/.test(f)?`${f.replace(/\\?$/,"\\")}${u}`:f==="/"||f==="\\"?`${c}${u}`:`${f.replace(/[\\/]+$/,"")}${c}${u}`,d=Array.isArray(a==null?void 0:a.files)?a.files.filter(f=>(f==null?void 0:f.type)==="directory"&&typeof(f==null?void 0:f.name)=="string").map(f=>({name:f.name,path:typeof(f==null?void 0:f.path)=="string"&&f.path.trim()?f.path:l(i,f.name)})).sort((f,u)=>f.name.localeCompare(u.name)):[];return{path:i,directories:d}}function ph(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function qo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function hh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function xh({ides:e,conversations:t,onOpenSession:r}){const[n,a]=o.useState(null),i=o.useCallback(c=>{a(c)},[]);return o.useEffect(()=>{if(!n)return;const c=qo(n.workspacePath),l=e.find(f=>{var S,p,h,j;if(!f||f.type==="adhdev-daemon"||ph(f.daemonId||f.id)!==n.machineId||(Qs(f)?"cli":ys(f)?"acp":"ide")!==n.kind||String(f.agentType||f.type||"")!==n.providerType)return!1;if(n.resumeSessionId)return String(f.providerSessionId||"")===n.resumeSessionId;if(c){const b=qo(f.workspace||f.runtimeWorkspaceLabel);return b?b===c:!1}return Number(f.lastUpdated||f._lastUpdate||f.timestamp||((j=(h=(p=(S=f.activeChat)==null?void 0:S.messages)==null?void 0:p.at)==null?void 0:h.call(p,-1))==null?void 0:j.timestamp)||0)>=n.startedAt-5e3});if(!l)return;const d=cc({entrySessionId:l.sessionId,entryInstanceId:l.instanceId,entryRouteId:l.id,conversations:t});d&&(a(null),r(d))},[t,e,r,n]),o.useEffect(()=>{if(!n)return;const c=window.setTimeout(()=>{a(l=>!l||l.startedAt!==n.startedAt?l:null)},45e3);return()=>window.clearTimeout(c)},[n]),{trackPendingLaunch:i}}function bh({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:i}){const c=o.useCallback(async(m,v)=>rn(e,m,v),[e]),l=o.useCallback(async(m,v)=>{if(!v.trim())return{ok:!1,error:"Choose a workspace path first."};try{const S=await e(m,"workspace_add",{path:v.trim()});return S!=null&&S.success?{ok:!0}:{ok:!1,error:(S==null?void 0:S.error)||"Could not save workspace"}}catch(S){return{ok:!1,error:S instanceof Error?S.message:"Could not save workspace"}}},[e]),d=o.useCallback(async(m,v,S)=>{var p;try{const h={ideType:v,enableCdp:!0};(p=S==null?void 0:S.workspacePath)!=null&&p.trim()&&(h.workspace=S.workspacePath.trim());const j=await e(m,"launch_ide",h);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:m,kind:"ide",providerType:v,workspacePath:(S==null?void 0:S.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(h){return{ok:!1,error:h instanceof Error?h.message:"Could not launch IDE"}}},[e,t]),f=o.useCallback(async(m,v,S,p)=>{var j,b,N;const h=Date.now();try{const A={cliType:S};(j=p==null?void 0:p.workspacePath)!=null&&j.trim()?A.dir=p.workspacePath.trim():p!=null&&p.workspaceId&&(A.workspaceId=p.workspaceId),(b=p==null?void 0:p.resumeSessionId)!=null&&b.trim()&&(A.resumeSessionId=p.resumeSessionId.trim()),Array.isArray(p==null?void 0:p.cliArgs)&&p.cliArgs.length>0&&(A.cliArgs=p.cliArgs),(N=p==null?void 0:p.initialModel)!=null&&N.trim()&&(A.initialModel=p.initialModel.trim());const y=await e(m,"launch_cli",A),I=(y==null?void 0:y.result)||y,k=(I==null?void 0:I.sessionId)||(I==null?void 0:I.id);return y!=null&&y.success&&k?(r(k),{ok:!0}):y!=null&&y.success?(t({machineId:m,kind:v,providerType:S,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:h}),{ok:!0}):{ok:!1,error:(y==null?void 0:y.error)||(I==null?void 0:I.error)||`Could not launch ${v.toUpperCase()} session`}}catch(A){return hh(A)?(t({machineId:m,kind:v,providerType:S,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:h}),{ok:!0}):{ok:!1,error:A instanceof Error?A.message:`Could not launch ${v.toUpperCase()} session`}}},[r,e,t]),u=o.useCallback(async(m,v)=>{if(!m||!v)return[];try{const S=await e(m,"list_saved_sessions",{providerType:v,kind:"cli",limit:30}),p=(S==null?void 0:S.result)??S;return Array.isArray(p==null?void 0:p.sessions)?p.sessions:[]}catch(S){return console.error("List saved sessions failed",S),[]}},[e]),x=o.useCallback(async m=>{await Uc({conversation:n,mode:m,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:i})},[n,a,e,i]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:l,handleLaunchMachineIde:d,handleLaunchMachineProvider:f,handleListMachineSavedSessions:u,setActiveCliViewMode:x}}function gh(e){switch(e){case"notification-open":case"toast-open":case"conversation-open":case"requested-tab":case"dockview-shortcut":case"dockview-focus":case"dockview-move":case"dockview-split":return!0;case"stored-layout-restore":case"passive-tab-sync":return!1;default:return!1}}function yh(e,t,r=Date.now()){return!e||!gh(t)?null:{tabKey:e,nonce:r}}function vh({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:i,setSearchParams:c}){const[l,d]=o.useState(null),[f,u]=o.useState(null),x=o.useMemo(()=>{var h,j;if(!e){if(l){const b=t.find(N=>N.tabKey===l);if(b)return b}return r[0]}const p=n[a];if(p){const b=t.find(N=>N.tabKey===p);if(b)return b}return((h=i[a])==null?void 0:h[0])||((j=i[0])==null?void 0:j[0])},[t,l,a,n,i,e,r]),m=o.useCallback(p=>{d(p)},[]),v=o.useCallback(p=>{d(p.tabKey),c(h=>{const j=new URLSearchParams(h),b=xm(p);return b?j.set("activeTab",b):j.delete("activeTab"),j},{replace:!0})},[c]),S=o.useCallback((p,h)=>{const j=yh(p,h);j&&u(j)},[]);return{activeConv:x,openDesktopConversation:v,requestScrollToBottom:S,scrollToBottomRequest:f,setDesktopActiveTab:m}}function wh({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:i,setToasts:c,setClearedTabs:l,setSearchParams:d}){var T;const[f,u]=o.useState(!1),[x,m]=o.useState([]),[v,S]=o.useState(()=>ht()),[p,h]=o.useState(!1),[j,b]=o.useState(null),N=o.useRef(null),A=o.useMemo(()=>r||t||e,[e,r,t]),y=!!A&&Ze(A)&&!Xe(A),I=o.useMemo(()=>{if(!A||!y)return null;const L=A.daemonId||A.routeId||"",Y=Kt(A);return`${L}:${Y}`},[A,y]),{isCreatingChat:k,isRefreshingHistory:w,handleSwitchSession:g,handleNewChat:E,handleRefreshHistory:M}=Yc({sendDaemonCommand:a,activeConv:A,chats:(T=n.find(L=>L.id===(A==null?void 0:A.routeId)))==null?void 0:T.chats,updateRouteChats:i,setToasts:c,setClearedTabs:l}),C=o.useCallback(()=>{u(!0)},[]),R=o.useCallback(()=>{u(!1)},[]),K=o.useCallback(async()=>{if(!(!A||!y||p)){h(!0);try{const L=A.daemonId||A.routeId,Y=Kt(A),O=await a(L,"list_saved_sessions",{agentType:Y,providerType:Y,kind:"cli",limit:50}),D=(O==null?void 0:O.result)??O;m(Array.isArray(D==null?void 0:D.sessions)?D.sessions:[])}catch(L){console.error("Refresh saved sessions failed",L),m([])}finally{h(!1)}}},[A,p,y,a]);o.useEffect(()=>{if(!f){N.current=null;return}if(!y){N.current=null,m([]),h(!1);return}!I||p||N.current!==I&&(N.current=I,K())},[K,f,p,y,I]);const z=o.useCallback(async L=>{if(!A||!y||!L.providerSessionId||!L.workspace)return;const Y=A.daemonId||A.routeId,O=Kt(A);try{b(L.providerSessionId);const D=await a(Y,"launch_cli",{cliType:O,dir:L.workspace,resumeSessionId:L.providerSessionId,initialModel:qi(L.summaryMetadata,"model",{preferShortValue:!0})||void 0}),W=(D==null?void 0:D.result)??D,Q=typeof(W==null?void 0:W.sessionId)=="string"?W.sessionId:typeof(W==null?void 0:W.id)=="string"?W.id:"";Q&&d(be=>{const pe=new URLSearchParams(be);return pe.set("activeTab",Q),pe},{replace:!0}),R()}catch(D){console.error("Resume saved session failed",D)}finally{b(null)}},[R,A,y,a,d]);return{historyModalOpen:f,openHistoryModal:C,closeHistoryModal:R,historyTargetConv:A,isSavedSessionHistoryTarget:y,isHistoryCreatingChat:k,isHistoryRefreshingHistory:w,handleHistorySwitchSession:g,handleHistoryNewChat:E,handleHistoryRefresh:M,savedHistorySessions:x,savedHistoryFilters:v,setSavedHistoryFilters:S,isSavedHistoryLoading:p,resumingSavedHistorySessionId:j,handleRefreshSavedHistory:K,handleResumeSavedHistorySession:z}}function jh({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[d,f]=o.useState(null),[u,x]=o.useState(null),m=o.useMemo(()=>{if(e||!n)return null;const j=l(n);return j&&!Ze(j)&&!Xe(j)?j:null},[e,n,l]),v=o.useMemo(()=>{const j=d==null?void 0:d.routeId;if(!j)return null;const b=d!=null&&d.tabKey?i.find(N=>N.tabKey===d.tabKey):a?i.find(N=>N.tabKey===a):null;return(b==null?void 0:b.routeId)===j?b:_t(i,j)},[i,d,a]),S=o.useMemo(()=>{if(v)return c.find(j=>j.id===v.routeId)},[c,v]);o.useEffect(()=>{m&&(f({routeId:m.routeId,tabKey:Co(m)}),x(m),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,m]);const p=o.useCallback(j=>{j&&(f({routeId:j.routeId,tabKey:Co(j)}),x(j))},[]),h=o.useCallback(()=>{f(null),x(null)},[]);return{remoteDialogConv:v,remoteDialogIdeEntry:S,remoteDialogActiveConv:u,setRemoteDialogActiveConv:x,openRemoteDialog:p,closeRemoteDialog:h}}function kh({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l,activeConv:d,sendDaemonCommand:f}){const{remoteDialogConv:u,remoteDialogIdeEntry:x,remoteDialogActiveConv:m,setRemoteDialogActiveConv:v,openRemoteDialog:S,closeRemoteDialog:p}=jh({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}),[h,j]=o.useState(!1),[b,N]=o.useState(null),A=o.useCallback(async k=>{const w=k||d;!w||!Ze(w)&&!Xe(w)||(N(w),j(!0))},[d]),y=o.useCallback(()=>{j(!1),N(null)},[]),I=o.useCallback(async k=>{const w=b||d;if(!w||!Ze(w)&&!Xe(w)){y();return}j(!1);try{const g=Kt(w),E=w.routeId||w.daemonId||"";await f(E,"stop_cli",{cliType:g,targetSessionId:w.sessionId,mode:k})}catch(g){console.error("Stop CLI failed:",g)}finally{N(null)}},[d,y,b,f]);return{remoteDialogConv:u,remoteDialogIdeEntry:x,remoteDialogActiveConv:m,setRemoteDialogActiveConv:v,openRemoteDialog:S,closeRemoteDialog:p,cliStopDialogOpen:h,cliStopTargetConv:b,requestCliStop:A,cancelCliStop:y,confirmCliStop:I}}function Jc(){return"select_session"}function Sh(){return"open_panel"}function Nh({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function Ch(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function Yo(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function Xo(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function za(e){return e instanceof Error?e.message:String(e||"")}function Jo(e){const t=za(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Qo(e,t){const r=za(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function nn({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,i]=o.useState(!1),[c,l]=o.useState(!1),[d,f]=o.useState(null),u=o.useRef(!1),x=o.useRef(null);o.useEffect(()=>{f(null)},[t==null?void 0:t.tabKey]);const m=o.useCallback(async h=>{if(!t)return!1;const j=h.trim(),b=Aa(t);if(Nh({hasMessage:!!j,blockedMessage:b,sendInFlight:u.current}))return b&&f(b),!1;const N=Date.now(),A={tabKey:t.tabKey,message:j,timestamp:N};if(Ch(x.current,A))return f(null),!0;u.current=!0,l(!0),f(null),x.current=A;try{const y=Zs(t);if(!y)return x.current=Yo(x.current,A),f("Unable to send message right now."),!1;const I=await e(y,"send_chat",{message:j,...js(t)}),k=Xo(I);if(k!=null&&k.deduplicated)return f(null),!0;if((k==null?void 0:k.sent)===!1)throw new Error((k==null?void 0:k.error)||"Send failed");if((k==null?void 0:k.success)===!1)throw new Error((k==null?void 0:k.error)||"Send failed");return f(null),!0}catch(y){const I=za(y);return I.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",I):console.warn("Send blocked/failed",y),x.current=Yo(x.current,A),f(Dm(y)),!1}finally{u.current=!1,l(!1)}},[t,e]),v=o.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(h){console.error("Relaunch failed",h)}},[t,e]),S=o.useCallback(async h=>{if(t)try{const b=(t.modalButtons||[]).indexOf(h),N=h.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),A=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(N),y=Zs(t);if(!y)return;const I=await e(y,"resolve_action",{button:h,action:A?"approve":"reject",...b>=0&&{buttonIndex:b},...js(t)}),k=Xo(I);k.success||r(w=>[...w,{routeId:t.tabKey,text:Qo(h,k==null?void 0:k.error),timestamp:Date.now()}])}catch(j){Jo(j)||console.error("[ModalButton] Error:",j),r(b=>[...b,{routeId:t.tabKey,text:Jo(j)?Qo(h,j):`❌ **${h}** error`,timestamp:Date.now()}])}},[t,e,r]),p=o.useCallback(async()=>{if(!(!t||a)){i(!0);try{await e(t.routeId,Sh(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(h){console.error("Focus agent failed",h)}finally{i(!1)}}},[t,a,e]);return{isSendingChat:c,sendFeedbackMessage:d,isFocusingAgent:a,handleSendChat:m,handleRelaunch:v,handleModalButton:S,handleFocusAgent:p}}function In(e,t=!0){return(e??!0)&&t}const Va=o.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u=null,handleFocusAgent:x,isFocusingAgent:m,actionLogs:v,userName:S,scrollToBottomRequestNonce:p,isInputActive:h=!0,isVisible:j=!0}){const[b,N]=o.useState(n),A=o.useRef(n);o.useEffect(()=>{const C=A.current;if(A.current=n,!n){N(!1);return}if(C){N(!0);return}N(!1);let R=0,K=0;return R=window.requestAnimationFrame(()=>{K=window.requestAnimationFrame(()=>{N(!0)})}),()=>{window.cancelAnimationFrame(R),window.cancelAnimationFrame(K)}},[n]);const y=n&&b,I=!n||!b,k=In(j,n),w=In(j,I),g=In(j),E=Kc(t),M=E.status||E.modalMessage||E.modalButtons?{...t,...E.status?{status:E.status}:{},...E.modalMessage!==void 0?{modalMessage:E.modalMessage}:{},...E.modalButtons!==void 0?{modalButtons:E.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(Fi,{activeConv:M,onModalButton:c}),M.transport!=="pty"&&M.transport!=="acp"&&M.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(Xs,{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:l,children:"Relaunch with CDP"})]})}):null,M.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:y?"visible":"hidden",pointerEvents:y?"auto":"none"},children:s.jsx(pf,{activeConv:M,clearToken:r,terminalRef:i,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u,isVisible:k,isInputActive:h&&k})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:I?"visible":"hidden",pointerEvents:I?"auto":"none"},children:s.jsx(na,{activeConv:M,ideEntry:a,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u,handleFocusAgent:x,isFocusingAgent:m,actionLogs:v,userName:S,scrollToBottomRequestNonce:p,isInputActive:h&&w,isVisible:w})})]}):s.jsx(na,{activeConv:M,ideEntry:a,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u,handleFocusAgent:x,isFocusingAgent:m,actionLogs:v,userName:S,scrollToBottomRequestNonce:p,isInputActive:h&&g,isVisible:g})]})},(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 Ih({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:d,onBack:f,onOpenNativeConversation:u,onOpenMachine:x,onOpenHistory:m,onOpenRemote:v,onHideConversation:S,onStopCli:p,cliViewMode:h,onSetCliViewMode:j,handleSendChat:b,handleFocusAgent:N,handleModalButton:A,handleRelaunch:y}){const I=o.useRef(null),k=Ze(e)&&!t,w=k&&h==="terminal",g=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${g} 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(xa,{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:nt(e)}),s.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:s.jsx(lc,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>x(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[k&&h&&s.jsx(Ra,{mode:h,onChange:j,compact:!0}),k&&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(vt,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>m(e),type:"button",children:s.jsx(ba,{size:14})}),!t&&!k&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>v(e),type:"button",children:s.jsx(Nt,{size:14})}),S&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(e),type:"button",title:"Close chat",children:s.jsx(vt,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(Va,{activeConv:e,clearToken:0,isCliTerminal:w,ideEntry:n,terminalRef:I,handleModalButton:A,handleRelaunch:y,handleSendChat:b,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:N,isFocusingAgent:d,actionLogs:a,userName:i})})]})}const Mn={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 Mh(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Qc(){const[e,t]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{t(Mh())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(Mn[c].cmd).catch(()=>{}),i(!0),setTimeout(()=>i(!1),2e3)},[c]);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:l,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:Mn[c].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Mn[c].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 Zc({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Nt},{key:"chats",label:"Chats",icon:Ut}];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:i})=>{const c=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 ${c?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(n),type:"button","aria-pressed":c,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(i,{size:15})}),s.jsx("span",{children:a})]},n)})})})}function wr({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 hs({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 Bs({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 jr({item:e,type:t,getAvatarText:r,onOpenConversation:n}){const a=t==="needs_attention"||t==="task_complete",i=t==="working",c=t==="earlier",l=t==="task_complete",{isReconnecting:d,isConnecting:f}=Ts(e.conversation),u=nt(e.conversation),x=us(e.conversation),m=bc(e.conversation,{requiresAction:t==="needs_attention"}),v=a?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":i?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",S=a?"bg-accent-primary shadow-glow":i?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":c?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",p=c?"text-text-secondary":"text-text-primary",h=c?"text-text-muted":"text-text-secondary",j=c?"text-text-secondary opacity-80":"text-text-muted",b=c?"text-text-muted opacity-80":"text-text-muted",N="text-[color:var(--status-warning)]";return s.jsxs("button",{className:`group flex items-start gap-3.5 px-4 py-3.5 w-full text-left relative overflow-hidden transition-colors active:scale-[0.995] ${v}`,onClick:()=>n(e.conversation),type:"button",children:[a||i?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.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${S}`,style:a?{color:"var(--accent-on-primary)"}:void 0,children:r(u)}),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 truncate tracking-tight ${p}`,children:u}),!i&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${b}`,children:Hi(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${h}`,children:[x,d?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${N} animate-pulse`,children:"Reconnecting…"})]}):f?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):m==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:N,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${j}`,children:e.preview})]}),a&&!l&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),l&&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"}),i&&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 Zo({size:e=32,label:t}){return s.jsxs("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}}),t&&s.jsx("div",{className:"text-xs font-semibold text-accent-primary-light tracking-tight",children:t})]})}function Ah({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:d,onShowConversation:f,onShowAllHidden:u,onOpenNewSession:x,onOpenMachine:m,onOpenSettings:v,onSectionChange:S,wsStatus:p="connected",isStandalone:h=!1}){const j=p==="disconnected"||p==="reconnecting"||p==="offline"||p==="auth_failed",b=c.length>0,N=t.length>0||r.length>0||n.length>0||a.length>0,A=e==="machines"?"Machines":"Chats",y=h?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",I=h?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]";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 ${y}`,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:A}),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(Xr,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:v,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(Yr,{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] ${I}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:j?s.jsx(Bs,{icon:s.jsx(Zo,{label:"Reconnecting…"}),title:"Connecting to server",subtitle:p==="offline"?"Your device appears to be offline. Waiting for network…":p==="auth_failed"?"Session expired. Please log in again.":"Establishing connection to the server. This usually takes a moment."}):c.length===0?s.jsx(Bs,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:h?"Waiting for your daemon":"Connect your machines",subtitle:h?"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:!h&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(Qc,{})})}):s.jsx(hs,{children:c.map((k,w)=>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] ${w>0?"border-t border-border-subtle/70":""}`,onClick:()=>m(k.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:l(k.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:k.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:k.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[k.unread," new"]}):k.total>0?`${k.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:k.subtitle}),k.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[k.total," chat",k.total!==1?"s":"",k.unread>0?` · ${k.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},k.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(wr,{title:"Needs attention",className:"mb-0"}),s.jsx(hs,{children:t.map((k,w)=>s.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"needs_attention",getAvatarText:l,onOpenConversation:d})},k.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(wr,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(hs,{children:r.map((k,w)=>s.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"task_complete",getAvatarText:l,onOpenConversation:d})},k.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(wr,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(hs,{children:n.map((k,w)=>s.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"working",getAvatarText:l,onOpenConversation:d})},k.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(wr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(hs,{children:a.map((k,w)=>s.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"earlier",getAvatarText:l,onOpenConversation:d})},k.conversation.tabKey))}):N?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):j?s.jsx(Bs,{icon:s.jsx(Zo,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):b?s.jsx(Bs,{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(Ut,{size:20})}),title:"No conversations yet",subtitle:vc,children:x&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:x,"aria-label":$t,title:$t,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:$t})]})}):s.jsx(Bs,{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"&&i.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsxs("div",{className:"mx-1 mt-4 mb-1 flex items-center justify-between gap-2 px-1 py-1 text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:[s.jsx("span",{children:"Hidden"}),s.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:u,children:"Restore all"})]}),s.jsx(hs,{className:"bg-bg-secondary/25",children:i.map((k,w)=>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] opacity-50 saturate-0 ${w>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(k),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-bg-primary border border-border-subtle text-text-secondary",children:l(nt(k))}),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:nt(k)}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:us(k)}),s.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},k.tabKey))})]})]}),e==="chats"&&x&&N&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:x,"aria-label":$t,title:$t,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"})]})}),s.jsx(Zc,{section:e,onSectionChange:S})]})}function Th(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 el(e){const t=[e.workspace||"Workspace unknown"],r=ds(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=Th(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function an({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:d,onConfirm:f}){const[u,x]=o.useState(r);o.useEffect(()=>{x(r)},[r]);const m=mh(r),v=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:l,"aria-label":"Close folder browser",children:s.jsx(vt,{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:()=>{!m||a||d(m)},disabled:!m||a,children:[s.jsx(xa,{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:S=>x(S.target.value),onKeyDown:S=>{S.key!=="Enter"||!v||a||(S.preventDefault(),d(v))},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:()=>{!v||a||d(v)},disabled:!v||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…"}):i?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):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(S=>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(S.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(Ns,{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:S.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:S.path})]})]},S.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:l,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>f(v||r),disabled:!v&&!r||a,children:c})]})]})})}function Ga({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:d=!1,showArgsInput:f,argsValue:u,onArgsChange:x,showModelInput:m,modelValue:v,onModelChange:S,historyProviderNode:p,onConfirm:h,onCancel:j}){const b=n==null?void 0:n.find(N=>N.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:j,"aria-label":"Close launch confirmation",children:s.jsx(vt,{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&&i&&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:N=>i(N.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(N=>s.jsx("option",{value:N.key,children:N.label},N.key))}),(b==null?void 0:b.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:b.description})]}),p,r.map(N=>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:N.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:N.value})]},`${N.label}:${N.value}`)),m&&S&&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:v||"",onChange:N=>S(N.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})]}),f&&x&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:u||"",onChange:N=>x(N.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:j,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:h,disabled:d,children:[s.jsx(ya,{size:14}),d?l:c]})]})]})})}function ei(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function os(e){const{machine:t,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,i=[];a&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const d of t.workspaces||[])i.push({key:`saved:${d.id}`,label:`${d.id===t.defaultWorkspaceId?"⭐ ":""}${ei(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const c=(r==null?void 0:r.trim())||"",l=c?(t.workspaces||[]).find(d=>d.path===c):null;if(c&&!l&&i.push({key:`custom:${c}`,label:ei(c),description:c,workspaceId:null,workspacePath:c}),n){const d=`saved:${n}`;if(i.some(f=>f.key===d))return{options:i,selectedKey:d}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function Lh(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Rh(e){return[Lh(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Ph(e){return e.lastLaunchedAt?Jr(e.lastLaunchedAt):""}function tl(e){return{metaText:Rh(e),updatedLabel:Ph(e)}}function An(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function _h({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var dt,mt,ot,ut;const c=ar(),[l,d]=o.useState(!1),f=(((dt=e.detectedIdes)==null?void 0:dt.length)||0)>0,u=o.useMemo(()=>(e.workspaces||[]).map(Ie=>({id:Ie.id,path:Ie.path,label:Ie.label})),[e]),x=e.defaultWorkspaceId||null,[m,v]=o.useState(x||((mt=u[0])==null?void 0:mt.id)||""),[S,p]=o.useState(""),[h,j]=o.useState(""),[b,N]=o.useState([]),[A,y]=o.useState(!1),[I,k]=o.useState(""),[w,g]=o.useState(!1),[E,M]=o.useState(An(f,t.length,r.length)),C=o.useRef(null),[R,K]=o.useState(null),z=o.useRef("__home__"),[T,L]=o.useState("__home__"),[Y,O]=o.useState(""),[D,W]=o.useState(""),[Q,be]=o.useState(""),[pe,ue]=o.useState([]),[we,ye]=o.useState(()=>ht().textQuery),[ve,V]=o.useState(()=>ht().workspaceQuery),[H,Z]=o.useState(()=>ht().modelQuery),[me,ne]=o.useState(()=>ht().resumableOnly),[fe,se]=o.useState(()=>ht().sortMode),[xe,ie]=o.useState(!1),[ce,ae]=o.useState(!1),X=o.useRef(null),J=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const oe=m==="__custom__"?S.trim():((ot=u.find(Ie=>Ie.id===m))==null?void 0:ot.path)||"",P=m==="__custom__"&&!!oe&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),G=m!=="__custom__"&&((ut=u.find(Ie=>Ie.id===m))==null?void 0:ut.path)||"",U=o.useMemo(()=>(e.recentLaunches||[]).map(Ie=>Ie.workspace),[e]),de=o.useCallback(async Ie=>{y(!0),k("");try{const $e=await a(Ie);j($e.path),p($e.path),N($e.directories)}catch($e){k($e instanceof Error?$e.message:"Could not load folder")}finally{y(!1)}},[a]),Ne=o.useCallback(()=>{var $e;v("__custom__"),g(!0);const Ie=sn(e.platform,tn(S.trim(),G,U,e.defaultWorkspacePath,($e=u.find(Ue=>Ue.id===x))==null?void 0:$e.path,u.map(Ue=>Ue.path)));de(Ie)},[S,x,de,U,G,e.platform,u]),_e=o.useCallback(Ie=>{if(Ie!=null&&Ie.workspaceId){v(Ie.workspaceId),p("");return}if(Ie!=null&&Ie.workspacePath){v("__custom__"),p(Ie.workspacePath);return}v(""),p("")},[]),ge=o.useCallback(Ie=>{if(v(Ie),Ie==="__custom__"){Ne();return}p("")},[Ne]),Be=o.useCallback(Ie=>{v("__custom__"),p(Ie)},[]),Oe=o.useCallback((Ie,$e)=>{C.current=$e,z.current=Ie.selectedWorkspaceKey||"__home__",L(Ie.selectedWorkspaceKey||"__home__"),O(Ie.initialArgs||""),W(Ie.initialModel||""),be(""),ue([]);const Ue=Ie.providerType?`${e.id}:${Ie.providerType}`:null;if(wf(J.current,Ue)){const Ve=ht();ye(Ve.textQuery),V(Ve.workspaceQuery),Z(Ve.modelQuery),ne(Ve.resumableOnly),se(Ve.sortMode)}J.current=Ue,K(Ie),Ie.providerType&&i&&(ie(!0),i(Ie.providerType).then(Ve=>ue(Ve||[])).catch(Ve=>console.warn("Failed to load saved sessions",Ve)).finally(()=>ie(!1)))},[i,e.id]),Ke=o.useMemo(()=>wc(pe,{textQuery:we,workspaceQuery:ve,modelQuery:H,resumableOnly:me,sortMode:fe}),[H,me,pe,fe,we,ve]);o.useEffect(()=>{Q&&(Ke.some(Ie=>Ie.providerSessionId===Q)||be(""))},[Ke,Q]);const et=o.useCallback(()=>{C.current&&(ae(!0),C.current().finally(()=>{C.current=null,ae(!1),K(null)}))},[]),Je=o.useCallback(()=>{C.current=null,K(null)},[]),at=o.useCallback(Ie=>{z.current=Ie,L(Ie)},[]);return o.useEffect(()=>{var Ie;X.current!==e.id&&(X.current=e.id,v(x||((Ie=u[0])==null?void 0:Ie.id)||"__custom__"),p(""),j(""),N([]),k(""),g(!1),ye(ht().textQuery),V(ht().workspaceQuery),Z(ht().modelQuery),ne(ht().resumableOnly),se(ht().sortMode),J.current=null,M(An(f,t.length,r.length)))},[r.length,t.length,x,f,e.id,u]),o.useEffect(()=>{var Ie;m!=="__custom__"&&(m&&u.some($e=>$e.id===m)||v(x||((Ie=u[0])==null?void 0:Ie.id)||"__custom__"))},[x,m,u]),o.useEffect(()=>{E==="ide"&&f||E==="cli"&&t.length>0||E==="acp"&&r.length>0||M(An(f,t.length,r.length))},[E,r.length,t.length,f]),{showAllRecent:l,setShowAllRecent:d,hasIdeOptions:f,workspaceRows:u,defaultWorkspaceId:x,workspaceChoice:m,customWorkspacePath:S,browseCurrentPath:h,browseDirectories:b,browseBusy:A,browseError:I,browseDialogOpen:w,activeLauncherKind:E,launchConfirm:R,launchConfirmWorkspaceKeyRef:z,launchConfirmWorkspaceKey:T,launchConfirmArgs:Y,launchConfirmModel:D,launchConfirmResumeId:Q,launchConfirmSavedSessions:pe,launchConfirmTextFilter:we,launchConfirmWorkspaceFilter:ve,launchConfirmModelFilter:H,launchConfirmResumableOnly:me,launchConfirmSortMode:fe,filteredLaunchConfirmSavedSessions:Ke,launchConfirmSessionsLoading:xe,launchConfirmBusy:ce,resolvedWorkspacePath:oe,canCreateMissingWorkspace:P,openBrowseDialog:Ne,loadBrowsePath:de,handleWorkspaceChoiceChange:ge,chooseCustomWorkspacePath:Be,setCustomWorkspacePath:p,setBrowseDialogOpen:g,setActiveLauncherKind:M,openLaunchConfirm:Oe,handleConfirmLaunch:et,closeLaunchConfirm:Je,setWorkspaceSelectionFromOption:_e,setLaunchConfirmWorkspaceKeyAndSync:at,setLaunchConfirmArgs:O,setLaunchConfirmModel:W,setLaunchConfirmResumeId:be,setLaunchConfirmTextFilter:ye,setLaunchConfirmWorkspaceFilter:V,setLaunchConfirmModelFilter:Z,setLaunchConfirmResumableOnly:ne,setLaunchConfirmSortMode:se}}function Dh({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:d,section:f,showBottomNav:u,onBack:x,onSectionChange:m,onOpenConversation:v,onOpenRecent:S,onOpenMachineDetails:p,onMachineUpgrade:h,onLaunchDetectedIde:j,onAddWorkspace:b,onBrowseDirectory:N,onLaunchWorkspaceProvider:A,onListSavedSessions:y}){const I=T=>T==="ide"?"IDE":T==="cli"?"CLI":"ACP",k=r.slice(0,4),w=t.slice(0,3),g=_h({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:N,onListSavedSessions:y}),E=o.useMemo(()=>k.map(T=>{const{metaText:L,updatedLabel:Y}=tl(T);return{key:`recent-launch:${T.id}`,primary:T.label,secondary:L,updatedLabel:Y,onClick:()=>{const{options:O,selectedKey:D}=os({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspacePath:T.workspace});g.openLaunchConfirm({title:T.kind==="ide"?ss("restart-ide",T.label):T.providerSessionId?Da(T.label):ss("start-fresh",T.label),description:T.kind==="ide"?rs("restart-ide"):T.providerSessionId?Ea():rs("start-fresh"),confirmLabel:T.kind==="ide"?Is("restart-ide"):T.providerSessionId?Ur(!0):Is("start-fresh"),busyLabel:T.kind==="ide"?Ms("restart-ide"):T.providerSessionId?Pa(!0):Ms("start-fresh"),workspaceOptions:O,selectedWorkspaceKey:D,details:[{label:"Mode",value:I(T.kind)},...T.providerType?[{label:"Provider",value:T.providerType}]:[]]},async()=>{const W=O.find(Q=>Q.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(W),await S({...T,workspace:(W==null?void 0:W.workspacePath)??null})})}}}),[g,S,k]),M=o.useMemo(()=>w.map(T=>({key:`recent-chat:${T.conversation.tabKey}`,primary:nt(T.conversation),secondary:df(T.conversation,{timestampLabel:T.timestamp?Hi(T.timestamp):null}),unread:T.unread,onClick:()=>v(T.conversation)})),[v,w]),C=g.showAllRecent?E:E.slice(0,4),R=E.length>0,K=M.length>0,z=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 ${z} 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:x,type:"button","aria-label":"Back",children:s.jsx(xa,{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:At(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:[K&&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:M.map(T=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${T.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:T.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:T.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:T.secondary})]},T.key))})]}),R&&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:C.map(T=>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:T.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:T.primary}),T.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:T.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:T.secondary})]},T.key))}),E.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:()=>g.setShowAllRecent(T=>!T),children:g.showAllRecent?"Show fewer":`Show ${E.length-4} more`})})]}),(g.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:g.workspaceChoice,onChange:T=>g.handleWorkspaceChoiceChange(T.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:g.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[g.workspaceRows.map(T=>s.jsxs("option",{value:T.id,children:[T.id===g.defaultWorkspaceId?"⭐ ":"",Zr(T.path,T.label)||T.path]},T.id)),s.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):s.jsx("option",{value:"__custom__",children:"Select workspace…"})}),g.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(Ns,{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:g.resolvedWorkspacePath||g.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:g.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:()=>{g.resolvedWorkspacePath&&b(g.resolvedWorkspacePath)},disabled:!g.resolvedWorkspacePath||g.browseBusy,children:"Save as workspace"})]})]}),g.resolvedWorkspacePath&&s.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:g.resolvedWorkspacePath})]})}),s.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[g.hasIdeOptions&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${g.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:()=>g.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${g.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:()=>g.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${g.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:()=>g.setActiveLauncherKind("acp"),children:"ACP"})]}),g.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:g.activeLauncherKind==="ide"?"Choose an IDE":g.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),s.jsx("div",{className:"grid grid-cols-1 gap-2",children:g.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(T=>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:L,selectedKey:Y}=os({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspaceId:g.workspaceChoice!=="__custom__"?g.workspaceChoice:null,currentWorkspacePath:g.resolvedWorkspacePath});g.openLaunchConfirm({title:`Launch ${T.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:L,selectedWorkspaceKey:Y,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:T.name}]},async()=>{const O=L.find(D=>D.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(O),j(T.type,{workspacePath:(O==null?void 0:O.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:T.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:g.resolvedWorkspacePath||"Use selected workspace"})]},T.type)):(g.activeLauncherKind==="cli"?n:a).map(T=>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 L=g.activeLauncherKind==="cli"?"cli":"acp",{options:Y,selectedKey:O}=os({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspaceId:g.workspaceChoice!=="__custom__"?g.workspaceChoice:null,currentWorkspacePath:g.resolvedWorkspacePath});g.openLaunchConfirm({title:`Launch ${T.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${L.toUpperCase()}`,workspaceOptions:Y,selectedWorkspaceKey:O,details:[{label:"Mode",value:L.toUpperCase()},{label:"Provider",value:T.displayName}],showArgsInput:!0,showModelInput:L==="acp",initialArgs:"",initialModel:"",providerType:T.type},async()=>{const D=Y.find(W=>W.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(D),A(L,T.type,{workspaceId:(D==null?void 0:D.workspaceId)??null,workspacePath:(D==null?void 0:D.workspacePath)??null,args:g.launchConfirmArgs,model:g.launchConfirmModel,resumeSessionId:g.launchConfirmResumeId||null})})},children:[s.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[T.icon?`${T.icon} `:"",T.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:g.resolvedWorkspacePath||"Use selected workspace"})]},T.type))})]}),l.message&&s.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${l.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[l.message,g.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:()=>b(g.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:[i&&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:h,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),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"})]})]})]})]}),g.browseDialogOpen&&s.jsx(an,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:g.browseCurrentPath,directories:g.browseDirectories,busy:g.browseBusy,error:g.browseError,confirmLabel:"Use this folder",onClose:()=>g.setBrowseDialogOpen(!1),onNavigate:T=>{g.loadBrowsePath(T)},onConfirm:T=>{g.chooseCustomWorkspacePath(T),g.setBrowseDialogOpen(!1)}}),g.launchConfirm&&s.jsx(Ga,{title:g.launchConfirm.title,description:g.launchConfirm.description,details:g.launchConfirm.details,workspaceOptions:g.launchConfirm.workspaceOptions,selectedWorkspaceKey:g.launchConfirmWorkspaceKey,onWorkspaceChange:g.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:g.launchConfirm.providerType?Ur(!!g.launchConfirmResumeId):g.launchConfirm.confirmLabel,busyLabel:g.launchConfirm.providerType?void 0:g.launchConfirm.busyLabel,busy:g.launchConfirmBusy,showArgsInput:g.launchConfirm.showArgsInput,argsValue:g.launchConfirmArgs,onArgsChange:g.setLaunchConfirmArgs,showModelInput:g.launchConfirm.showModelInput,modelValue:g.launchConfirmModel,onModelChange:g.setLaunchConfirmModel,historyProviderNode:g.launchConfirm.providerType&&(g.launchConfirmSessionsLoading||g.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"}),g.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:_a()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:g.launchConfirmTextFilter,onChange:T=>g.setLaunchConfirmTextFilter(T.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:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:g.launchConfirmWorkspaceFilter,onChange:T=>g.setLaunchConfirmWorkspaceFilter(T.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:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:g.launchConfirmModelFilter,onChange:T=>g.setLaunchConfirmModelFilter(T.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:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),s.jsxs("select",{value:g.launchConfirmSortMode,onChange:T=>g.setLaunchConfirmSortMode(T.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:g.launchConfirmBusy||g.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:g.launchConfirmResumableOnly,onChange:T=>g.setLaunchConfirmResumableOnly(T.target.checked),disabled:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:g.launchConfirmResumeId,onChange:T=>g.setLaunchConfirmResumeId(T.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:g.launchConfirmBusy||g.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Sf()}),g.filteredLaunchConfirmSavedSessions.map(T=>s.jsxs("option",{value:T.providerSessionId,disabled:!T.canResume,children:[T.title||T.providerSessionId," ",T.canResume?"":"(workspace missing)"]},T.providerSessionId))]}),!g.launchConfirmSessionsLoading&&g.launchConfirmSavedSessions.length>0&&g.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),g.launchConfirmResumeId&&(()=>{const T=g.filteredLaunchConfirmSavedSessions.find(Y=>Y.providerSessionId===g.launchConfirmResumeId);if(!T)return null;const L=el(T);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:L.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:L.providerSessionId}),s.jsx("div",{className:"mt-1",children:L.metaLine}),L.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:L.updatedLabel}),L.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:L.preview})]})})()]}),onConfirm:g.handleConfirmLaunch,onCancel:g.closeLaunchConfirm}),u&&s.jsx(Zc,{section:f,onSectionChange:m})]})}function Eh(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 $h(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:ds(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 c,l,d,f,u;const a=Qs(n)?"cli":ys(n)?"acp":"ide",i=ds(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(Qs(n)?n.cliName||n.type:ys(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:ys(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((u=(f=(d=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:d.at)==null?void 0:f.call(d,-1))==null?void 0:u.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function Bh(e,t){const r=new Map;for(const n of t){const a=fs(n.conversation),i=r.get(a);i?i.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],i=[...a].sort((x,m)=>m.timestamp-x.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=Jn(n),d=a.filter(x=>x.unread||x.requiresAction).length,f=Eh(n),u=[n.platform||"machine",f].filter(Boolean);return{id:n.id,label:At(n,{fallbackId:n.id}),subtitle:u.join(" · "),unread:d,total:a.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?uf(c):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((n,a)=>{const i=n.latestTimestamp||n.fallbackActivityAt||0,c=a.latestTimestamp||a.fallbackActivityAt||0;return c!==i?c-i:n.label.localeCompare(a.label)})}function Kh(e){return e==="chat"}function kr(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 Oh({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:f,requestedMachineId:u,onRequestedMachineConsumed:x,requestedMobileSection:m,onRequestedMobileSectionConsumed:v,setSelectedTabKey:S,setScreen:p,setSelectedMachineId:h,setSection:j,setMachineBackTarget:b,resetMachineAction:N}){const A=o.useRef(null),y=o.useCallback(I=>{if(!(I!=null&&I.sessionId))return;const k=Or(I,c),w=Math.max(Date.now(),es(I),k.lastUpdated||0);kr("mark_read:start",{tabKey:I.tabKey,sessionId:I.sessionId,displayPrimary:nt(I),inboxBucket:k.inboxBucket,unread:k.unread,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,activityAt:es(I),readAt:w}),l(fs(I)||I.routeId,"mark_session_seen",{sessionId:I.sessionId,seenAt:w}).then(g=>{kr("mark_read:result",{tabKey:I.tabKey,sessionId:I.sessionId,result:g})}).catch(g=>{kr("mark_read:error",{tabKey:I.tabKey,sessionId:I.sessionId,error:g instanceof Error?g.message:String(g)})})},[c,l]);return o.useEffect(()=>{var k;if(!n){Kh(i)&&p("inbox"),S(((k=e[0])==null?void 0:k.tabKey)||null),A.current=null;return}if(i!=="chat"){A.current=null;return}const I=`${n.tabKey}:${n.sessionId||""}`;A.current!==I&&(A.current=I,y(n))},[e,y,i,n,p,S]),o.useEffect(()=>{if(!d)return;const I=e.find(k=>k.tabKey===d);I&&(S(I.tabKey),p("chat"),f==null||f())},[e,f,d,p,S]),o.useEffect(()=>{if(!u)return;const I=t.find(k=>k.id===u);I&&(h(I.id),N(),j("machines"),b("inbox"),p("machine"),x==null||x())},[t,x,u,N,b,p,j,h]),o.useEffect(()=>{m&&(j(m),p("inbox"),v==null||v())},[v,m,p,j]),o.useEffect(()=>{const I=r.filter(k=>k.inboxBucket==="task_complete"||k.unread);I.length!==0&&kr("inbox_state",{screen:i,selectedTabKey:a,items:I.map(k=>{const w=Or(k.conversation,c);return{liveState:w,tabKey:k.conversation.tabKey,sessionId:k.conversation.sessionId,displayPrimary:nt(k.conversation),serverBucket:w.inboxBucket,computedBucket:k.inboxBucket,serverUnread:w.unread,computedUnread:k.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,activityAt:es(k.conversation)}})})},[r,c,i,a]),{markConversationRead:y}}function Wh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function ti(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Hh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Fh({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[d,f]=o.useState(null),u=o.useCallback(()=>{i("idle"),l(""),f(null)},[]),x=o.useCallback(async(b,N,A)=>{var y;try{i("loading"),l(`Launching ${N}…`);const I={ideType:N,enableCdp:!0};(y=A==null?void 0:A.workspacePath)!=null&&y.trim()&&(I.workspace=A.workspacePath.trim()),await e(b,"launch_ide",I),i("done"),l(`${N} launch requested`)}catch(I){i("error"),l(I instanceof Error?I.message:"Launch IDE failed"),console.error("Launch IDE failed",I)}},[e]),m=o.useCallback(async(b,N,A)=>{if(N.trim())try{i("loading"),l(A!=null&&A.createIfMissing?"Creating folder…":"Saving workspace…");const y=await e(b,"workspace_add",{path:N.trim(),createIfMissing:(A==null?void 0:A.createIfMissing)===!0});if(y!=null&&y.success){i("done"),l(A!=null&&A.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((y==null?void 0:y.error)||"Could not save workspace")}catch(y){i("error"),l(y instanceof Error?y.message:"Could not save workspace")}},[e]),v=o.useCallback(async b=>{var N,A,y,I,k,w;try{i("loading"),l("Starting daemon upgrade…");const g=await e(b,"daemon_upgrade",{});if((N=g==null?void 0:g.result)!=null&&N.alreadyLatest){i("done"),l(`Already on v${((A=g==null?void 0:g.result)==null?void 0:A.version)||"latest"}.`);return}if((y=g==null?void 0:g.result)!=null&&y.upgraded||(I=g==null?void 0:g.result)!=null&&I.success){i("done"),l(`Upgrade to v${((k=g==null?void 0:g.result)==null?void 0:k.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((w=g==null?void 0:g.result)==null?void 0:w.error)||"Upgrade failed")}catch(g){i("error"),l(g instanceof Error?g.message:"Upgrade failed")}},[e]),S=o.useCallback(async(b,N,A,y)=>{var w,g,E;const I=Date.now(),k={machineId:b,kind:N,providerType:A,workspaceId:(y==null?void 0:y.workspaceId)||null,workspacePath:(y==null?void 0:y.workspacePath)||null,resumeSessionId:(y==null?void 0:y.resumeSessionId)||null,startedAt:I};try{i("loading"),l(`Launching ${A}…`),f(k);const M={cliType:A};(w=y==null?void 0:y.workspacePath)!=null&&w.trim()?M.dir=y.workspacePath.trim():y!=null&&y.workspaceId&&(M.workspaceId=y.workspaceId),y!=null&&y.resumeSessionId&&(M.resumeSessionId=y.resumeSessionId),(g=y==null?void 0:y.args)!=null&&g.trim()&&(M.cliArgs=y.args.trim().split(/\s+/).filter(Boolean)),(E=y==null?void 0:y.model)!=null&&E.trim()&&(M.initialModel=y.model.trim());const C=await e(b,"launch_cli",M),R=(C==null?void 0:C.result)||C,K=(R==null?void 0:R.sessionId)||(R==null?void 0:R.id);if(C!=null&&C.success&&K){f(null),i("done"),l(`${A} launched`),t(Gt(K));return}if(C!=null&&C.success){i("loading"),l(`${A} launch requested — waiting for session…`);return}f(null),i("error"),l((C==null?void 0:C.error)||(R==null?void 0:R.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(M){if(Hh(M)){i("loading"),l(`${A} launch requested — waiting for session…`);return}f(null),i("error"),l(M instanceof Error?M.message:`Could not launch ${N.toUpperCase()} workspace`)}},[t,e]),p=o.useCallback(async(b,N)=>{try{const A=await e(b,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),y=(A==null?void 0:A.result)??A;return Array.isArray(y==null?void 0:y.sessions)?y.sessions:[]}catch(A){return console.error("Failed to list saved sessions on mobile:",A),[]}},[e]),h=o.useCallback(async(b,N)=>rn(e,b,N),[e]);o.useEffect(()=>{if(!d)return;const b=ti(d.workspacePath),N=r.find(y=>{var M,C,R,K;if(!y||y.type==="adhdev-daemon"||Wh(y.daemonId||y.id)!==d.machineId||(y.transport==="acp"?"acp":y.transport==="pty"?"cli":null)!==d.kind||String(y.agentType||y.type||"")!==d.providerType)return!1;const g=String(y.providerSessionId||"");if(d.resumeSessionId&&g)return g===d.resumeSessionId;if(b){const z=ti(y.workspace||y.runtimeWorkspaceLabel);return z?z===b:!1}return Number(y.lastUpdated||y._lastUpdate||y.timestamp||((K=(R=(C=(M=y.activeChat)==null?void 0:M.messages)==null?void 0:C.at)==null?void 0:R.call(C,-1))==null?void 0:K.timestamp)||0)>=d.startedAt-5e3});if(!N)return;const A=cc({entrySessionId:N.sessionId,entryInstanceId:N.instanceId,entryRouteId:N.id,conversations:n});A&&(f(null),i("done"),l(`${d.providerType} launched`),t(Gt(A)))},[n,r,t,d]),o.useEffect(()=>{if(!d)return;const b=window.setTimeout(()=>{f(N=>!N||N.startedAt!==d.startedAt?N:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(b)},[d]);const j=o.useCallback(async(b,N)=>{if(N.kind==="ide"&&N.providerType){await x(b,N.providerType,{workspacePath:N.workspace||null});return}(N.kind==="cli"||N.kind==="acp")&&N.providerType&&await S(b,N.kind,N.providerType,{workspacePath:N.workspace||null,resumeSessionId:N.providerSessionId||null})},[x,S]);return{machineAction:{state:a,message:c},resetMachineAction:u,handleLaunchDetectedIde:x,handleAddWorkspace:m,handleMachineUpgrade:v,handleLaunchWorkspaceProvider:S,handleListSavedSessions:p,handleBrowseDirectory:h,handleOpenRecent:j}}function Uh({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:d,setMachineBackTarget:f}){const u=o.useCallback(j=>{i(j.tabKey),c("chat"),n(j)},[n,c,i]),x=o.useCallback(j=>{const b=e.find(N=>N.routeId===j.routeId&&N.streamSource==="native");b&&(i(b.tabKey),c("chat"),n(b))},[e,n,c,i]),m=o.useCallback(()=>{n(t),c("inbox")},[n,t,c]),v=o.useCallback((j,b="inbox")=>{l(j),a(),d("machines"),f(b),c("machine")},[a,f,c,d,l]),S=o.useCallback(j=>{const b=fs(j);b&&v(b,"chat")},[v]),p=o.useCallback(()=>{a(),c(r)},[r,a,c]),h=o.useCallback(j=>{d(j),c("inbox")},[c,d]);return{openConversation:u,openNativeConversation:x,backFromConversation:m,openMachine:v,openConversationMachine:S,backFromMachine:p,changeMachineSection:h}}function zh(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function Sr(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Vh({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,userName:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:f,requestedMachineId:u,onRequestedMachineConsumed:x,requestedMobileSection:m,onRequestedMobileSectionConsumed:v,onOpenHistory:S,onOpenRemote:p,onStopCli:h,wsStatus:j,isConnected:b,onShowHiddenConversation:N,onShowAllHiddenConversations:A,onHideConversation:y,onOpenNewSession:I,liveSessionInboxState:k,setCliViewModeOverrides:w}){const[g,E]=o.useState(()=>{var G;return((G=e[0])==null?void 0:G.tabKey)||null}),[M,C]=o.useState(()=>e[0]?"chat":"inbox"),[R,K]=o.useState("chats"),[z,T]=o.useState(null),[L,Y]=o.useState("inbox"),O=As(),D="0.9.27",W=o.useMemo(()=>e.find(G=>G.tabKey===g)||e[0]||null,[e,g]),Q=o.useMemo(()=>W?r.find(G=>G.id===W.routeId):void 0,[r,W]),be=o.useMemo(()=>!W||Xe(W)||!Ze(W)?null:Ls(W),[W]),pe=o.useMemo(()=>r.filter(G=>G.type==="adhdev-daemon").sort(wa),[r]),ue=o.useMemo(()=>pe.find(G=>G.id===z)||null,[pe,z]),we=nn({sendDaemonCommand:a,activeConv:W||void 0,setActionLogs:i,isStandalone:c}),ye=Fh({sendDaemonCommand:a,navigate:O,ides:r,conversations:e}),ve=o.useMemo(()=>e.map(G=>{const U=M==="chat"&&(W==null?void 0:W.tabKey)===G.tabKey,de=Qr(G,k,{hideOpenTaskCompleteUnread:!0,isOpenConversation:U}),Ne=es(G),_e=xc(G);return{conversation:G,timestamp:Ne,preview:_e,unread:de.unread,requiresAction:de.requiresAction,isWorking:de.isWorking,inboxBucket:de.inboxBucket}}),[e,k,M,W]),{markConversationRead:V}=Oh({conversations:e,machineEntries:pe,items:ve,selectedConversation:W,selectedTabKey:g,screen:M,liveSessionInboxState:k,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:f,requestedMachineId:u,onRequestedMachineConsumed:x,requestedMobileSection:m,onRequestedMobileSectionConsumed:v,setSelectedTabKey:E,setScreen:C,setSelectedMachineId:T,setSection:K,setMachineBackTarget:Y,resetMachineAction:ye.resetMachineAction}),H=Uh({conversations:e,selectedConversation:W,machineBackTarget:L,markConversationRead:V,resetMachineAction:ye.resetMachineAction,setSelectedTabKey:E,setScreen:C,setSelectedMachineId:T,setSection:K,setMachineBackTarget:Y}),Z=o.useMemo(()=>Sr(ve.filter(G=>G.requiresAction)),[ve]),me=o.useMemo(()=>Sr(ve.filter(G=>G.unread&&!G.requiresAction)),[ve]),ne=o.useMemo(()=>Sr(ve.filter(G=>!G.unread&&!G.requiresAction&&G.isWorking)),[ve]),fe=o.useMemo(()=>Sr(ve.filter(G=>!G.unread&&!G.requiresAction&&!G.isWorking)),[ve]),se=o.useMemo(()=>ue?ve.filter(G=>fs(G.conversation)===ue.id):[],[ve,ue]),xe=o.useMemo(()=>$h(ue,r),[r,ue]),ie=(ue==null?void 0:ue.version)||null,ce=!!ue&&!!ie&&!0&&ie!==D,ae=o.useMemo(()=>(ue==null?void 0:ue.availableProviders)||[],[ue]),X=o.useMemo(()=>ae.filter(G=>G.category==="cli"&&G.installed!==!1).map(G=>({type:G.type,displayName:G.displayName||G.type,icon:G.icon})),[ae]),J=o.useMemo(()=>ae.filter(G=>G.category==="acp"&&G.installed!==!1).map(G=>({type:G.type,displayName:G.displayName||G.type,icon:G.icon})),[ae]),oe=o.useMemo(()=>Bh(pe,ve),[ve,pe]),P=o.useCallback(async G=>{ue&&await ye.handleOpenRecent(ue.id,G)},[ye,ue]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:M==="chat"&&W?s.jsx(Ih,{selectedConversation:W,isAcp:Xe(W),isStandalone:c,selectedIdeEntry:Q,actionLogs:n,userName:l,isSendingChat:we.isSendingChat,sendFeedbackMessage:we.sendFeedbackMessage,isFocusingAgent:we.isFocusingAgent,handleModalButton:we.handleModalButton,handleRelaunch:we.handleRelaunch,onBack:H.backFromConversation,onOpenNativeConversation:H.openNativeConversation,onOpenMachine:H.openConversationMachine,onHideConversation:y,onOpenHistory:S,onOpenRemote:p,onStopCli:h,cliViewMode:be,onSetCliViewMode:async G=>{await Uc({conversation:W,mode:G,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:w})},handleSendChat:we.handleSendChat,handleFocusAgent:we.handleFocusAgent}):M==="machine"&&ue?s.jsx(Dh,{selectedMachineEntry:ue,selectedMachineConversations:se,selectedMachineRecentLaunches:xe,cliProviders:X,acpProviders:J,selectedMachineNeedsUpgrade:ce,appVersion:D,machineAction:ye.machineAction,isStandalone:c,section:R,showBottomNav:L==="inbox",onBack:H.backFromMachine,onSectionChange:H.changeMachineSection,onOpenConversation:H.openConversation,onOpenRecent:P,onOpenMachineDetails:()=>O(`/machines/${ue.id}`),onMachineUpgrade:()=>ye.handleMachineUpgrade(ue.id),onLaunchDetectedIde:(G,U)=>ye.handleLaunchDetectedIde(ue.id,G,U),onAddWorkspace:(G,U)=>ye.handleAddWorkspace(ue.id,G,U),onBrowseDirectory:G=>ye.handleBrowseDirectory(ue.id,G),onLaunchWorkspaceProvider:(G,U,de)=>ye.handleLaunchWorkspaceProvider(ue.id,G,U,de),onListSavedSessions:G=>ye.handleListSavedSessions(ue.id,G)}):s.jsx(Ah,{section:R,attentionItems:Z,unreadItems:me,workingItems:ne,completedItems:fe,hiddenConversations:t,machineCards:oe,getAvatarText:zh,onOpenConversation:H.openConversation,onShowConversation:N,onShowAllHidden:A,onOpenNewSession:I,onOpenMachine:H.openMachine,onOpenSettings:()=>O("/settings"),onSectionChange:K,wsStatus:j,isConnected:b,isStandalone:c})})}function Tn(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function Gh({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,d]=o.useState(!1),[f,u]=o.useState(null),x=o.useCallback(()=>{c.current=0,d(!1),u(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",x),window.addEventListener("drop",x),()=>{window.removeEventListener("dragend",x),window.removeEventListener("drop",x)}),[x]);const m=o.useCallback(h=>{h.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,d(!0))},[]),v=o.useCallback(h=>{if(!h.dataTransfer.types.includes("text/tab-key"))return;if(h.preventDefault(),!Tn(t,r)){u("merge");return}const j=h.currentTarget.getBoundingClientRect(),b=h.clientX-j.left,N=j.width/3;b<N?u("split-left"):b>N*2?u("split-right"):u("merge")},[t,r]),S=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,d(!1),u(null))},[]),p=o.useCallback(h=>{c.current=0,d(!1);const j=h.dataTransfer.getData("text/tab-key"),b=j?e.some(A=>A.tabKey===j):!1,N=f;if(u(null),i(),!!j){if(h.preventDefault(),N==="split-left"&&Tn(t,r)){r==null||r(j,"split-left");return}if(N==="split-right"&&Tn(t,r)){r==null||r(j,"split-right");return}if(b){a(j);return}n==null||n(j)}},[e,f,t,r,n,a,i]);return{dragOver:l,dropAction:f,resetDragState:x,handleDragEnter:m,handleDragOver:v,handleDragLeave:S,handleDrop:p}}function qh(e,t){const r=new Set(t.map(i=>i.tabKey)),n=e.filter(i=>r.has(i)),a=t.filter(i=>!e.includes(i.tabKey)).map(i=>i.tabKey);return[...n,...a]}function Yh({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(t??null),[l,d]=o.useState(r??[]),[f,u]=o.useState(null),x=o.useRef(null),m=o.useRef(null),v=o.useRef(n),S=o.useRef(a);o.useEffect(()=>{v.current=n},[n]),o.useEffect(()=>{S.current=a},[a]),o.useEffect(()=>{t&&t!==i&&c(t)},[t,i]),o.useEffect(()=>{d(k=>{const w=qh(k,e);return w.length===k.length&&w.every((g,E)=>g===k[E])?k:w})},[e]);const p=o.useMemo(()=>{const k=f??l;if(k.length===0)return e;const w=new Map(k.map((g,E)=>[g,E]));return[...e].sort((g,E)=>{const M=w.get(g.tabKey)??999,C=w.get(E.tabKey)??999;return M-C})},[e,f,l]);o.useEffect(()=>{var w,g;if(p.length===0){i!==null&&(c(null),(w=v.current)==null||w.call(v,null));return}if(i&&p.some(E=>E.tabKey===i))return;const k=p[0].tabKey;k!==i&&(c(k),(g=v.current)==null||g.call(v,k))},[p,i]);const h=o.useMemo(()=>p.find(k=>k.tabKey===i),[p,i]),j=o.useCallback(k=>{var w;c(k),(w=v.current)==null||w.call(v,k)},[]),b=o.useCallback((k,w,g)=>{d(E=>{var K;const M=E.filter(z=>z!==k),C=M.indexOf(w);if(C<0)return E;const R=g==="left"?C:C+1;return M.splice(R,0,k),(K=S.current)==null||K.call(S,M),M}),u(null)},[]),N=o.useCallback((k,w,g)=>{const M=(l.length>0?l:e.map(K=>K.tabKey)).filter(K=>K!==k),C=M.indexOf(w);if(C<0)return;const R=g==="left"?C:C+1;M.splice(R,0,k),x.current=M,u(M)},[l,e]),A=o.useCallback(()=>{var w;const k=x.current;k&&(d(k),(w=S.current)==null||w.call(S,k))},[]),y=o.useCallback(()=>{x.current=null,u(null)},[]),I=o.useCallback(k=>{d(w=>{var E;const g=w.filter(M=>M!==k);return g.push(k),(E=S.current)==null||E.call(S,g),g})},[]);return{activeTabId:i,activeConv:h,sortedConversations:p,previewOrderRef:x,draggingTabRef:m,selectTab:j,handleTabReorder:b,updatePreviewOrder:N,commitPreviewOrder:A,clearPreviewOrder:y,moveTabToEnd:I,setDraggingTabKey:k=>{m.current=k}}}function Xh({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 qa({conversationsCount:e,isSplitMode:t,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession:i}){if(a)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const c=!r&&!n,l=n&&!!i,d=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",f=n?vc: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:f}),l&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:i,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:$t,"aria-label":$t,children:[s.jsx(Ei,{size:14}),s.jsx("span",{children:$t})]})}),c&&s.jsx(Qc,{}),c&&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 sl="adhdev-tab-shortcuts";function rl(){try{return JSON.parse(localStorage.getItem(sl)||"{}")}catch{return{}}}function nl({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>rl()),[l,d]=o.useState(null),f=o.useCallback(x=>{const m=[];return x.metaKey&&m.push(a?"⌘":"Meta"),x.ctrlKey&&m.push("Ctrl"),x.altKey&&m.push(a?"⌥":"Alt"),x.shiftKey&&m.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(x.key)?null:(m.push(x.key.length===1?x.key.toUpperCase():x.key),m.join("+"))},[a]),u=o.useCallback(x=>{c(x);try{localStorage.setItem(sl,JSON.stringify(x))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const x=m=>{if(m.preventDefault(),m.stopPropagation(),m.key==="Escape"){d(null);return}const v=f(m);if(!v)return;const S={...i};for(const[p,h]of Object.entries(S))h===v&&delete S[p];S[l]=v,u(S),d(null)};return window.addEventListener("keydown",x,!0),()=>window.removeEventListener("keydown",x,!0)},[e,l,i,u,f]),o.useEffect(()=>{if(!e)return;const x=m=>{if(!(!m.ctrlKey&&!m.metaKey&&!m.altKey)){for(const[v,S]of Object.entries(i))if(t.includes(v)&&f(m)===S){m.preventDefault(),r(),n(v);return}}};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[e,i,t,r,n,f]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:d,saveShortcuts:u}}const Jh=o.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:d,onSelectTab:f,onConversationActivated:u,onPreviewReorder:x,onReorderTab:m,onCommitPreviewOrder:v,onClearPreviewOrder:S,onDragStateReset:p,onDragTabKeyChange:h,onReceiveTab:j,onOpenContextMenu:b,longPressTimer:N,isGroupActive:A}){const y=Ts(t),I=y.isGenerating?"agent-tab-generating":y.isWaiting?"agent-tab-waiting":"",k=y.isReconnecting,w=o.useCallback(L=>{l.current=t.tabKey,h(t.tabKey),L.dataTransfer.setData("text/tab-key",t.tabKey),L.dataTransfer.effectAllowed="move"},[t.tabKey,l,h]),g=o.useCallback(()=>{l.current=null,h(null),v(),S(),p()},[l,h,v,S,p]),E=o.useCallback(L=>{const Y=l.current;if(!(!Y||Y===t.tabKey)&&L.dataTransfer.types.includes("text/tab-key")){L.preventDefault(),L.stopPropagation();const O=L.currentTarget.getBoundingClientRect(),D=L.clientX<O.left+O.width/2?"left":"right";x(Y,t.tabKey,D)}},[t.tabKey,l,x]),M=o.useCallback(L=>{L.preventDefault(),L.stopPropagation();const Y=L.dataTransfer.getData("text/tab-key");if(Y&&Y!==t.tabKey){const O=L.currentTarget.getBoundingClientRect(),D=L.clientX<O.left+O.width/2?"left":"right";c.includes(Y)?m(Y,t.tabKey,D):j&&j(Y)}S()},[t.tabKey,c,m,j,S]),C=o.useCallback(L=>{L.stopPropagation(),d(),f(t.tabKey),u(t)},[t,u,d,f]),R=o.useCallback(L=>{L.preventDefault(),b(L.clientX,L.clientY,t.tabKey)},[t.tabKey,b]),K=o.useCallback(L=>{const Y=L.touches[0];N.current=setTimeout(()=>{b(Y.clientX,Y.clientY,t.tabKey)},600)},[t.tabKey,N,b]),z=o.useCallback(()=>{N.current&&clearTimeout(N.current)},[N]),T=["adhdev-dockview-tab",I,r&&"is-active",A&&"is-group-active",k&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:T,draggable:!0,onDragStart:w,onDragEnd:g,onDragOver:E,onDrop:M,onClick:C,onContextMenu:R,onTouchStart:K,onTouchEnd:z,onTouchMove:z,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:y.isGenerating?s.jsx("div",{className:"tab-spinner"}):y.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):k?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):y.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:nt(t),children:nt(t)}),s.jsx("span",{className:"adhdev-dockview-tab-meta",children:k?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ts(t)}):y.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[ts(t),s.jsx("span",{className:"connecting-dots"})]}):ts(t)})]}),i&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${i}`,children:i})]})},(e,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 Qh({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:f,onCommitPreviewOrder:u,onClearPreviewOrder:x,onDragStateReset:m,onDragTabKeyChange:v,onReceiveTab:S,onHideTab:p,isGroupActive:h,allowTabShortcuts:j=!0}){const[b,N]=o.useState(null),A=o.useRef(null),y=o.useRef(null),I=o.useMemo(()=>e.map(R=>R.tabKey),[e]);rr("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(b==null?void 0:b.tabKey)||null});const{isMac:k,tabShortcuts:w,shortcutListening:g,setShortcutListening:E,saveShortcuts:M}=nl({enabled:j,sortedTabKeys:e.map(R=>R.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!b)return;const R=K=>{const z=document.querySelector("[data-pane-context-menu]");z&&z.contains(K.target)||N(null)};return window.addEventListener("mousedown",R,!0),()=>window.removeEventListener("mousedown",R,!0)},[b]),o.useEffect(()=>{const R=y.current;if(!R)return;const K=z=>{Math.abs(z.deltaY)<=Math.abs(z.deltaX)||(z.preventDefault(),R.scrollLeft+=z.deltaY)};return R.addEventListener("wheel",K,{passive:!1}),()=>R.removeEventListener("wheel",K)},[]);const C=o.useCallback((R,K,z)=>{N({x:R,y:K,tabKey:z})},[]);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:y,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(R=>s.jsx(Jh,{conv:R,isActive:t===R.tabKey,isDraggedTab:a.current===R.tabKey,isTaskCompleteUnread:n.has(R.tabKey),shortcut:j?w[R.tabKey]:void 0,conversationKeys:I,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:f,onCommitPreviewOrder:u,onClearPreviewOrder:x,onDragStateReset:m,onDragTabKeyChange:v,onReceiveTab:S,onOpenContextMenu:C,longPressTimer:A,isGroupActive:h},R.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),b&&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:b.x,top:b.y},children:[j&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:R=>{R.stopPropagation(),E(b.tabKey),N(null)},children:["⌨ ",w[b.tabKey]?`Change shortcut (${w[b.tabKey]})`:"Set shortcut"]}),w[b.tabKey]&&s.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onClick:()=>{const R={...w};delete R[b.tabKey],M(R),N(null)},children:"✕ Remove shortcut"})]}),p&&s.jsxs(s.Fragment,{children:[j&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onClick:()=>{p(b.tabKey),N(null)},children:"🚫 Hide from Dashboard"})]})]}),j&&g&&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:()=>E(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:R=>R.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. ",k?"⌘+1":"Ctrl+1",", ",k?"⌥+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 Zh({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,userName:d,groupIndex:f,onFocus:u,isSplitMode:x,numGroups:m,onMoveTab:v,onReceiveTab:S,style:p,onActiveTabChange:h,initialActiveTabId:j,initialTabOrder:b,onTabOrderChange:N,onHideTab:A,isFocused:y,allowTabShortcuts:I=!0,onOpenNewSession:k,liveSessionInboxState:w}){const{sendCommand:g}=wt(),E=o.useRef(null),{activeTabId:M,activeConv:C,sortedConversations:R,draggingTabRef:K,selectTab:z,handleTabReorder:T,updatePreviewOrder:L,commitPreviewOrder:Y,clearPreviewOrder:O,moveTabToEnd:D,setDraggingTabKey:W}=Yh({conversations:e,initialActiveTabId:j,initialTabOrder:b,onActiveTabChange:h,onTabOrderChange:N}),Q=nn({sendDaemonCommand:a,activeConv:C,setActionLogs:i,isStandalone:c}),{dragOver:be,dropAction:pe,resetDragState:ue,handleDragEnter:we,handleDragOver:ye,handleDragLeave:ve,handleDrop:V}=Gh({conversations:e,numGroups:m,onMoveTab:v,onReceiveTab:S,onOwnTabDrop:D,onClearPreviewOrder:O}),H=C&&!Xe(C)&&Ls(C)==="terminal",Z=o.useMemo(()=>C?t.find(se=>se.id===C.routeId):void 0,[t,C]),me=o.useMemo(()=>C?n.filter(se=>se.routeId===C.tabKey):[],[n,C]),ne=o.useMemo(()=>new Set(R.filter(se=>ju(se,w,{isOpenConversation:se.tabKey===M})).map(se=>se.tabKey)),[M,w,R]);rr("PaneGroup",{groupIndex:f,conversationCount:e.length,activeTabId:M,dragOver:be});const fe=o.useCallback(se=>{se.streamSource==="agent-stream"&&se.agentType&&g(se.routeId,Jc(),{agentType:se.agentType,...se.sessionId&&{targetSessionId:se.sessionId}}).catch(()=>{})},[g]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...p,outline:be?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(Qh,{conversations:R,activeTabId:M,groupIndex:f,numGroups:m,unreadTabKeys:ne,draggingTabRef:K,onFocus:u,onSelectTab:z,onConversationActivated:fe,onPreviewReorder:L,onReorderTab:T,onCommitPreviewOrder:Y,onClearPreviewOrder:O,onDragStateReset:ue,onDragTabKeyChange:W,onMoveTab:v,onReceiveTab:S,onHideTab:A,isGroupActive:y??!1,allowTabShortcuts:I}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:we,onDragOver:ye,onDragLeave:ve,onDrop:V,children:[be&&s.jsx(Xh,{dropAction:pe,canSplit:!!(m<4&&v)}),C?s.jsx(Va,{activeConv:C,clearToken:r[C.tabKey]||0,isCliTerminal:!!H,ideEntry:Z,terminalRef:E,handleModalButton:Q.handleModalButton,handleRelaunch:Q.handleRelaunch,handleSendChat:Q.handleSendChat,isSendingChat:Q.isSendingChat,sendFeedbackMessage:Q.sendFeedbackMessage,handleFocusAgent:Q.handleFocusAgent,isFocusingAgent:Q.isFocusingAgent,actionLogs:me,userName:d,isInputActive:!x||!!y}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(qa,{conversationsCount:e.length,isSplitMode:x,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:k})})]})]})}function ex({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:f,isStandalone:u,hasRegisteredMachines:x,userName:m,focusedGroup:v,focusGroup:S,moveTabToGroup:p,splitTabRelative:h,closeGroup:j,handleResizeStart:b,groupActiveTabIds:N,setGroupActiveTab:A,groupTabOrders:y,setGroupTabOrder:I,toggleHiddenTab:k,onOpenNewSession:w,allowTabShortcuts:g=!0,liveSessionInboxState:E}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((M,C)=>{const R=t&&n.length===r?`${n[C]}%`:void 0;return s.jsxs(kt.Fragment,{children:[t&&C>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:K=>b(C-1,K),onDoubleClick:()=>j(C),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(Zh,{style:t?{flexBasis:R??`${100/r}%`,flexGrow:R?0:1,flexShrink:R?0:1}:void 0,conversations:M,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:f,isStandalone:u,hasRegisteredMachines:x,userName:m,groupIndex:C,isFocused:t&&v===C,onFocus:()=>S(C),isSplitMode:t,numGroups:r,onMoveTab:(K,z)=>{z==="left"&&C>0?p(K,C-1):z==="right"&&C<r-1?p(K,C+1):z==="split-left"&&r<4?h(K,C,"left"):z==="split-right"&&r<4&&h(K,C,"right")},onReceiveTab:K=>p(K,C),onActiveTabChange:K=>A(C,K),initialActiveTabId:N[C],initialTabOrder:y[C],onTabOrderChange:K=>I(C,K),onHideTab:k,onOpenNewSession:w,allowTabShortcuts:g,liveSessionInboxState:E})]},C)})})}function al({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?it.onScreenshot("ide-page",(u,x)=>{if(u!==e)return;const m=new FileReader;m.onload=()=>i(m.result),m.readAsDataURL(x)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var u;return e?((u=it.onStatus)==null?void 0:u.call(it,(x,m)=>{x===e&&m!=null&&m.screenshotUsage&&l(m.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,t]),o.useEffect(()=>{const f=e?it.get(e):null;if(!(!f||r!=="connected"))return n!=="chat"&&t?f.startScreenshots(t):f.stopScreenshots(t),()=>{f.stopScreenshots(t)}},[n,r,t,e]);const d=o.useCallback(async(f,u)=>{const x=e?it.get(e):null;return!x||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):x.sendInput(f,u,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:d}}const ol="adhdev-dashboard-action-shortcuts",tx=1200,sx={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function rx(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function tt(e,t){switch(e){case"openShortcutHelp":return"?";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+Alt+\\";case"splitActiveTabDown":return t?"⌘+⌥+-":"Ctrl+Alt+-";case"focusLeftPane":return t?"⌘+⌥+[":"Ctrl+Alt+←";case"focusRightPane":return t?"⌘+⌥+]":"Ctrl+Alt+→";case"focusUpPane":return t?"⌘+⌥+U":"Ctrl+Alt+↑";case"focusDownPane":return t?"⌘+⌥+J":"Ctrl+Alt+↓";case"moveActiveTabToLeftPane":return t?"⌘+⌥+,":"Ctrl+Alt+Shift+←";case"moveActiveTabToRightPane":return t?"⌘+⌥+.":"Ctrl+Alt+Shift+→";case"moveActiveTabToUpPane":return t?"⌘+⌥+I":"Ctrl+Alt+Shift+↑";case"moveActiveTabToDownPane":return t?"⌘+⌥+K":"Ctrl+Alt+Shift+↓";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+Alt+[";case"selectNextGroupTab":return t?"⌥+]":"Ctrl+Alt+]";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function il(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:tt("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:tt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:tt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:tt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:tt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:tt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:tt("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:tt("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:tt("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:tt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:tt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:tt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:tt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:tt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:tt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:tt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:tt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:tt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:tt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:tt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:tt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:tt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:tt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:tt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:tt("toggleCliView",e)}]}function la(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Gr(e){const t=Object.fromEntries(il(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(ol)||"{}"),n={...t,...r};for(const[a,i]of Object.entries(sx))n[a]===i&&(n[a]=t[a]);return n}catch{return t}}function cl(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function nx({enabled:e=!0,onTrigger:t}){const r=rx(),[n,a]=o.useState(()=>Gr(r)),[i,c]=o.useState(null),[l,d]=o.useState([]),f=o.useRef({parts:[],timer:null}),u=o.useCallback(p=>{const h=[];return p.metaKey&&h.push(r?"⌘":"Meta"),p.ctrlKey&&h.push("Ctrl"),p.altKey&&h.push(r?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&h.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(h.push(cl(p.key)),h.join("+"))},[r]),x=o.useCallback(p=>{a(p);try{localStorage.setItem(ol,JSON.stringify(p))}catch{}},[]);o.useEffect(()=>{const p=Gr(r),h=Object.entries(n),j=Object.entries(p);h.length===j.length&&h.every(([b,N])=>p[b]===N)||x(p)},[n,r,x]);const m=o.useCallback(()=>{typeof window<"u"&&f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current={parts:[],timer:null}},[]),v=o.useCallback(()=>{typeof window>"u"||(f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current.timer=window.setTimeout(()=>{f.current={parts:[],timer:null}},tx))},[]);o.useEffect(()=>{if(!i)return;const p=h=>{if(h.preventDefault(),h.stopPropagation(),h.key==="Escape"){c(null),d([]);return}const j=u(h);if(!j)return;const N=!(h.metaKey||h.ctrlKey||h.altKey)&&/^[A-Z0-9]$/.test(j);if(l.length===0&&N){d([j]);return}const y=[...l,j].slice(0,2).join(" "),I={...n};for(const[k,w]of Object.entries(I))w===y&&delete I[k];I[i]=y,x(I),c(null),d([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,u,x,i,l]),o.useEffect(()=>{if(!e||i)return;const p=h=>{if(h.defaultPrevented)return;const j=u(h);if(!j)return;const b=h.metaKey||h.ctrlKey||h.altKey;if(la(h.target)&&!b)return;const N=f.current.parts,A=b?[j]:[...N.slice(-1),j].slice(-2),y=A.join(" "),I=A[A.length-1],k=Object.entries(n).filter(([,C])=>!!C),w=k.find(([,C])=>C===y);if(w){h.preventDefault(),m(),t(w[0]);return}if(k.some(([,C])=>C.startsWith(`${y} `))){h.preventDefault(),f.current.parts=A,v();return}const E=k.find(([,C])=>C===I);if(E){h.preventDefault(),m(),t(E[0]);return}if(k.some(([,C])=>C.startsWith(`${I} `))){h.preventDefault(),f.current.parts=[I],v();return}m()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,v,e,u,t,m,i]),o.useEffect(()=>()=>m(),[m]);const S=o.useMemo(()=>il(r),[r]);return{isMac:r,actionDefinitions:S,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:d,saveShortcuts:x}}function ax({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 ll(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function si({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!ll(n):!0}function ox({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:ll(r)}const dl=o.createContext(null);function on(){const e=o.useContext(dl);if(!e)throw new Error("DashboardDockviewContext missing");return e}function _r(e){return nt(e)||e.tabKey}function ix(e){return`remote:${e}`}function Lt(e){return e.startsWith("remote:")}function ri(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Ln(e){var r,n,a,i,c;const t=e==null?void 0:e.defaultView;if(t)try{t.focus(),(n=(r=e==null?void 0:e.body)==null?void 0:r.focus)==null||n.call(r),(i=(a=e==null?void 0:e.documentElement)==null?void 0:a.focus)==null||i.call(a),(c=t.requestAnimationFrame)==null||c.call(t,()=>{var l,d;try{t.focus(),(d=(l=e==null?void 0:e.body)==null?void 0:l.focus)==null||d.call(l)}catch{}})}catch{}}function Nr(e,t){e.classList.remove(Un.className,zn.className),e.classList.add(t==="light"?Un.className:zn.className)}function ni(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 cx(e){const[,t]=o.useState(0);o.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 lx(e,t,r){var c;const n=[t];let a;for(const l of n){let d;for(const f of l){const u=e.addPanel({id:f.tabKey,component:"conversation",title:_r(f),params:{kind:"conversation",tabKey:f.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??((c=t[0])==null?void 0:c.tabKey)??null}function ai(e,t){const r=new Set(t.map(n=>n.tabKey));for(const n of[...e.panels])Lt(n.id)||r.has(n.id)||e.removePanel(n);for(const n of t){const a=e.getPanel(n.tabKey);if(a){a.update({params:{tabKey:n.tabKey}}),a.title!==_r(n)&&a.api.setTitle(_r(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:_r(n),params:{kind:"conversation",tabKey:n.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function oi(e,t,r){var d,f;const n=r?ix(r):null;for(const u of[...e.panels])Lt(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=_t(t,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=yc(a);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((f=e.panels.find(u=>!Lt(u.id)))==null?void 0:f.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function dx({params:e,api:t}){var x;const r=on(),n=o.useRef(null),[a,i]=o.useState(t.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=nn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(t.isActive);const m=[t.onDidActiveChange(v=>i(v.isActive)),t.onDidActiveGroupChange(v=>{if(!t.isActive&&!v.isActive){i(!1);return}i(t.isActive)})];return()=>{for(const v of m)v.dispose()}},[t]);const d=o.useMemo(()=>c?r.ides.find(m=>m.id===c.routeId):void 0,[r.ides,c]),f=o.useMemo(()=>c?r.actionLogs.filter(m=>m.routeId===c.tabKey):[],[r.actionLogs,c]);if(!c)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(qa,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const u=!Xe(c)&&Ls(c)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(Va,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:u,ideEntry:d,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:f,userName:r.userName,scrollToBottomRequestNonce:((x=r.scrollToBottomRequest)==null?void 0:x.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:a})})}function ux({params:e}){var d;const t=on(),r=o.useMemo(()=>_t([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=o.useMemo(()=>t.ides.find(f=>f.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:i,screenshotUsage:c,handleRemoteAction:l}=al({doId:a,targetSessionId:r?nc(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(Wi,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:c,transportType:r.transport,onAction:l})}):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 mx(){const e=on();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(qa,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function fx(e){var v,S;cx(e);const t=on(),r=o.useCallback(p=>{"button"in p&&p.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const p=_t([...t.conversationsByTabKey.values()],e.params.routeId),h=((v=e.api.group.activePanel)==null?void 0:v.id)===e.api.id,j=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${h?" is-active":""}${j?" 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=((S=e.api.group.activePanel)==null?void 0:S.id)===e.api.id,i=e.api.isGroupActive,c=Qr(n,t.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,d=c.isConnecting,f=c.isGenerating,u=c.isWaiting,x=c.unread,m=t.tabShortcuts[n.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:nt(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:p=>{var h;p.preventDefault(),r(p),t.openTabContextMenu({x:p.clientX,y:p.clientY,tabKey:n.tabKey,sourceDocument:((h=p.target)==null?void 0:h.ownerDocument)??document})},children:[x&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:f?s.jsx("div",{className:"tab-spinner"}):u?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?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:nt(n)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ts(n)}):d?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ts(n)}):s.jsx("span",{children:ts(n)})})]}),m&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:m,children:m})]})}function px({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:d,userName:f,toggleHiddenTab:u,actionShortcuts:x,registerActionHandlers:m,onActiveTabChange:v,onOpenNewSession:S,onRequestScrollToBottom:p,requestedActiveTabKey:h,requestedRemoteIdeId:j,onRequestedActiveTabConsumed:b,scrollToBottomRequest:N,liveSessionInboxState:A,layoutProfile:y}){var ft,Tt,yt;const{theme:I}=Ka(),{sendCommand:k}=wt(),w=o.useRef(null),g=o.useRef(null),E=o.useRef(!1),M=o.useRef(!1),C=o.useRef(!1),R=o.useRef(null),K=o.useRef([]),[z,T]=o.useState(null),[L,Y]=o.useState(!1),[O,D]=o.useState(!1),[W,Q]=o.useState(0),be=o.useRef(null),pe=o.useRef(typeof window>"u"?{}:Up(y)),ue=o.useMemo(()=>new Map(e.map(B=>[B.tabKey,B])),[e]),we=o.useMemo(()=>{const B=w.current;return B?B.groups.some($=>{try{const F=$.model.location.type;return F!=="floating"&&F!=="popout"?!1:$.panels.some(q=>ue.has(q.id))}catch{return!1}}):!1},[ue,W,e]),ye=o.useCallback(()=>{var B;(B=w.current)==null||B.focus()},[]),ve=o.useCallback((B,$)=>{p==null||p(B,$)},[p]),V=o.useCallback(B=>{const $=document,F=B.document;for(const Ce of $.querySelectorAll('link[rel="stylesheet"]')){const re=F.createElement("link");re.rel="stylesheet",re.href=Ce.href,Ce.crossOrigin&&(re.crossOrigin=Ce.crossOrigin),F.head.appendChild(re)}for(const Ce of $.querySelectorAll("style")){const re=F.createElement("style");re.textContent=Ce.textContent,F.head.appendChild(re)}const q=[];for(const Ce of $.styleSheets)try{for(const re of Ce.cssRules)re instanceof CSSStyleRule&&(re.selectorText===":root"||re.selectorText==="html")&&q.push(re.cssText)}catch{}if(q.length>0){const Ce=F.createElement("style");Ce.textContent=q.join(`
43
43
  `),F.head.appendChild(Ce)}const le=$.documentElement.getAttribute("data-theme");le&&F.documentElement.setAttribute("data-theme",le),F.documentElement.style.colorScheme=le==="light"?"light":"dark",F.body.className=$.body.className;const ke=$.documentElement.getAttribute("style");ke&&F.documentElement.setAttribute("style",ke);const Me=F.getElementById("dv-popout-window");Me instanceof HTMLElement&&(Me.classList.add("adhdev-dockview"),Nr(Me,I))},[I]),H=o.useCallback(()=>{var $;const B=w.current;if(B)for(const F of B.groups)try{const q=($=F.element)==null?void 0:$.ownerDocument;if(!q||q===document)continue;const le=q.getElementById("dv-popout-window");le instanceof HTMLElement&&(le.classList.add("adhdev-dockview"),Nr(le,I));const ke=document.documentElement.getAttribute("data-theme");ke&&q.documentElement.setAttribute("data-theme",ke),q.documentElement.style.colorScheme=ke==="light"?"light":"dark",q.body.className=document.body.className;const Me=document.documentElement.getAttribute("style");Me?q.documentElement.setAttribute("style",Me):q.documentElement.removeAttribute("style")}catch{}},[I]),Z=o.useCallback(()=>{var $;const B=w.current;if(B)for(const F of B.groups)try{const q=($=F.element)==null?void 0:$.ownerDocument;if(!q||q===document)continue;const le=q.getElementById("dv-popout-window");if(!(le instanceof HTMLElement))continue;le.classList.add("adhdev-dockview"),Nr(le,I),le.classList.toggle("is-showing-dockview-overlay",O),le.classList.toggle("is-dragging-dockview",L)}catch{}},[L,O,I]),me=o.useCallback(B=>{const $=w.current;if(!$)return;const F=$.getPanel(B);F&&$.addPopoutGroup(F,{popoutUrl:"/popout.html",onDidOpen:({window:q})=>{V(q),J();const le=ue.get(B);q.document.title=le?`${nt(le)} — ADHDev`:"ADHDev — Popout"}})},[ue,V]),ne=o.useCallback(B=>{const $=w.current,F=$==null?void 0:$.getPanel(B);if(!$||!F)return;const q=$.groups.filter(le=>{var ke;try{return((ke=le.element)==null?void 0:ke.ownerDocument)===document}catch{return!0}});q.length>0?F.api.moveTo({group:q[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),fe=o.useCallback(B=>{var q;const $=w.current;if(!$)return!1;const F=$.getPanel(B);if(!F)return!1;try{return((q=F.group.element)==null?void 0:q.ownerDocument)!==document}catch{return!1}},[]),se=o.useCallback(B=>{fe(B)&&ne(B),u(B)},[fe,ne,u]),xe=o.useCallback(B=>{const $=w.current,F=$==null?void 0:$.getPanel(B);!$||!F||$.addFloatingGroup(F,{width:600,height:500})},[]),ie=o.useCallback(B=>{var F;const $=(F=w.current)==null?void 0:F.getPanel(B);if(!$)return!1;try{return $.group.model.location.type==="floating"}catch{return!1}},[]),ce=o.useCallback(()=>{var $,F;const B=(F=($=w.current)==null?void 0:$.activePanel)==null?void 0:F.id;return!B||Lt(B)?null:ue.has(B)?B:null},[ue]),ae=o.useCallback(B=>{const $=w.current,F=$==null?void 0:$.getPanel(B);if(!$||!F)return;const q=$.groups.filter(le=>{try{return le.model.location.type==="grid"}catch{return!0}});q.length>0?F.api.moveTo({group:q[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),X=o.useCallback(()=>{var ke;const B=w.current;if(!B)return;const F=B.groups.filter(Me=>{var Ce;try{return((Ce=Me.element)==null?void 0:Ce.ownerDocument)===document&&Me.model.location.type==="grid"}catch{return!1}})[0]||null,q=[...B.panels];for(const Me of q){const Ce=(ke=Me.group.element)==null?void 0:ke.ownerDocument,re=Me.group.model.location.type;Ce===document&&re==="grid"||(F&&F.id!==Me.group.id?Me.api.moveTo({group:F,position:"center"}):Me.api.moveTo({position:"center"}))}const le=B.activePanel;le&&(le.group.model.openPanel(le),le.api.setActive()),Ln(document)},[]),J=o.useCallback(()=>{var $,F;const B=w.current;if(B)for(const q of B.groups){const le=($=q.element)==null?void 0:$.ownerDocument;if(!le||le===document)continue;const ke=le.getElementById("dv-popout-window");if(!(ke instanceof HTMLElement))continue;let Me=null,Ce=le.title||"ADHDev",re="Popout workspace";const je=q.activePanel;if(je)if(Me=je.id,Lt(je.id)){const Pe=((F=je.params)==null?void 0:F.routeId)||je.id.slice(7),_=_t([...ue.values()],Pe);Ce=yc(_),re=_!=null&&_.machineName?`Remote view · ${_.machineName}`:"Remote view"}else{const Pe=ue.get(je.id);Ce=Pe?nt(Pe):je.title||je.id,re=Pe?ts(Pe):"Dockview panel"}le.title=`${Ce} — ADHDev`;const We=Array.from(le.querySelectorAll("#adhdev-popout-header"));for(const Pe of We)Pe.remove();const Fe=le.createElement("div");Fe.id="adhdev-popout-header",le.body.appendChild(Fe),Fe.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(";")),Fe.innerHTML=`
44
44
  <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
45
45
  <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
@@ -68,9 +68,9 @@ This will disconnect CDP and optionally kill the process.`))try{const D=await r(
68
68
 
69
69
  `)}function sb({daemonLogs:e,trace:t,webEvents:r,daemonLogKind:n,daemonFetchError:a,traceFetchError:i,searchQuery:c}){const l=gl(e,c),d=yl(t,c),f=vl(r,c),u=l.filter(v=>v.level==="warn"||v.level==="error").map(v=>({source:"daemon",level:v.level,timestamp:v.timestamp,label:"daemon",detail:v.message})),x=d.filter(v=>v.level==="warn"||v.level==="error").map(v=>({source:"trace",level:v.level,timestamp:v.ts,label:`${v.category}.${v.stage}`,detail:er(v.payload,320)||`${v.category}.${v.stage}`})),m=[...u,...x].sort((v,S)=>S.timestamp-v.timestamp);return{daemonCount:l.length,traceCount:d.length,webCount:f.length,issueCount:m.length,latestIssue:m[0]||null,hasAnyData:n==="text"||l.length>0||d.length>0||f.length>0,hasBlockingError:!!(a||i)}}function ui(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function mi(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 Dn(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 rb({machineId:e,sendDaemonCommand:t}){var P,G;const[r,n]=o.useState([]),[a,i]=o.useState("empty"),[c,l]=o.useState(""),[d,f]=o.useState([]),[u,x]=o.useState([]),[m,v]=o.useState(null),[S,p]=o.useState(!0),[h,j]=o.useState("info"),[b,N]=o.useState("info"),[A,y]=o.useState("all"),[I,k]=o.useState(""),[w,g]=o.useState(!0),[E,M]=o.useState(!0),[C,R]=o.useState(""),[K,z]=o.useState(""),[T,L]=o.useState(0),[Y,O]=o.useState({daemon:!0,trace:!1,web:!1}),D=o.useRef(null),W=o.useRef(!1),Q=o.useRef(0),be=o.useRef(0),pe=o.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),ue=o.useRef([]),we=o.useCallback(()=>{const U={entries:[],kind:"empty",rawText:"",lastTs:0};pe.current=U,Q.current=0,n([]),l(""),i("empty"),g(!0)},[]),ye=o.useCallback(()=>{ue.current=[],be.current=0,f([]),M(!0)},[]),ve=o.useMemo(()=>qx(d,A),[d,A]),V=o.useMemo(()=>gl(r,I),[r,I]),H=o.useMemo(()=>Zx(c,I),[c,I]),Z=o.useMemo(()=>yl(ve,I),[ve,I]),me=o.useMemo(()=>vl(u,I),[u,I]),ne=o.useMemo(()=>b==="issues"?V.filter(U=>U.level==="warn"||U.level==="error"):b==="info"?V.filter(U=>U.level!=="debug"):V,[V,b]),fe=o.useMemo(()=>b==="all"?H:[],[H,b]),se=o.useMemo(()=>b==="issues"?Z.filter(U=>U.level==="warn"||U.level==="error"):b==="info"?Z.filter(U=>U.level!=="debug"):Z,[Z,b]),xe=o.useMemo(()=>b==="issues"?[]:me,[me,b]),ie=o.useMemo(()=>eb({daemonLogs:V,daemonRawLines:H,trace:Z,webEvents:me}),[V,H,Z,me]),ce=o.useMemo(()=>sb({daemonLogs:r,trace:ve,webEvents:u,daemonLogKind:a,daemonFetchError:C,traceFetchError:K,searchQuery:I}),[C,a,r,ve,I,K,u]),ae=o.useCallback(async()=>{if(!e)return;const U=Q.current,de=be.current,[Ne,_e]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:h,since:U}),t(e,"get_debug_trace",Gx({count:120,since:de,category:A}))]);if(Ne.status==="fulfilled"){const ge=Ne.value,Be=(ge==null?void 0:ge.result)||ge,Oe=Xx(Be),Ke=Jx(pe.current,Oe,300);pe.current=Ke,Q.current=Ke.lastTs,g(!1),R((ge==null?void 0:ge.success)===!1?String((ge==null?void 0:ge.error)||"Could not load daemon logs"):""),i(Ke.kind),l(Ke.rawText),n(Ke.entries)}else g(!1),R(Ne.reason instanceof Error?Ne.reason.message:"Could not load daemon logs");if(_e.status==="fulfilled"){const ge=_e.value,Be=(ge==null?void 0:ge.result)||ge;if((ge==null?void 0:ge.success)===!1)z(String((ge==null?void 0:ge.error)||"Could not load daemon trace"));else if(Array.isArray(Be==null?void 0:Be.trace)){const Oe=Be.trace,Ke=Qx(ue.current,Oe,120),et=Oe.reduce((Je,at)=>Math.max(Je,Number(at.ts||0)),de);ue.current=Ke,et>de&&(be.current=et),z(""),f(Ke)}else z("");M(!1)}else M(!1),z(_e.reason instanceof Error?_e.reason.message:"Could not load daemon trace");x(ks.list({limit:120})),v(Date.now())},[h,e,t,A]);o.useEffect(()=>{ye()},[ye,A]),o.useEffect(()=>{if(!e||(ae(),!S))return;const U=setInterval(()=>{ae()},3e3);return()=>clearInterval(U)},[S,ae,e,T]),o.useEffect(()=>{if(S&&(ne.length>0||fe.length>0||se.length>0||xe.length>0)){const U=W.current?"smooth":"instant";setTimeout(()=>{var de;(de=D.current)==null||de.scrollIntoView({behavior:U}),W.current=!0},50)}},[ne.length,fe.length,se.length,xe.length,S]);const X=((P=ce.latestIssue)==null?void 0:P.level)==="error"?"danger":((G=ce.latestIssue)==null?void 0:G.level)==="warn"?"warning":"good",J=C||K?"danger":S?"good":"neutral",oe=o.useCallback(async()=>{var de;const U=tb({daemonLogs:ne,daemonRawLines:fe,trace:se,webEvents:xe});if(!U.trim()){lt.showToast("No visible logs to copy.","info");return}try{await((de=navigator.clipboard)==null?void 0:de.writeText(U)),lt.showToast("Copied visible logs to clipboard.","success")}catch(Ne){lt.showToast(Ne instanceof Error?Ne.message:"Could not copy visible logs","warning")}},[ne,fe,se,xe]);return s.jsxs("div",{className:"space-y-4",children:[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:"Level"}),["debug","info","warn","error"].map(U=>s.jsx("button",{onClick:()=>{U!==h&&(j(U),we())},className:`machine-btn text-[10px] px-2 py-0.5 ${h===U?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:U.toUpperCase()},U)),s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider ml-3 mr-1",children:"Trace"}),Vx.map(U=>s.jsx("button",{onClick:()=>{U.value!==A&&y(U.value)},className:`machine-btn text-[10px] px-2 py-0.5 ${A===U.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:U.label},U.value))]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[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+ (${ie.info})`},{id:"issues",label:`Issues (${ie.issues})`},{id:"all",label:`All (${ie.all})`}].map(U=>s.jsx("button",{type:"button",onClick:()=>N(U.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${b===U.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:U.label},U.id))}),s.jsx("input",{value:I,onChange:U=>k(U.target.value),placeholder:"Search visible logs, trace, events…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"}),s.jsx("button",{onClick:()=>{oe()},className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:()=>p(U=>!U),className:`machine-btn ${S?"text-green-500 border-green-500/30":""}`,children:S?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:()=>L(U=>U+1),className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:()=>{we(),ye(),x([]),v(null),R(""),z(""),ks.clear()},className:"machine-btn",children:"Clear"})]})]}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${Dn(ce.issueCount>0?"warning":"good")}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Visible signals"}),s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:["daemon ",ne.length+fe.length," · trace ",se.length," · web ",xe.length]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:I.trim()?`Filtered by “${I.trim()}”`:"Showing the latest buffered entries"})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Dn(X)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Attention needed"}),ce.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[ce.latestIssue.source," · ",ce.latestIssue.label]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:ce.latestIssue.detail}),s.jsxs("div",{className:"text-[10px] text-text-muted mt-2",children:[ce.issueCount," warn/error signal(s) · ",ui(ce.latestIssue.timestamp)]})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No recent warn/error signal"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use search or lower the log level if you need more context."})]})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Dn(J)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Fetch status"}),s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:C||K?"Needs attention":S?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",ui(m)]}),(C||K)&&s.jsxs("div",{className:"text-[11px] text-red-300 mt-2 space-y-1",children:[C&&s.jsxs("div",{children:["Daemon logs: ",C]}),K&&s.jsxs("div",{children:["Daemon trace: ",K]})]})]})]}),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:()=>O(U=>({...U,daemon:!U.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:a==="text"?`${fe.length} visible raw line(s) from file fallback`:`${ne.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:Y.daemon?"Hide":"Show"})]}),Y.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:[w&&!ce.hasAnyData&&!C&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!w&&C&&a==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:C}),!w&&a==="empty"&&!C&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),a==="text"&&fe.length===0&&c&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:b==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),a==="structured"&&ne.length===0&&r.length>0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),a==="text"&&fe.map((U,de)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:U},`raw-${de}`)),a!=="text"&&ne.map((U,de)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${mi(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-${de}`))]})]}),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:()=>O(U=>({...U,trace:!U.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Structured daemon trace",A==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[se.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:Y.trace?"Hide":"Show"})]}),Y.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&&se.length===0&&!K&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!E&&K&&se.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:K}),!E&&se.length===0&&!K&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:I.trim()?"No trace entries match the current search.":A==="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."}),se.map(U=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${mi(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:er(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:()=>O(U=>({...U,web:!U.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[xe.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:Y.web?"Hide":"Show"})]}),Y.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:[xe.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:I.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),xe.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:er(U.payload,360)||"No payload"})]},U.id))]})]})]}),s.jsx("div",{ref:D})]})}function nb(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 wl(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 ab(e){var a;const t=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=wl((i==null?void 0:i.meta)||void 0),d=((a=i==null?void 0:i.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(c)?t.push(i):(c==="stopped"||c==="failed")&&(d||l)?r.push(i):n.push(i)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function ob(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function En(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 $n(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Bn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function fi(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 ib(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function cb(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 lb(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 i=`${n.providerType}::${n.workspace}::${a}`;t.set(i,(t.get(i)||0)+1)}return Array.from(t.values()).filter(n=>n>1).length}function db({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,d]=o.useState(!1),f=yp(e,{enabled:!!e,includeSessions:!0,limit:Mo,intervalMs:Lm}),u=f.diagnostics,x=f.loading,m=f.applyDiagnostics,v=o.useMemo(()=>nb({diagnostics:u,loading:x,refreshing:l,error:n}),[u,x,l,n]),S=o.useMemo(()=>new Map(t.map(M=>[M.sessionId||M.id,M])),[t]),p=o.useCallback(async()=>{if(e){d(!0);try{const M=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Mo}),C=$n(M);if(!(C!=null&&C.success))throw new Error((C==null?void 0:C.error)||"Could not load hosted runtime diagnostics");m(C.diagnostics||C.result||null),a("")}catch(M){const C=M instanceof Error?M.message:"Could not load hosted runtime diagnostics";a(C)}finally{d(!1)}}},[m,e,r]);o.useEffect(()=>{!e||u||x||l||p()},[u,x,e,p,l]);const h=o.useCallback(async(M,C)=>{const R=`${M}:${C.sessionId}`;if(!(M==="session_host_stop_session"&&!window.confirm(`Stop ${C.displayName}?
70
70
  This will terminate the hosted runtime.`))){c(R);try{const K=await r(e,M,{sessionId:C.sessionId}),z=$n(K);if(!(z!=null&&z.success))throw new Error((z==null?void 0:z.error)||"Session host action failed");const T=M==="session_host_resume_session"?"resumed":M==="session_host_restart_session"?"restarted":"stopped";lt.showToast(`Session host ${T}: ${C.displayName}`,"success"),await p()}catch(K){const z=K instanceof Error?K.message:"Session host action failed";lt.showToast(z,"warning"),a(z)}finally{c(K=>K===R?null:K)}}},[e,p,r]),j=o.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
71
- The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){c("session_host_prune_duplicate_sessions");try{const C=await r(e,"session_host_prune_duplicate_sessions",{}),R=$n(C);if(!(R!=null&&R.success))throw new Error((R==null?void 0:R.error)||"Duplicate prune failed");const K=R.result||{},z=Array.isArray(K.prunedSessionIds)?K.prunedSessionIds.length:0,T=typeof K.duplicateGroupCount=="number"?K.duplicateGroupCount:0;lt.showToast(`Pruned ${z} duplicate runtime(s) across ${T} group(s)`,"success"),await p()}catch(C){const R=C instanceof Error?C.message:"Duplicate prune failed";lt.showToast(R,"warning"),a(R)}finally{c(C=>C==="session_host_prune_duplicate_sessions"?null:C)}}},[e,p,r]),b=o.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((M,C)=>(C.lastActivityAt||0)-(M.lastActivityAt||0)),[u==null?void 0:u.sessions]),N=o.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:ab(b),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,b]),A=N.liveRuntimes,y=N.recoverySnapshots,I=N.inactiveRecords,k=o.useMemo(()=>lb(A),[A]),w=o.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),g=o.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(M=>M.level==="warn"||M.level==="error")||null,[u==null?void 0:u.recentLogs]),E=(M,C)=>{var W;const R=i===`session_host_resume_session:${M.sessionId}`,K=i===`session_host_restart_session:${M.sessionId}`,z=i===`session_host_stop_session:${M.sessionId}`,T=wl(M.meta),L=S.get(M.sessionId),Y=M.attachedClients.length===1?"1 client":`${M.attachedClients.length} clients`,O=C==="recovery"?"Recover":"Resume",D=ob(C);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:M.displayName||(L==null?void 0:L.cliName)||M.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${cb(M.lifecycle)}`,children:M.lifecycle}),T&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:T})]}),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:M.workspaceLabel||(L==null?void 0:L.runtimeWorkspaceLabel)||M.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:M.runtimeKey}),M.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",M.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((W=M.writeOwner)==null?void 0:W.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:ib(M.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(Ti,{size:11})," ",Y]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",fi(M.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",D]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[C==="recovery"&&(M.lifecycle==="interrupted"||M.lifecycle==="failed"||M.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{h("session_host_resume_session",M)},children:R?`${O}ing…`:O}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{h("session_host_restart_session",M)},children:K?"Restarting…":"Restart"}),C==="live"&&(M.lifecycle==="running"||M.lifecycle==="starting"||M.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:!!i,onClick:()=>{h("session_host_stop_session",M)},children:z?"Stopping…":"Stop"})]})]})},M.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(ls,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Nf()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[k>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{j()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${k})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${v.toneClass}`,children:v.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:x||l,children:[s.jsx(sr,{size:13}),x||l?"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(Xs,{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:y.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:fi(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Bn(u.hostStartedAt)})]})]}),g&&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(Xs,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:g.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Bn(g.timestamp),g.sessionId?` · ${g.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(ga,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:En("live")}),A.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:A.map(M=>E(M,"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(ls,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:En("recovery")}),y.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:y.map(M=>E(M,"recovery"))})]}),I.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:En("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:I.map(M=>E(M,"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"}),w.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:w.map(M=>{var R;const C=b.find(K=>K.sessionId===M.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:(C==null?void 0:C.displayName)||((R=S.get(M.sessionId))==null?void 0:R.cliName)||M.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[M.action,M.lifecycle?` · ${M.lifecycle}`:"",M.detail?` · ${M.detail}`:"",M.error?` · ${M.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${M.success===!1?"text-red-300":"text-text-secondary"}`,children:Bn(M.timestamp)})]},`${M.sessionId}:${M.timestamp}:${M.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 ub({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(i=>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:i.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.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 Kn({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 On({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 mb({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),d=r.slice(0,4),u=zs(e,"0.9.26");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:[l.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Kn,{icon:s.jsx(Ut,{size:13}),children:"Current Chats"}),s.jsx(On,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(x=>{const m=ea(x);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>c(x),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:nt(x)}),m>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Jr(m)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:us(x)})]},x.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Kn,{icon:s.jsx(Di,{size:13}),children:"Recent Launches"}),s.jsx(On,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(x=>{const{metaText:m,updatedLabel:v}=tl(x);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>i(x),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:x.label}),v&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:v})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:m})]},x.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Kn,{icon:s.jsx(Xs,{size:13}),children:"Daemon Update"}),s.jsx(On,{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:u?"Daemon update required":"Version mismatch detected"}),s.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:u?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),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(sr,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function fb(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const pb={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 Ir(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Wn({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:d,initialWorkspacePath:f}){const u=As(),{handleLaunchIde:x,handleStopCli:m,handleRestartIde:v,handleStopIde:S,handleDetectIdes:p,launchingIde:h,launchingAgentType:j,addLog:b}=c,[N,A]=o.useState(null),y=o.useCallback(_=>{_&&u(Gt(_))},[u]),I=pb[e],k=e==="ide",w=e==="acp",g=o.useMemo(()=>n.filter(_=>_.category===e&&(e==="ide"||_.installed!==!1)),[e,n]),E=o.useMemo(()=>new Map(g.map(_=>[_.type,_.displayName||_.type])),[g]),[M,C]=o.useState(""),[R,K]=o.useState(""),[z,T]=o.useState([]),[L,Y]=o.useState(""),[O,D]=o.useState(""),[W,Q]=o.useState([]),[be,pe]=o.useState(!1),[ue,we]=o.useState(!1),[ye,ve]=o.useState(""),[V,H]=o.useState(!1),[Z,me]=o.useState(()=>ht()),[ne,fe]=o.useState(null),[se,xe]=o.useState(f?"__custom__":d||t.defaultWorkspaceId||""),[ie,ce]=o.useState(f||""),[ae,X]=o.useState([]),[J,oe]=o.useState(!1),[P,G]=o.useState(""),[U,de]=o.useState([]),[Ne,_e]=o.useState(!1),[ge,Be]=o.useState(""),Oe=o.useRef(null),[Ke,et]=o.useState(null),Je=o.useRef("__home__"),[at,dt]=o.useState("__home__"),[mt,ot]=o.useState(!1),ut=o.useRef(0),Ie=ae.filter(_=>!a.some(te=>te.type===_&&bt(te.status)!=="stopped")),$e=o.useRef({});o.useEffect(()=>{t.defaultWorkspaceId&&!se&&xe(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),o.useEffect(()=>{if(f){xe("__custom__"),ce(f);return}d&&(xe(d),ce(""))},[d,f]),o.useEffect(()=>{k||M&&(g.some(_=>_.type===M)||(C(""),D("")))},[g,k,M]);const Ue=(()=>{if(se==="__custom__")return ie.trim();if(!se)return"";const _=(t.workspaces||[]).find(te=>te.id===se);return(_==null?void 0:_.path)||""})(),Ve=o.useCallback(_=>{const te=$e.current[_];te&&(clearTimeout(te),delete $e.current[_]),X(he=>he.includes(_)?he.filter(Re=>Re!==_):he)},[]),qe=o.useRef(new Set),Qe=o.useCallback(async _=>{if(l){_e(!0),Be("");try{const te=await rn(l,r,_);G(te.path),ce(te.path),de(te.directories)}catch(te){Be(te instanceof Error?te.message:"Could not load folder")}finally{_e(!1)}}},[r,l]),ee=o.useCallback(()=>{if(!l)return;xe("__custom__"),oe(!0);const _=a.map(he=>he.workspace),te=sn(t.platform,tn(ie.trim(),Ue,f,_,t.defaultWorkspacePath,(t.workspaces||[]).map(he=>he.path)));Qe(te)},[ie,f,Qe,t.defaultWorkspacePath,t.platform,t.workspaces,a,Ue,l]),Le=o.useCallback(_=>{const te=String(_.workspace||"").trim();if(!te)return;const he=(t.workspaces||[]).find(Re=>Ir(Re.path)===Ir(te));if(he){xe(he.id),ce("");return}xe("__custom__"),ce(te)},[t.workspaces]),De=o.useCallback(_=>{const te=String(_.workspace||"").trim();if(!te)return{workspaceId:null,workspacePath:"",useHome:!0};const he=(t.workspaces||[]).find(Re=>Ir(Re.path)===Ir(te));return he?{workspaceId:he.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:te,useHome:!1}},[t.workspaces]),rt=o.useCallback(async _=>{if(!l||!_||e!=="cli"){Q([]),pe(!1),we(!1),ve("");return}const te=ut.current+1;ut.current=te,pe(!0),ve("");try{const he=await l(r,"list_saved_sessions",{providerType:_,kind:"cli",limit:30});if(ut.current!==te)return;const Re=(he==null?void 0:he.result)??he;Q(Array.isArray(Re==null?void 0:Re.sessions)?Re.sessions:[])}catch(he){if(ut.current!==te)return;Q([]),ve(he instanceof Error?he.message:"Could not load saved sessions")}finally{ut.current===te&&(pe(!1),we(!0))}},[e,r,l]),Ct=o.useMemo(()=>{if(e!=="cli"||!M)return null;const _=E.get(M)||M;return{routeId:r,daemonId:r,providerSessionId:O||void 0,transport:"pty",mode:"chat",agentName:_,agentType:M,status:"idle",title:_,messages:[],ideType:M,workspaceName:Ue,displayPrimary:_,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${M}`}},[e,r,E,Ue,O,M]),ft=o.useCallback(_=>{if(e==="ide"||!_){T([]);return}T(pl(r,_))},[e,r]);o.useEffect(()=>{ut.current+=1,D(""),ft(M),we(!1),Q([]),ve(""),pe(!1)},[e,ft,rt,M]);const Tt=o.useMemo(()=>W.find(_=>_.providerSessionId===O)||null,[W,O]);o.useEffect(()=>{if(!O)return;const _=W.find(te=>te.providerSessionId===O);_!=null&&_.canResume||D("")},[W,O]);const yt=o.useCallback((_,te)=>{Oe.current=te,Je.current=_.selectedWorkspaceKey||"__home__",dt(_.selectedWorkspaceKey||"__home__"),et(_)},[]),B=o.useCallback(()=>{Oe.current&&(ot(!0),Oe.current().finally(()=>{Oe.current=null,ot(!1),et(null)}))},[]),$=o.useCallback(_=>{if(!_)return;X(he=>he.includes(_)?he:[...he,_]);const te=$e.current[_];te&&clearTimeout(te),$e.current[_]=setTimeout(()=>{X(he=>he.includes(_)?he.filter(Re=>Re!==_):he),delete $e.current[_]},2e4)},[]);o.useEffect(()=>{for(const te of a)bt(te.status)!=="stopped"&&(ae.includes(te.type)&&!qe.current.has(te.type)&&(qe.current.add(te.type),b("info",`${E.get(te.type)||te.type} launched`,!0)),Ve(te.type));const _=new Set(a.filter(te=>bt(te.status)!=="stopped").map(te=>te.type));qe.current.forEach(te=>{!ae.includes(te)&&!_.has(te)&&qe.current.delete(te)})},[b,Ve,a,ae,E]),o.useEffect(()=>()=>{Object.values($e.current).forEach(clearTimeout),$e.current={}},[]);const[F,q]=o.useState({}),[le,ke]=o.useState(null);o.useEffect(()=>{if(!k||!r||!l)return;(async()=>{try{const te=await l(r,"get_ide_extensions",{}),he=(te==null?void 0:te.result)||te;he!=null&&he.success&&(he!=null&&he.ideExtensions)&&q(he.ideExtensions)}catch{}})()},[k,r,l]);const Me=_=>k?st(_.type):e==="cli"?_.cliName:_.acpName,Ce=k?t.detectedIdes||[]:[],re=o.useCallback(async _=>{const te=(_==null?void 0:_.type)||M,he=(_==null?void 0:_.workspacePath)??Ue;if(k){await x(te,he?{workspace:he}:void 0)&&$(te);return}const Re=await c.runLaunchCliCore({cliType:te,dir:_!=null&&_.workspaceId?void 0:he||void 0,workspaceId:(_==null?void 0:_.workspaceId)||void 0,useHome:(_==null?void 0:_.useHome)||!(_!=null&&_.workspaceId)&&!he,argsStr:(_==null?void 0:_.argsStr)??(R||void 0),model:(_==null?void 0:_.model)??(w&&L||void 0),resumeSessionId:(_==null?void 0:_.resumeSessionId)||!w&&e==="cli"&&te===M&&O||void 0});if(Re.success||Re.pending){const Se=(_==null?void 0:_.argsStr)??R;!k&&(Se!=null&&Se.trim())&&(hl(r,te,Se),ft(te)),$(te),Re.success&&Re.sessionId&&y(Re.sessionId)}},[c,x,w,k,R,L,ft,$,r,y,Ue,O,M]),je=jc(k?"ide":w?"acp":"cli",!k&&!w&&!!O),We=kc(k?"ide":w?"acp":"cli",!k&&!w&&!!O),Fe=()=>{var Se;const _=k?st(M):E.get(M)||M,te=!k&&!w&&!!O,{options:he,selectedKey:Re}=os({machine:t,currentWorkspaceId:se&&se!=="__custom__"?se:null,currentWorkspacePath:Ue});yt({title:te?Da(_):ss("start-fresh",_),description:te?Ea():rs("start-fresh"),confirmLabel:je,busyLabel:We,workspaceOptions:he,selectedWorkspaceKey:Re,details:[{label:"Mode",value:I.label},{label:"Provider",value:_},...!k&&e==="cli"&&O?[{label:"Resume",value:((Se=W.find(Ae=>Ae.providerSessionId===O))==null?void 0:Se.title)||O}]:[],...!k&&R.trim()?[{label:"Arguments",value:R.trim()}]:[],...w&&L.trim()?[{label:"Model",value:L.trim()}]:[]]},async()=>{const Ae=he.find(Te=>Te.key===Je.current);Ae!=null&&Ae.workspaceId?(xe(Ae.workspaceId),ce("")):Ae!=null&&Ae.workspacePath?(xe("__custom__"),ce(Ae.workspacePath)):(xe(""),ce("")),await re({workspaceId:(Ae==null?void 0:Ae.workspaceId)??null,workspacePath:(Ae==null?void 0:Ae.workspacePath)??"",useHome:!(Ae!=null&&Ae.workspaceId)&&!(Ae!=null&&Ae.workspacePath)})})},Ye=_=>{k?S(_):m(_.type,_.workspace,_.id)},ze=o.useCallback(async(_,te,he=!1)=>{if(_.mode===te){he&&_.sessionId&&y(_.sessionId);return}if(!l||!_.sessionId){he&&_.sessionId&&y(_.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:_.sessionId,cliType:_.type,mode:te}),he&&y(_.sessionId)}catch(Re){const Se=Fc(Re);Hc(Re)?console.warn(Se?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Re instanceof Error?Re.message:String(Re)):console.error("Failed to switch CLI view mode:",Re)}},[r,y,l]),Pe=s.jsxs("div",{className:"mb-3",children:[s.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[s.jsx("select",{value:se,onChange:_=>{const te=_.target.value;if(xe(te),te==="__custom__"&&l){ee();return}te!=="__custom__"&&ce("")},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:(t.workspaces||[]).length>0?s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(t.workspaces||[]).map(_=>s.jsxs("option",{value:_.id,children:[_.id===t.defaultWorkspaceId?"⭐ ":"",Zr(_.path,_.label)]},_.id)),s.jsx("option",{value:"__custom__",children:l?"📁 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:l?"📁 Select workspace…":"✏️ Custom path…"})]})}),se==="__custom__"&&(l?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:ee,children:"Select workspace…"}):s.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:ie,onChange:_=>ce(_.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:se==="__custom__"?Ue?s.jsx("span",{className:"font-mono truncate block",title:Ue,children:Ue}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":Ue?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:se===t.defaultWorkspaceId?"Default workspace":"Selected workspace"}),s.jsx("span",{className:"font-mono truncate block",title:Ue,children:Ue})]}):"No workspace selected. This launches in the home directory."})]});return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${I.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 ",I.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:k?Ce.length>0?Ce.map(_=>{const te=a.find(Te=>(Te.type||"").toLowerCase()===(_.type||"").toLowerCase()&&bt(Te.status)!=="stopped"),he=_.running||!!te,Re=!!te&&te.cdpConnected,Se=ae.includes(_.type||_.id||""),Ae=M===(_.type||"");return s.jsxs("button",{onClick:()=>{if(Re&&te){const Te=te.sessionId;Te?u(Gt(Te),{state:{openRemoteForTabKey:Te}}):u("/dashboard",{state:{openRemoteForTabKey:te.id}});return}Se||C(Te=>Te===(_.type||"")?"":_.type||"")},disabled:!!h||Se,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Re?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Ae?"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:h&&h!==_.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:i(_.type)}),he&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Re?"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||st(_.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Re?"text-green-400":Se?"text-orange-400":Ae?"text-accent-primary":"text-text-muted"}`,children:Re?"Open Session":Se?"Starting...":Ae?"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:p,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($d,{size:14})," Scan System"]})]}):g.length>0?g.map(_=>{const te=M===_.type,he=ae.includes(_.type),Se=!!a.find(Ae=>Ae.type===_.type&&bt(Ae.status)!=="stopped");return s.jsxs("button",{onClick:()=>C(Ae=>Ae===_.type?"":_.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${te?"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}),Se&&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 ${he?"text-orange-400":te?"text-accent-primary":"text-text-muted"}`,children:he?"Starting...":te?"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."})]})}),M&&(k?Ce.find(_=>_.type===M):g.find(_=>_.type===M))&&s.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[s.jsx("span",{children:"Launch Settings"}),s.jsx("span",{className:"text-accent-primary font-bold",children:k?st(M):E.get(M)||M})]}),Pe,!k&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!w&&e==="cli"&&s.jsx(bl,{busy:!!j||!!h||ae.includes(M),savedSessionsLoading:be,savedSessionsError:ye,selectedSession:Tt,onRefresh:()=>void rt(M),onOpenHistory:()=>{M&&(H(!0),xl({hasLoadedInitialResults:ue,isLoading:be})&&rt(M))},onClearSelection:()=>D("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[w&&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:L,onChange:_=>Y(_.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:R,onChange:_=>K(_.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),z.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:z.map(_=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>K(_),title:_,children:_},_))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:Fe,disabled:!!j||!!h||ae.includes(M),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:j===M||h===M?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+ae.filter(_=>!a.some(te=>te.type===_&&bt(te.status)!=="stopped")).length,")"]}),a.length===0&&Ie.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 ",I.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Ie.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:i(_)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:k?st(_):E.get(_)||_}),s.jsx("div",{className:"text-[11px] text-text-muted",children:j===_?"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 te=k?_:null,he=!k&&!w?_:null,Re=bt(_.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:i(_.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Me(_),(te==null?void 0:te.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",te.version]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[s.jsx("span",{children:_.workspace||"—"}),(he==null?void 0:he.mode)&&s.jsx("span",{className:he.mode==="chat"?"text-violet-400":"text-text-secondary",children:he.mode==="chat"?"Chat view":"Terminal view"})]}),he&&(he.runtimeKey||he.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[he.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 ",he.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 Se;(Se=navigator.clipboard)==null||Se.writeText(`adhdev attach ${he.runtimeKey}`),A(he.runtimeKey||null),window.setTimeout(()=>{A(Ae=>Ae===he.runtimeKey?null:Ae)},1200)},children:N===he.runtimeKey?"Copied":"Copy"})]}),he.runtimeWriteOwner&&s.jsx("span",{style:{color:he.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:he.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:fb(he.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 ${Re==="stopped"?"bg-red-500/[0.08] text-red-500":Re==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Re}),k&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const Se=_.sessionId;if(Se){u(Gt(Se),{state:{openRemoteForTabKey:Se}});return}u("/dashboard",{state:{openRemoteForTabKey:_.id}})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-primary transition-colors cursor-pointer",title:"Open remote control",children:s.jsx(Nt,{size:13})}),s.jsx("button",{onClick:()=>{const Se=_.workspace||"",{options:Ae,selectedKey:Te}=os({machine:t,currentWorkspacePath:Se});yt({title:ss("restart-ide",st(_.type)),description:rs("restart-ide"),confirmLabel:Is("restart-ide"),busyLabel:Ms("restart-ide"),workspaceOptions:Ae,selectedWorkspaceKey:Te,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:st(_.type)}]},async()=>{const pt=Ae.find(Ot=>Ot.key===Je.current),ct=(pt==null?void 0:pt.workspacePath)??"";if(ct&&ct!==Se){await re({type:_.type,workspacePath:ct});return}await v(_)})},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(sr,{size:14})})]}),w&&s.jsx("button",{onClick:()=>{const Se=_.sessionId;Se&&y(Se)},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(Ut,{size:14})}),he&&Re!=="stopped"&&s.jsxs(s.Fragment,{children:[he.mode&&s.jsx(Ra,{mode:he.mode,onChange:Se=>void ze(he,Se,!1),compact:!0}),s.jsx("button",{onClick:()=>{const Se=_.sessionId;Se&&y(Se)},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:he.mode==="chat"?s.jsx(Ut,{size:14}):s.jsx(Nt,{size:13})})]}),Re==="stopped"?s.jsx("button",{onClick:()=>{const Se=_.workspace||"",Ae=k?st(_.type):Me(_),{options:Te,selectedKey:pt}=os({machine:t,currentWorkspacePath:Se});yt({title:ss("restart-stopped",Ae),description:rs("restart-stopped"),confirmLabel:Is("restart-stopped"),busyLabel:Ms("restart-stopped"),workspaceOptions:Te,selectedWorkspaceKey:pt,details:[{label:"Mode",value:I.label},{label:"Provider",value:Ae}]},async()=>{const ct=Te.find(Ot=>Ot.key===Je.current);await re({type:_.type,workspaceId:(ct==null?void 0:ct.workspaceId)??null,workspacePath:(ct==null?void 0:ct.workspacePath)??"",useHome:!(ct!=null&&ct.workspaceId)&&!(ct!=null&&ct.workspacePath)})})},disabled:ae.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:ae.includes(_.type)?"⏳":s.jsx(ya,{size:14})}):s.jsx("button",{onClick:()=>Ye(_),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(vt,{size:14})})]})]}),te&&te.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:te.aiAgents.map(Se=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${zi(Se.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Se.name," · ",bt(Se.status)]},Se.id))}),te&&(F[te.type]||[]).length>0&&l&&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:(F[te.type]||[]).map(Se=>s.jsxs("button",{disabled:le===`${te.type}.${Se.type}`,onClick:async()=>{const Ae=`${te.type}.${Se.type}`;ke(Ae);try{await l(r,"set_ide_extension",{ideType:te.type,extensionType:Se.type,enabled:!Se.enabled}),q(Te=>({...Te,[te.type]:(Te[te.type]||[]).map(pt=>pt.type===Se.type?{...pt,enabled:!pt.enabled}:pt)}))}catch(Te){console.error("Extension toggle failed:",Te)}finally{ke(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 ${Se.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 ${Se.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Se.name,s.jsx("span",{className:"text-[9px] font-normal",children:Se.enabled?"ON":"OFF"})]},Se.type))})]})]},_.id)})]}),J&&l&&s.jsx(an,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:P,directories:U,busy:Ne,error:ge,confirmLabel:"Use this folder",onClose:()=>oe(!1),onNavigate:_=>{Qe(_)},onConfirm:_=>{ce(_),xe("__custom__"),oe(!1)}}),Ke&&s.jsx(Ga,{title:Ke.title,description:Ke.description,details:Ke.details,workspaceOptions:Ke.workspaceOptions,selectedWorkspaceKey:at,onWorkspaceChange:_=>{Je.current=_,dt(_)},confirmLabel:Ke.confirmLabel,busyLabel:Ke.busyLabel,busy:mt,onConfirm:B,onCancel:()=>{Oe.current=null,et(null)}}),V&&Ct&&s.jsx($a,{activeConv:Ct,ides:[],isCreatingChat:!1,isRefreshingHistory:be,savedSessions:W,isSavedSessionsLoading:be,isResumingSavedSessionId:ne,savedHistoryFilters:Z,onSavedHistoryFiltersChange:me,onClose:()=>H(!1),onNewChat:()=>{D(""),H(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{rt(M)},onResumeSavedSession:_=>{if(!_.canResume||ne)return;const te=De(_);D(_.providerSessionId),Le(_),fe(_.providerSessionId),H(!1),re({type:_.providerType,workspaceId:te.workspaceId,workspacePath:te.workspacePath,useHome:te.useHome,resumeSessionId:_.providerSessionId}).finally(()=>{fe(he=>he===_.providerSessionId?null:he)})}})]})}const pi=[{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 hb({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:d="ide",initialWorkspaceId:f,initialWorkspacePath:u,sendDaemonCommand:x}){var p;const[m,v]=o.useState(d);o.useEffect(()=>{v(d)},[d]);const S=o.useMemo(()=>({ide:n.length,cli:a.length,acp:i.length}),[n.length,a.length,i.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:pi.map(h=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${m===h.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>v(h.id),children:[s.jsx("span",{children:h.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${m===h.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:S[h.id]})]},h.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(p=pi.find(h=>h.id===m))==null?void 0:p.helper})]}),m==="ide"&&s.jsx(Wn,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:x,initialWorkspaceId:f,initialWorkspacePath:u}),m==="cli"&&s.jsx(Wn,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:x,initialWorkspaceId:f,initialWorkspacePath:u}),m==="acp"&&s.jsx(Wn,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:x,initialWorkspaceId:f,initialWorkspacePath:u})]})}function xb({onNicknameSynced:e}={}){var fe,se,xe,ie,ce,ae,X,J,oe;const{id:t}=id(),r=As(),n=pa(),{sendCommand:a}=wt(),i=ar(),c=Bc(),l=pc(),d=l.ides||[],f=l.initialLoaded??!0,u=d.find(P=>P.id===t&&P.type==="adhdev-daemon"),x=d.some(P=>P.type==="adhdev-daemon"),[m,v]=o.useState("workspace"),[S,p]=o.useState("ide"),h=o.useRef(null),[j,b]=o.useState(null),N=o.useRef("__home__"),[A,y]=o.useState("__home__"),[I,k]=o.useState(!1),w=o.useRef(null);o.useEffect(()=>{!t||!u||!(!u.workspaces||!u.availableProviders||!u.detectedIdes||!u.recentLaunches)||i(t,{minFreshMs:3e4}).catch(()=>{})},[i,u,t]),o.useEffect(()=>{if(!t||!u||m!=="overview")return;const P=u.machine;(typeof(P==null?void 0:P.cpus)!="number"||typeof(P==null?void 0:P.totalMem)!="number"||typeof(P==null?void 0:P.arch)!="string"||typeof(P==null?void 0:P.release)!="string")&&c(t,{minFreshMs:3e4}).catch(()=>{})},[m,c,u,t]),gp(t&&m==="overview"?[t]:[],{enabled:m==="overview",intervalMs:Im});const g=()=>{if(x){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},E=$x({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:w});o.useEffect(()=>lt.onToast(G=>{l.setToasts(de=>{if(de.some(ge=>ge.message===G.message&&G.timestamp-ge.timestamp<3e3))return de;const _e={id:G.id,message:G.message,type:G.type,timestamp:G.timestamp,targetKey:G.targetKey,actions:G.actions};return[...de.slice(-4),_e]});const U=G.duration||5e3;setTimeout(()=>l.setToasts(de=>de.filter(Ne=>Ne.id!==G.id)),U)}),[l]);const M=(u==null?void 0:u.availableProviders)||[],C={};for(const P of M)C[P.type]=P.icon;const R=P=>C[P]||"",K=u?{id:u.id,hostname:Vi(u,{fallbackId:u.id}),platform:((fe=u.machine)==null?void 0:fe.platform)||"unknown",arch:((se=u.machine)==null?void 0:se.arch)||"",cpus:((xe=u.machine)==null?void 0:xe.cpus)||0,totalMem:((ie=u.machine)==null?void 0:ie.totalMem)||0,freeMem:(ce=u.machine)==null?void 0:ce.freeMem,availableMem:(ae=u.machine)==null?void 0:ae.availableMem,loadavg:(X=u.machine)==null?void 0:X.loadavg,uptime:(J=u.machine)==null?void 0:J.uptime,release:((oe=u.machine)==null?void 0:oe.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,z=d.filter(P=>P.daemonId===t&&P.type!=="adhdev-daemon").filter(P=>!Qs(P)&&!ys(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,version:P.version||"",instanceId:P.instanceId||"",status:P.status,workspace:P.workspace||null,terminals:P.terminals||0,aiAgents:Ru(P.aiAgents||(P.agents||[]).map(G=>({id:G.name,name:G.name,status:G.status,version:G.version}))),activeChat:P.activeChat||null,chats:P.chats||[],childSessions:P.childSessions||[],cdpConnected:P.cdpConnected||!1,daemonId:t})),T=d.filter(P=>P.daemonId===t&&Qs(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,cliName:P.cliName||P.type,status:P.status,workspace:P.workspace||"",activeChat:P.activeChat||null,providerSessionId:P.providerSessionId,mode:P.mode,runtimeKey:P.runtimeKey,runtimeDisplayName:P.runtimeDisplayName,runtimeWorkspaceLabel:P.runtimeWorkspaceLabel,runtimeWriteOwner:P.runtimeWriteOwner||null,runtimeAttachedClients:P.runtimeAttachedClients||[],daemonId:t})),L=d.filter(P=>P.daemonId===t&&ys(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,acpName:P.cliName||P.type,status:P.status,workspace:P.workspace||"",activeChat:P.activeChat||null,providerSessionId:P.providerSessionId,daemonId:t})),Y=u?At(u,{fallbackId:t}):"",O="workspace",D=n.state,W=D==null?void 0:D.initialMachineTab,Q=D==null?void 0:D.initialWorkspaceCategory,be=D==null?void 0:D.initialWorkspaceId,pe=D==null?void 0:D.initialWorkspacePath,ue=W==="ides"||W==="clis"||W==="acps"?"workspace":W||O,we=W==="ides"?"ide":W==="clis"?"cli":W==="acps"?"acp":Q,ye=[...z.map(P=>{var G,U,de,Ne,_e;return{id:`ide:${P.type}:${P.workspace||""}`,label:((G=P.activeChat)==null?void 0:G.title)||P.type,kind:"ide",providerType:P.type,subtitle:P.workspace||void 0,workspace:P.workspace||void 0,lastLaunchedAt:((_e=(Ne=(de=(U=P.activeChat)==null?void 0:U.messages)==null?void 0:de.at)==null?void 0:Ne.call(de,-1))==null?void 0:_e.timestamp)||0}}),...T.map(P=>{var G,U,de,Ne,_e;return{id:`cli:${P.type}:${P.workspace||""}`,label:((G=P.activeChat)==null?void 0:G.title)||P.cliName,kind:"cli",providerType:P.type,providerSessionId:P.providerSessionId,subtitle:P.workspace||void 0,workspace:P.workspace||void 0,lastLaunchedAt:((_e=(Ne=(de=(U=P.activeChat)==null?void 0:U.messages)==null?void 0:de.at)==null?void 0:Ne.call(de,-1))==null?void 0:_e.timestamp)||0}}),...L.map(P=>{var G,U,de,Ne,_e;return{id:`acp:${P.type}:${P.workspace||""}`,label:((G=P.activeChat)==null?void 0:G.title)||P.acpName,kind:"acp",providerType:P.type,providerSessionId:P.providerSessionId,subtitle:ds(P.summaryMetadata)||P.workspace||void 0,workspace:P.workspace||void 0,lastLaunchedAt:((_e=(Ne=(de=(U=P.activeChat)==null?void 0:U.messages)==null?void 0:de.at)==null?void 0:Ne.call(de,-1))==null?void 0:_e.timestamp)||0}})].sort((P,G)=>(G.lastLaunchedAt||0)-(P.lastLaunchedAt||0)),ve=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(P=>({id:P.id,label:P.title||P.providerName||P.providerType,kind:P.kind,providerType:P.providerType,providerSessionId:P.providerSessionId,subtitle:ds(P.summaryMetadata)||P.workspace||void 0,workspace:P.workspace,summaryMetadata:P.summaryMetadata,lastLaunchedAt:P.lastLaunchedAt})):ye,V=o.useMemo(()=>{var G;const P=((G=l.connectionStates)==null?void 0:G[t||""])||void 0;return d.filter(U=>U.daemonId===t&&U.type!=="adhdev-daemon").flatMap(U=>Ba(U,{connectionStates:t&&P?{[t]:P}:void 0,defaultConnectionState:P})).filter(U=>!(U.transport==="pty"&&U.mode==="terminal")).sort((U,de)=>ea(de)-ea(U))},[d,l.connectionStates,t]),H=o.useCallback(P=>{const G=Ia(P);G&&r(Gt(G))},[r]),Z=o.useCallback(()=>{h.current&&(k(!0),h.current().finally(()=>{h.current=null,k(!1),b(null)}))},[]),me=o.useCallback(P=>{if(!K)return;const{options:G,selectedKey:U}=os({machine:K,currentWorkspacePath:P.workspace}),de=async()=>{p(P.kind),v("workspace")};h.current=async()=>{const Ne=G.find(Be=>Be.key===N.current),_e=(Ne==null?void 0:Ne.workspacePath)??null,ge=(Ne==null?void 0:Ne.workspaceId)??null;if(P.kind==="ide"&&P.providerType){await E.handleLaunchIde(P.providerType,_e?{workspace:_e}:void 0);return}if((P.kind==="cli"||P.kind==="acp")&&P.providerType){await E.runLaunchCliCore({cliType:P.providerType,dir:ge?void 0:_e||"",workspaceId:ge||void 0,model:P.kind==="acp"&&qi(P.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:P.providerSessionId});return}await de()},N.current=U,y(U),b({title:P.kind==="ide"?ss("restart-ide",P.label):P.providerSessionId?Da(P.label):ss("start-fresh",P.label),description:P.kind==="ide"?rs("restart-ide"):P.providerSessionId?Ea():rs("start-fresh"),confirmLabel:P.kind==="ide"?Is("restart-ide"):P.providerSessionId?Ur(!0):Is("start-fresh"),busyLabel:P.kind==="ide"?Ms("restart-ide"):P.providerSessionId?Pa(!0):Ms("start-fresh"),workspaceOptions:G,details:[{label:"Mode",value:P.kind.toUpperCase()},...P.providerType?[{label:"Provider",value:P.providerType}]:[]]})},[E,K]);if(o.useEffect(()=>{v(ue)},[O,ue,t]),o.useEffect(()=>{we&&p(we)},[we,t]),!K)return f?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:g,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 ne=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Nt,{size:14})," Workspace"]}),count:z.length+T.length+L.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ls,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Yr,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Bd,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Dd,{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:g,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[E.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:E.nicknameInput,onChange:P=>E.setNicknameInput(P.target.value),onKeyDown:P=>{P.key==="Enter"&&E.handleSaveNickname(),P.key==="Escape"&&E.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:E.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),s.jsx("button",{onClick:()=>E.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{E.setEditingNickname(!0),E.setNicknameInput(K.machineNickname||"")},title:"Click to set nickname",children:Y}),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:[K.platform," · ",K.arch]}),s.jsxs("span",{children:[K.cpus," cores"]}),(u==null?void 0:u.version)&&s.jsxs("span",{children:["v",u.version]}),K.p2p.available&&s.jsxs("span",{children:["P2P ",K.p2p.state==="connected"?"connected":K.p2p.state]}),K.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:K.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ne.map(P=>s.jsxs("button",{onClick:()=>v(P.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${m===P.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[P.label,P.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${m===P.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:P.count})]},P.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:[m==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(mb,{machineEntry:u,providers:M,recentLaunches:ve,currentConversations:V,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",{})}catch{}},onOpenRecent:me,onOpenConversation:H}),s.jsx(hb,{machine:K,machineId:t,providers:M,ideSessions:z,cliSessions:T,acpSessions:L,actions:E,getIcon:R,initialCategory:S,initialWorkspaceId:be,initialWorkspacePath:pe,sendDaemonCommand:a})]}),m==="providers"&&s.jsx(zx,{machineId:t,providers:M,sendDaemonCommand:a}),m==="overview"&&s.jsx(Bx,{machineId:t,machine:K,ideSessions:z,cliSessions:T,acpSessions:L,actions:E,sendDaemonCommand:a}),m==="session-host"&&s.jsx(db,{machineId:t,cliSessions:T,sendDaemonCommand:a}),m==="logs"&&s.jsx(rb,{machineId:t,sendDaemonCommand:a})]})})}),E.launchPick&&K&&s.jsx(ub,{machine:K,launchPick:E.launchPick,actions:E}),j&&s.jsx(Ga,{title:j.title,description:j.description,details:j.details,workspaceOptions:j.workspaceOptions,selectedWorkspaceKey:A,onWorkspaceChange:P=>{N.current=P,y(P)},confirmLabel:j.confirmLabel,busyLabel:j.busyLabel,busy:I,onConfirm:Z,onCancel:()=>{h.current=null,b(null)}}),s.jsx(Sc,{toasts:l.toasts||[],onDismiss:P=>l.setToasts(G=>G.filter(U=>U.id!==P)),onClickToast:P=>{P.targetKey&&r(Gt(P.targetKey))}}),s.jsx("style",{children:`
71
+ The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){c("session_host_prune_duplicate_sessions");try{const C=await r(e,"session_host_prune_duplicate_sessions",{}),R=$n(C);if(!(R!=null&&R.success))throw new Error((R==null?void 0:R.error)||"Duplicate prune failed");const K=R.result||{},z=Array.isArray(K.prunedSessionIds)?K.prunedSessionIds.length:0,T=typeof K.duplicateGroupCount=="number"?K.duplicateGroupCount:0;lt.showToast(`Pruned ${z} duplicate runtime(s) across ${T} group(s)`,"success"),await p()}catch(C){const R=C instanceof Error?C.message:"Duplicate prune failed";lt.showToast(R,"warning"),a(R)}finally{c(C=>C==="session_host_prune_duplicate_sessions"?null:C)}}},[e,p,r]),b=o.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((M,C)=>(C.lastActivityAt||0)-(M.lastActivityAt||0)),[u==null?void 0:u.sessions]),N=o.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:ab(b),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,b]),A=N.liveRuntimes,y=N.recoverySnapshots,I=N.inactiveRecords,k=o.useMemo(()=>lb(A),[A]),w=o.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),g=o.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(M=>M.level==="warn"||M.level==="error")||null,[u==null?void 0:u.recentLogs]),E=(M,C)=>{var W;const R=i===`session_host_resume_session:${M.sessionId}`,K=i===`session_host_restart_session:${M.sessionId}`,z=i===`session_host_stop_session:${M.sessionId}`,T=wl(M.meta),L=S.get(M.sessionId),Y=M.attachedClients.length===1?"1 client":`${M.attachedClients.length} clients`,O=C==="recovery"?"Recover":"Resume",D=ob(C);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:M.displayName||(L==null?void 0:L.cliName)||M.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${cb(M.lifecycle)}`,children:M.lifecycle}),T&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:T})]}),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:M.workspaceLabel||(L==null?void 0:L.runtimeWorkspaceLabel)||M.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:M.runtimeKey}),M.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",M.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((W=M.writeOwner)==null?void 0:W.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:ib(M.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(Ti,{size:11})," ",Y]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",fi(M.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",D]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[C==="recovery"&&(M.lifecycle==="interrupted"||M.lifecycle==="failed"||M.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{h("session_host_resume_session",M)},children:R?`${O}ing…`:O}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{h("session_host_restart_session",M)},children:K?"Restarting…":"Restart"}),C==="live"&&(M.lifecycle==="running"||M.lifecycle==="starting"||M.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:!!i,onClick:()=>{h("session_host_stop_session",M)},children:z?"Stopping…":"Stop"})]})]})},M.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(ls,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Nf()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[k>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{j()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${k})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${v.toneClass}`,children:v.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:x||l,children:[s.jsx(sr,{size:13}),x||l?"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(Xs,{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:y.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:fi(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Bn(u.hostStartedAt)})]})]}),g&&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(Xs,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:g.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Bn(g.timestamp),g.sessionId?` · ${g.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(ga,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:En("live")}),A.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:A.map(M=>E(M,"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(ls,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:En("recovery")}),y.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:y.map(M=>E(M,"recovery"))})]}),I.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:En("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:I.map(M=>E(M,"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"}),w.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:w.map(M=>{var R;const C=b.find(K=>K.sessionId===M.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:(C==null?void 0:C.displayName)||((R=S.get(M.sessionId))==null?void 0:R.cliName)||M.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[M.action,M.lifecycle?` · ${M.lifecycle}`:"",M.detail?` · ${M.detail}`:"",M.error?` · ${M.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${M.success===!1?"text-red-300":"text-text-secondary"}`,children:Bn(M.timestamp)})]},`${M.sessionId}:${M.timestamp}:${M.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 ub({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(i=>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:i.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.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 Kn({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 On({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 mb({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),d=r.slice(0,4),u=zs(e,"0.9.27");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:[l.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Kn,{icon:s.jsx(Ut,{size:13}),children:"Current Chats"}),s.jsx(On,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(x=>{const m=ea(x);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>c(x),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:nt(x)}),m>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Jr(m)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:us(x)})]},x.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Kn,{icon:s.jsx(Di,{size:13}),children:"Recent Launches"}),s.jsx(On,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(x=>{const{metaText:m,updatedLabel:v}=tl(x);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>i(x),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:x.label}),v&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:v})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:m})]},x.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Kn,{icon:s.jsx(Xs,{size:13}),children:"Daemon Update"}),s.jsx(On,{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:u?"Daemon update required":"Version mismatch detected"}),s.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:u?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),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(sr,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function fb(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const pb={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 Ir(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Wn({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:d,initialWorkspacePath:f}){const u=As(),{handleLaunchIde:x,handleStopCli:m,handleRestartIde:v,handleStopIde:S,handleDetectIdes:p,launchingIde:h,launchingAgentType:j,addLog:b}=c,[N,A]=o.useState(null),y=o.useCallback(_=>{_&&u(Gt(_))},[u]),I=pb[e],k=e==="ide",w=e==="acp",g=o.useMemo(()=>n.filter(_=>_.category===e&&(e==="ide"||_.installed!==!1)),[e,n]),E=o.useMemo(()=>new Map(g.map(_=>[_.type,_.displayName||_.type])),[g]),[M,C]=o.useState(""),[R,K]=o.useState(""),[z,T]=o.useState([]),[L,Y]=o.useState(""),[O,D]=o.useState(""),[W,Q]=o.useState([]),[be,pe]=o.useState(!1),[ue,we]=o.useState(!1),[ye,ve]=o.useState(""),[V,H]=o.useState(!1),[Z,me]=o.useState(()=>ht()),[ne,fe]=o.useState(null),[se,xe]=o.useState(f?"__custom__":d||t.defaultWorkspaceId||""),[ie,ce]=o.useState(f||""),[ae,X]=o.useState([]),[J,oe]=o.useState(!1),[P,G]=o.useState(""),[U,de]=o.useState([]),[Ne,_e]=o.useState(!1),[ge,Be]=o.useState(""),Oe=o.useRef(null),[Ke,et]=o.useState(null),Je=o.useRef("__home__"),[at,dt]=o.useState("__home__"),[mt,ot]=o.useState(!1),ut=o.useRef(0),Ie=ae.filter(_=>!a.some(te=>te.type===_&&bt(te.status)!=="stopped")),$e=o.useRef({});o.useEffect(()=>{t.defaultWorkspaceId&&!se&&xe(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),o.useEffect(()=>{if(f){xe("__custom__"),ce(f);return}d&&(xe(d),ce(""))},[d,f]),o.useEffect(()=>{k||M&&(g.some(_=>_.type===M)||(C(""),D("")))},[g,k,M]);const Ue=(()=>{if(se==="__custom__")return ie.trim();if(!se)return"";const _=(t.workspaces||[]).find(te=>te.id===se);return(_==null?void 0:_.path)||""})(),Ve=o.useCallback(_=>{const te=$e.current[_];te&&(clearTimeout(te),delete $e.current[_]),X(he=>he.includes(_)?he.filter(Re=>Re!==_):he)},[]),qe=o.useRef(new Set),Qe=o.useCallback(async _=>{if(l){_e(!0),Be("");try{const te=await rn(l,r,_);G(te.path),ce(te.path),de(te.directories)}catch(te){Be(te instanceof Error?te.message:"Could not load folder")}finally{_e(!1)}}},[r,l]),ee=o.useCallback(()=>{if(!l)return;xe("__custom__"),oe(!0);const _=a.map(he=>he.workspace),te=sn(t.platform,tn(ie.trim(),Ue,f,_,t.defaultWorkspacePath,(t.workspaces||[]).map(he=>he.path)));Qe(te)},[ie,f,Qe,t.defaultWorkspacePath,t.platform,t.workspaces,a,Ue,l]),Le=o.useCallback(_=>{const te=String(_.workspace||"").trim();if(!te)return;const he=(t.workspaces||[]).find(Re=>Ir(Re.path)===Ir(te));if(he){xe(he.id),ce("");return}xe("__custom__"),ce(te)},[t.workspaces]),De=o.useCallback(_=>{const te=String(_.workspace||"").trim();if(!te)return{workspaceId:null,workspacePath:"",useHome:!0};const he=(t.workspaces||[]).find(Re=>Ir(Re.path)===Ir(te));return he?{workspaceId:he.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:te,useHome:!1}},[t.workspaces]),rt=o.useCallback(async _=>{if(!l||!_||e!=="cli"){Q([]),pe(!1),we(!1),ve("");return}const te=ut.current+1;ut.current=te,pe(!0),ve("");try{const he=await l(r,"list_saved_sessions",{providerType:_,kind:"cli",limit:30});if(ut.current!==te)return;const Re=(he==null?void 0:he.result)??he;Q(Array.isArray(Re==null?void 0:Re.sessions)?Re.sessions:[])}catch(he){if(ut.current!==te)return;Q([]),ve(he instanceof Error?he.message:"Could not load saved sessions")}finally{ut.current===te&&(pe(!1),we(!0))}},[e,r,l]),Ct=o.useMemo(()=>{if(e!=="cli"||!M)return null;const _=E.get(M)||M;return{routeId:r,daemonId:r,providerSessionId:O||void 0,transport:"pty",mode:"chat",agentName:_,agentType:M,status:"idle",title:_,messages:[],ideType:M,workspaceName:Ue,displayPrimary:_,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${M}`}},[e,r,E,Ue,O,M]),ft=o.useCallback(_=>{if(e==="ide"||!_){T([]);return}T(pl(r,_))},[e,r]);o.useEffect(()=>{ut.current+=1,D(""),ft(M),we(!1),Q([]),ve(""),pe(!1)},[e,ft,rt,M]);const Tt=o.useMemo(()=>W.find(_=>_.providerSessionId===O)||null,[W,O]);o.useEffect(()=>{if(!O)return;const _=W.find(te=>te.providerSessionId===O);_!=null&&_.canResume||D("")},[W,O]);const yt=o.useCallback((_,te)=>{Oe.current=te,Je.current=_.selectedWorkspaceKey||"__home__",dt(_.selectedWorkspaceKey||"__home__"),et(_)},[]),B=o.useCallback(()=>{Oe.current&&(ot(!0),Oe.current().finally(()=>{Oe.current=null,ot(!1),et(null)}))},[]),$=o.useCallback(_=>{if(!_)return;X(he=>he.includes(_)?he:[...he,_]);const te=$e.current[_];te&&clearTimeout(te),$e.current[_]=setTimeout(()=>{X(he=>he.includes(_)?he.filter(Re=>Re!==_):he),delete $e.current[_]},2e4)},[]);o.useEffect(()=>{for(const te of a)bt(te.status)!=="stopped"&&(ae.includes(te.type)&&!qe.current.has(te.type)&&(qe.current.add(te.type),b("info",`${E.get(te.type)||te.type} launched`,!0)),Ve(te.type));const _=new Set(a.filter(te=>bt(te.status)!=="stopped").map(te=>te.type));qe.current.forEach(te=>{!ae.includes(te)&&!_.has(te)&&qe.current.delete(te)})},[b,Ve,a,ae,E]),o.useEffect(()=>()=>{Object.values($e.current).forEach(clearTimeout),$e.current={}},[]);const[F,q]=o.useState({}),[le,ke]=o.useState(null);o.useEffect(()=>{if(!k||!r||!l)return;(async()=>{try{const te=await l(r,"get_ide_extensions",{}),he=(te==null?void 0:te.result)||te;he!=null&&he.success&&(he!=null&&he.ideExtensions)&&q(he.ideExtensions)}catch{}})()},[k,r,l]);const Me=_=>k?st(_.type):e==="cli"?_.cliName:_.acpName,Ce=k?t.detectedIdes||[]:[],re=o.useCallback(async _=>{const te=(_==null?void 0:_.type)||M,he=(_==null?void 0:_.workspacePath)??Ue;if(k){await x(te,he?{workspace:he}:void 0)&&$(te);return}const Re=await c.runLaunchCliCore({cliType:te,dir:_!=null&&_.workspaceId?void 0:he||void 0,workspaceId:(_==null?void 0:_.workspaceId)||void 0,useHome:(_==null?void 0:_.useHome)||!(_!=null&&_.workspaceId)&&!he,argsStr:(_==null?void 0:_.argsStr)??(R||void 0),model:(_==null?void 0:_.model)??(w&&L||void 0),resumeSessionId:(_==null?void 0:_.resumeSessionId)||!w&&e==="cli"&&te===M&&O||void 0});if(Re.success||Re.pending){const Se=(_==null?void 0:_.argsStr)??R;!k&&(Se!=null&&Se.trim())&&(hl(r,te,Se),ft(te)),$(te),Re.success&&Re.sessionId&&y(Re.sessionId)}},[c,x,w,k,R,L,ft,$,r,y,Ue,O,M]),je=jc(k?"ide":w?"acp":"cli",!k&&!w&&!!O),We=kc(k?"ide":w?"acp":"cli",!k&&!w&&!!O),Fe=()=>{var Se;const _=k?st(M):E.get(M)||M,te=!k&&!w&&!!O,{options:he,selectedKey:Re}=os({machine:t,currentWorkspaceId:se&&se!=="__custom__"?se:null,currentWorkspacePath:Ue});yt({title:te?Da(_):ss("start-fresh",_),description:te?Ea():rs("start-fresh"),confirmLabel:je,busyLabel:We,workspaceOptions:he,selectedWorkspaceKey:Re,details:[{label:"Mode",value:I.label},{label:"Provider",value:_},...!k&&e==="cli"&&O?[{label:"Resume",value:((Se=W.find(Ae=>Ae.providerSessionId===O))==null?void 0:Se.title)||O}]:[],...!k&&R.trim()?[{label:"Arguments",value:R.trim()}]:[],...w&&L.trim()?[{label:"Model",value:L.trim()}]:[]]},async()=>{const Ae=he.find(Te=>Te.key===Je.current);Ae!=null&&Ae.workspaceId?(xe(Ae.workspaceId),ce("")):Ae!=null&&Ae.workspacePath?(xe("__custom__"),ce(Ae.workspacePath)):(xe(""),ce("")),await re({workspaceId:(Ae==null?void 0:Ae.workspaceId)??null,workspacePath:(Ae==null?void 0:Ae.workspacePath)??"",useHome:!(Ae!=null&&Ae.workspaceId)&&!(Ae!=null&&Ae.workspacePath)})})},Ye=_=>{k?S(_):m(_.type,_.workspace,_.id)},ze=o.useCallback(async(_,te,he=!1)=>{if(_.mode===te){he&&_.sessionId&&y(_.sessionId);return}if(!l||!_.sessionId){he&&_.sessionId&&y(_.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:_.sessionId,cliType:_.type,mode:te}),he&&y(_.sessionId)}catch(Re){const Se=Fc(Re);Hc(Re)?console.warn(Se?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Re instanceof Error?Re.message:String(Re)):console.error("Failed to switch CLI view mode:",Re)}},[r,y,l]),Pe=s.jsxs("div",{className:"mb-3",children:[s.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[s.jsx("select",{value:se,onChange:_=>{const te=_.target.value;if(xe(te),te==="__custom__"&&l){ee();return}te!=="__custom__"&&ce("")},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:(t.workspaces||[]).length>0?s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(t.workspaces||[]).map(_=>s.jsxs("option",{value:_.id,children:[_.id===t.defaultWorkspaceId?"⭐ ":"",Zr(_.path,_.label)]},_.id)),s.jsx("option",{value:"__custom__",children:l?"📁 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:l?"📁 Select workspace…":"✏️ Custom path…"})]})}),se==="__custom__"&&(l?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:ee,children:"Select workspace…"}):s.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:ie,onChange:_=>ce(_.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:se==="__custom__"?Ue?s.jsx("span",{className:"font-mono truncate block",title:Ue,children:Ue}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":Ue?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:se===t.defaultWorkspaceId?"Default workspace":"Selected workspace"}),s.jsx("span",{className:"font-mono truncate block",title:Ue,children:Ue})]}):"No workspace selected. This launches in the home directory."})]});return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${I.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 ",I.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:k?Ce.length>0?Ce.map(_=>{const te=a.find(Te=>(Te.type||"").toLowerCase()===(_.type||"").toLowerCase()&&bt(Te.status)!=="stopped"),he=_.running||!!te,Re=!!te&&te.cdpConnected,Se=ae.includes(_.type||_.id||""),Ae=M===(_.type||"");return s.jsxs("button",{onClick:()=>{if(Re&&te){const Te=te.sessionId;Te?u(Gt(Te),{state:{openRemoteForTabKey:Te}}):u("/dashboard",{state:{openRemoteForTabKey:te.id}});return}Se||C(Te=>Te===(_.type||"")?"":_.type||"")},disabled:!!h||Se,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Re?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Ae?"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:h&&h!==_.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:i(_.type)}),he&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Re?"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||st(_.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Re?"text-green-400":Se?"text-orange-400":Ae?"text-accent-primary":"text-text-muted"}`,children:Re?"Open Session":Se?"Starting...":Ae?"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:p,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($d,{size:14})," Scan System"]})]}):g.length>0?g.map(_=>{const te=M===_.type,he=ae.includes(_.type),Se=!!a.find(Ae=>Ae.type===_.type&&bt(Ae.status)!=="stopped");return s.jsxs("button",{onClick:()=>C(Ae=>Ae===_.type?"":_.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${te?"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}),Se&&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 ${he?"text-orange-400":te?"text-accent-primary":"text-text-muted"}`,children:he?"Starting...":te?"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."})]})}),M&&(k?Ce.find(_=>_.type===M):g.find(_=>_.type===M))&&s.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[s.jsx("span",{children:"Launch Settings"}),s.jsx("span",{className:"text-accent-primary font-bold",children:k?st(M):E.get(M)||M})]}),Pe,!k&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!w&&e==="cli"&&s.jsx(bl,{busy:!!j||!!h||ae.includes(M),savedSessionsLoading:be,savedSessionsError:ye,selectedSession:Tt,onRefresh:()=>void rt(M),onOpenHistory:()=>{M&&(H(!0),xl({hasLoadedInitialResults:ue,isLoading:be})&&rt(M))},onClearSelection:()=>D("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[w&&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:L,onChange:_=>Y(_.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:R,onChange:_=>K(_.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),z.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:z.map(_=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>K(_),title:_,children:_},_))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:Fe,disabled:!!j||!!h||ae.includes(M),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:j===M||h===M?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+ae.filter(_=>!a.some(te=>te.type===_&&bt(te.status)!=="stopped")).length,")"]}),a.length===0&&Ie.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 ",I.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Ie.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:i(_)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:k?st(_):E.get(_)||_}),s.jsx("div",{className:"text-[11px] text-text-muted",children:j===_?"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 te=k?_:null,he=!k&&!w?_:null,Re=bt(_.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:i(_.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Me(_),(te==null?void 0:te.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",te.version]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[s.jsx("span",{children:_.workspace||"—"}),(he==null?void 0:he.mode)&&s.jsx("span",{className:he.mode==="chat"?"text-violet-400":"text-text-secondary",children:he.mode==="chat"?"Chat view":"Terminal view"})]}),he&&(he.runtimeKey||he.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[he.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 ",he.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 Se;(Se=navigator.clipboard)==null||Se.writeText(`adhdev attach ${he.runtimeKey}`),A(he.runtimeKey||null),window.setTimeout(()=>{A(Ae=>Ae===he.runtimeKey?null:Ae)},1200)},children:N===he.runtimeKey?"Copied":"Copy"})]}),he.runtimeWriteOwner&&s.jsx("span",{style:{color:he.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:he.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:fb(he.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 ${Re==="stopped"?"bg-red-500/[0.08] text-red-500":Re==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Re}),k&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const Se=_.sessionId;if(Se){u(Gt(Se),{state:{openRemoteForTabKey:Se}});return}u("/dashboard",{state:{openRemoteForTabKey:_.id}})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-primary transition-colors cursor-pointer",title:"Open remote control",children:s.jsx(Nt,{size:13})}),s.jsx("button",{onClick:()=>{const Se=_.workspace||"",{options:Ae,selectedKey:Te}=os({machine:t,currentWorkspacePath:Se});yt({title:ss("restart-ide",st(_.type)),description:rs("restart-ide"),confirmLabel:Is("restart-ide"),busyLabel:Ms("restart-ide"),workspaceOptions:Ae,selectedWorkspaceKey:Te,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:st(_.type)}]},async()=>{const pt=Ae.find(Ot=>Ot.key===Je.current),ct=(pt==null?void 0:pt.workspacePath)??"";if(ct&&ct!==Se){await re({type:_.type,workspacePath:ct});return}await v(_)})},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(sr,{size:14})})]}),w&&s.jsx("button",{onClick:()=>{const Se=_.sessionId;Se&&y(Se)},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(Ut,{size:14})}),he&&Re!=="stopped"&&s.jsxs(s.Fragment,{children:[he.mode&&s.jsx(Ra,{mode:he.mode,onChange:Se=>void ze(he,Se,!1),compact:!0}),s.jsx("button",{onClick:()=>{const Se=_.sessionId;Se&&y(Se)},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:he.mode==="chat"?s.jsx(Ut,{size:14}):s.jsx(Nt,{size:13})})]}),Re==="stopped"?s.jsx("button",{onClick:()=>{const Se=_.workspace||"",Ae=k?st(_.type):Me(_),{options:Te,selectedKey:pt}=os({machine:t,currentWorkspacePath:Se});yt({title:ss("restart-stopped",Ae),description:rs("restart-stopped"),confirmLabel:Is("restart-stopped"),busyLabel:Ms("restart-stopped"),workspaceOptions:Te,selectedWorkspaceKey:pt,details:[{label:"Mode",value:I.label},{label:"Provider",value:Ae}]},async()=>{const ct=Te.find(Ot=>Ot.key===Je.current);await re({type:_.type,workspaceId:(ct==null?void 0:ct.workspaceId)??null,workspacePath:(ct==null?void 0:ct.workspacePath)??"",useHome:!(ct!=null&&ct.workspaceId)&&!(ct!=null&&ct.workspacePath)})})},disabled:ae.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:ae.includes(_.type)?"⏳":s.jsx(ya,{size:14})}):s.jsx("button",{onClick:()=>Ye(_),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(vt,{size:14})})]})]}),te&&te.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:te.aiAgents.map(Se=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${zi(Se.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Se.name," · ",bt(Se.status)]},Se.id))}),te&&(F[te.type]||[]).length>0&&l&&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:(F[te.type]||[]).map(Se=>s.jsxs("button",{disabled:le===`${te.type}.${Se.type}`,onClick:async()=>{const Ae=`${te.type}.${Se.type}`;ke(Ae);try{await l(r,"set_ide_extension",{ideType:te.type,extensionType:Se.type,enabled:!Se.enabled}),q(Te=>({...Te,[te.type]:(Te[te.type]||[]).map(pt=>pt.type===Se.type?{...pt,enabled:!pt.enabled}:pt)}))}catch(Te){console.error("Extension toggle failed:",Te)}finally{ke(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 ${Se.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 ${Se.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Se.name,s.jsx("span",{className:"text-[9px] font-normal",children:Se.enabled?"ON":"OFF"})]},Se.type))})]})]},_.id)})]}),J&&l&&s.jsx(an,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:P,directories:U,busy:Ne,error:ge,confirmLabel:"Use this folder",onClose:()=>oe(!1),onNavigate:_=>{Qe(_)},onConfirm:_=>{ce(_),xe("__custom__"),oe(!1)}}),Ke&&s.jsx(Ga,{title:Ke.title,description:Ke.description,details:Ke.details,workspaceOptions:Ke.workspaceOptions,selectedWorkspaceKey:at,onWorkspaceChange:_=>{Je.current=_,dt(_)},confirmLabel:Ke.confirmLabel,busyLabel:Ke.busyLabel,busy:mt,onConfirm:B,onCancel:()=>{Oe.current=null,et(null)}}),V&&Ct&&s.jsx($a,{activeConv:Ct,ides:[],isCreatingChat:!1,isRefreshingHistory:be,savedSessions:W,isSavedSessionsLoading:be,isResumingSavedSessionId:ne,savedHistoryFilters:Z,onSavedHistoryFiltersChange:me,onClose:()=>H(!1),onNewChat:()=>{D(""),H(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{rt(M)},onResumeSavedSession:_=>{if(!_.canResume||ne)return;const te=De(_);D(_.providerSessionId),Le(_),fe(_.providerSessionId),H(!1),re({type:_.providerType,workspaceId:te.workspaceId,workspacePath:te.workspacePath,useHome:te.useHome,resumeSessionId:_.providerSessionId}).finally(()=>{fe(he=>he===_.providerSessionId?null:he)})}})]})}const pi=[{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 hb({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:d="ide",initialWorkspaceId:f,initialWorkspacePath:u,sendDaemonCommand:x}){var p;const[m,v]=o.useState(d);o.useEffect(()=>{v(d)},[d]);const S=o.useMemo(()=>({ide:n.length,cli:a.length,acp:i.length}),[n.length,a.length,i.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:pi.map(h=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${m===h.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>v(h.id),children:[s.jsx("span",{children:h.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${m===h.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:S[h.id]})]},h.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(p=pi.find(h=>h.id===m))==null?void 0:p.helper})]}),m==="ide"&&s.jsx(Wn,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:x,initialWorkspaceId:f,initialWorkspacePath:u}),m==="cli"&&s.jsx(Wn,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:x,initialWorkspaceId:f,initialWorkspacePath:u}),m==="acp"&&s.jsx(Wn,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:x,initialWorkspaceId:f,initialWorkspacePath:u})]})}function xb({onNicknameSynced:e}={}){var fe,se,xe,ie,ce,ae,X,J,oe;const{id:t}=id(),r=As(),n=pa(),{sendCommand:a}=wt(),i=ar(),c=Bc(),l=pc(),d=l.ides||[],f=l.initialLoaded??!0,u=d.find(P=>P.id===t&&P.type==="adhdev-daemon"),x=d.some(P=>P.type==="adhdev-daemon"),[m,v]=o.useState("workspace"),[S,p]=o.useState("ide"),h=o.useRef(null),[j,b]=o.useState(null),N=o.useRef("__home__"),[A,y]=o.useState("__home__"),[I,k]=o.useState(!1),w=o.useRef(null);o.useEffect(()=>{!t||!u||!(!u.workspaces||!u.availableProviders||!u.detectedIdes||!u.recentLaunches)||i(t,{minFreshMs:3e4}).catch(()=>{})},[i,u,t]),o.useEffect(()=>{if(!t||!u||m!=="overview")return;const P=u.machine;(typeof(P==null?void 0:P.cpus)!="number"||typeof(P==null?void 0:P.totalMem)!="number"||typeof(P==null?void 0:P.arch)!="string"||typeof(P==null?void 0:P.release)!="string")&&c(t,{minFreshMs:3e4}).catch(()=>{})},[m,c,u,t]),gp(t&&m==="overview"?[t]:[],{enabled:m==="overview",intervalMs:Im});const g=()=>{if(x){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},E=$x({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:w});o.useEffect(()=>lt.onToast(G=>{l.setToasts(de=>{if(de.some(ge=>ge.message===G.message&&G.timestamp-ge.timestamp<3e3))return de;const _e={id:G.id,message:G.message,type:G.type,timestamp:G.timestamp,targetKey:G.targetKey,actions:G.actions};return[...de.slice(-4),_e]});const U=G.duration||5e3;setTimeout(()=>l.setToasts(de=>de.filter(Ne=>Ne.id!==G.id)),U)}),[l]);const M=(u==null?void 0:u.availableProviders)||[],C={};for(const P of M)C[P.type]=P.icon;const R=P=>C[P]||"",K=u?{id:u.id,hostname:Vi(u,{fallbackId:u.id}),platform:((fe=u.machine)==null?void 0:fe.platform)||"unknown",arch:((se=u.machine)==null?void 0:se.arch)||"",cpus:((xe=u.machine)==null?void 0:xe.cpus)||0,totalMem:((ie=u.machine)==null?void 0:ie.totalMem)||0,freeMem:(ce=u.machine)==null?void 0:ce.freeMem,availableMem:(ae=u.machine)==null?void 0:ae.availableMem,loadavg:(X=u.machine)==null?void 0:X.loadavg,uptime:(J=u.machine)==null?void 0:J.uptime,release:((oe=u.machine)==null?void 0:oe.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,z=d.filter(P=>P.daemonId===t&&P.type!=="adhdev-daemon").filter(P=>!Qs(P)&&!ys(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,version:P.version||"",instanceId:P.instanceId||"",status:P.status,workspace:P.workspace||null,terminals:P.terminals||0,aiAgents:Ru(P.aiAgents||(P.agents||[]).map(G=>({id:G.name,name:G.name,status:G.status,version:G.version}))),activeChat:P.activeChat||null,chats:P.chats||[],childSessions:P.childSessions||[],cdpConnected:P.cdpConnected||!1,daemonId:t})),T=d.filter(P=>P.daemonId===t&&Qs(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,cliName:P.cliName||P.type,status:P.status,workspace:P.workspace||"",activeChat:P.activeChat||null,providerSessionId:P.providerSessionId,mode:P.mode,runtimeKey:P.runtimeKey,runtimeDisplayName:P.runtimeDisplayName,runtimeWorkspaceLabel:P.runtimeWorkspaceLabel,runtimeWriteOwner:P.runtimeWriteOwner||null,runtimeAttachedClients:P.runtimeAttachedClients||[],daemonId:t})),L=d.filter(P=>P.daemonId===t&&ys(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,acpName:P.cliName||P.type,status:P.status,workspace:P.workspace||"",activeChat:P.activeChat||null,providerSessionId:P.providerSessionId,daemonId:t})),Y=u?At(u,{fallbackId:t}):"",O="workspace",D=n.state,W=D==null?void 0:D.initialMachineTab,Q=D==null?void 0:D.initialWorkspaceCategory,be=D==null?void 0:D.initialWorkspaceId,pe=D==null?void 0:D.initialWorkspacePath,ue=W==="ides"||W==="clis"||W==="acps"?"workspace":W||O,we=W==="ides"?"ide":W==="clis"?"cli":W==="acps"?"acp":Q,ye=[...z.map(P=>{var G,U,de,Ne,_e;return{id:`ide:${P.type}:${P.workspace||""}`,label:((G=P.activeChat)==null?void 0:G.title)||P.type,kind:"ide",providerType:P.type,subtitle:P.workspace||void 0,workspace:P.workspace||void 0,lastLaunchedAt:((_e=(Ne=(de=(U=P.activeChat)==null?void 0:U.messages)==null?void 0:de.at)==null?void 0:Ne.call(de,-1))==null?void 0:_e.timestamp)||0}}),...T.map(P=>{var G,U,de,Ne,_e;return{id:`cli:${P.type}:${P.workspace||""}`,label:((G=P.activeChat)==null?void 0:G.title)||P.cliName,kind:"cli",providerType:P.type,providerSessionId:P.providerSessionId,subtitle:P.workspace||void 0,workspace:P.workspace||void 0,lastLaunchedAt:((_e=(Ne=(de=(U=P.activeChat)==null?void 0:U.messages)==null?void 0:de.at)==null?void 0:Ne.call(de,-1))==null?void 0:_e.timestamp)||0}}),...L.map(P=>{var G,U,de,Ne,_e;return{id:`acp:${P.type}:${P.workspace||""}`,label:((G=P.activeChat)==null?void 0:G.title)||P.acpName,kind:"acp",providerType:P.type,providerSessionId:P.providerSessionId,subtitle:ds(P.summaryMetadata)||P.workspace||void 0,workspace:P.workspace||void 0,lastLaunchedAt:((_e=(Ne=(de=(U=P.activeChat)==null?void 0:U.messages)==null?void 0:de.at)==null?void 0:Ne.call(de,-1))==null?void 0:_e.timestamp)||0}})].sort((P,G)=>(G.lastLaunchedAt||0)-(P.lastLaunchedAt||0)),ve=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(P=>({id:P.id,label:P.title||P.providerName||P.providerType,kind:P.kind,providerType:P.providerType,providerSessionId:P.providerSessionId,subtitle:ds(P.summaryMetadata)||P.workspace||void 0,workspace:P.workspace,summaryMetadata:P.summaryMetadata,lastLaunchedAt:P.lastLaunchedAt})):ye,V=o.useMemo(()=>{var G;const P=((G=l.connectionStates)==null?void 0:G[t||""])||void 0;return d.filter(U=>U.daemonId===t&&U.type!=="adhdev-daemon").flatMap(U=>Ba(U,{connectionStates:t&&P?{[t]:P}:void 0,defaultConnectionState:P})).filter(U=>!(U.transport==="pty"&&U.mode==="terminal")).sort((U,de)=>ea(de)-ea(U))},[d,l.connectionStates,t]),H=o.useCallback(P=>{const G=Ia(P);G&&r(Gt(G))},[r]),Z=o.useCallback(()=>{h.current&&(k(!0),h.current().finally(()=>{h.current=null,k(!1),b(null)}))},[]),me=o.useCallback(P=>{if(!K)return;const{options:G,selectedKey:U}=os({machine:K,currentWorkspacePath:P.workspace}),de=async()=>{p(P.kind),v("workspace")};h.current=async()=>{const Ne=G.find(Be=>Be.key===N.current),_e=(Ne==null?void 0:Ne.workspacePath)??null,ge=(Ne==null?void 0:Ne.workspaceId)??null;if(P.kind==="ide"&&P.providerType){await E.handleLaunchIde(P.providerType,_e?{workspace:_e}:void 0);return}if((P.kind==="cli"||P.kind==="acp")&&P.providerType){await E.runLaunchCliCore({cliType:P.providerType,dir:ge?void 0:_e||"",workspaceId:ge||void 0,model:P.kind==="acp"&&qi(P.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:P.providerSessionId});return}await de()},N.current=U,y(U),b({title:P.kind==="ide"?ss("restart-ide",P.label):P.providerSessionId?Da(P.label):ss("start-fresh",P.label),description:P.kind==="ide"?rs("restart-ide"):P.providerSessionId?Ea():rs("start-fresh"),confirmLabel:P.kind==="ide"?Is("restart-ide"):P.providerSessionId?Ur(!0):Is("start-fresh"),busyLabel:P.kind==="ide"?Ms("restart-ide"):P.providerSessionId?Pa(!0):Ms("start-fresh"),workspaceOptions:G,details:[{label:"Mode",value:P.kind.toUpperCase()},...P.providerType?[{label:"Provider",value:P.providerType}]:[]]})},[E,K]);if(o.useEffect(()=>{v(ue)},[O,ue,t]),o.useEffect(()=>{we&&p(we)},[we,t]),!K)return f?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:g,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 ne=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Nt,{size:14})," Workspace"]}),count:z.length+T.length+L.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ls,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Yr,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Bd,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Dd,{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:g,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[E.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:E.nicknameInput,onChange:P=>E.setNicknameInput(P.target.value),onKeyDown:P=>{P.key==="Enter"&&E.handleSaveNickname(),P.key==="Escape"&&E.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:E.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),s.jsx("button",{onClick:()=>E.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{E.setEditingNickname(!0),E.setNicknameInput(K.machineNickname||"")},title:"Click to set nickname",children:Y}),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:[K.platform," · ",K.arch]}),s.jsxs("span",{children:[K.cpus," cores"]}),(u==null?void 0:u.version)&&s.jsxs("span",{children:["v",u.version]}),K.p2p.available&&s.jsxs("span",{children:["P2P ",K.p2p.state==="connected"?"connected":K.p2p.state]}),K.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:K.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ne.map(P=>s.jsxs("button",{onClick:()=>v(P.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${m===P.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[P.label,P.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${m===P.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:P.count})]},P.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:[m==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(mb,{machineEntry:u,providers:M,recentLaunches:ve,currentConversations:V,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",{})}catch{}},onOpenRecent:me,onOpenConversation:H}),s.jsx(hb,{machine:K,machineId:t,providers:M,ideSessions:z,cliSessions:T,acpSessions:L,actions:E,getIcon:R,initialCategory:S,initialWorkspaceId:be,initialWorkspacePath:pe,sendDaemonCommand:a})]}),m==="providers"&&s.jsx(zx,{machineId:t,providers:M,sendDaemonCommand:a}),m==="overview"&&s.jsx(Bx,{machineId:t,machine:K,ideSessions:z,cliSessions:T,acpSessions:L,actions:E,sendDaemonCommand:a}),m==="session-host"&&s.jsx(db,{machineId:t,cliSessions:T,sendDaemonCommand:a}),m==="logs"&&s.jsx(rb,{machineId:t,sendDaemonCommand:a})]})})}),E.launchPick&&K&&s.jsx(ub,{machine:K,launchPick:E.launchPick,actions:E}),j&&s.jsx(Ga,{title:j.title,description:j.description,details:j.details,workspaceOptions:j.workspaceOptions,selectedWorkspaceKey:A,onWorkspaceChange:P=>{N.current=P,y(P)},confirmLabel:j.confirmLabel,busyLabel:j.busyLabel,busy:I,onConfirm:Z,onCancel:()=>{h.current=null,b(null)}}),s.jsx(Sc,{toasts:l.toasts||[],onDismiss:P=>l.setToasts(G=>G.filter(U=>U.id!==P)),onClickToast:P=>{P.targetKey&&r(Gt(P.targetKey))}}),s.jsx("style",{children:`
72
72
  @keyframes toast-in {
73
73
  from { opacity: 0; transform: translateX(40px); }
74
74
  to { opacity: 1; transform: translateX(0); }
75
75
  }
76
- `})]})}function Xa(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function bb(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=Xa();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 Et(e,t){return await fetch(bb(e),{credentials:"same-origin",...t})}function jl(){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 gb{constructor(){Ge(this,"adapters",new Map);Ge(this,"states",new Map);Ge(this,"runtimeListeners",new Map);Ge(this,"screenshotCallbacks",new Map);Ge(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,i,c){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:i,rows:c})}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){if(!r)return{success:!1,error:"sessionId is required"};const n=await Et(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`);if(!n.ok){let i=`Runtime snapshot unavailable (${n.status})`;try{const c=await n.json();c!=null&&c.error&&(i=c.error)}catch{}return{success:!1,error:i}}const a=await n.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof a.seq=="number"?a.seq:0,text:typeof a.text=="string"?a.text:"",truncated:!!a.truncated,cols:typeof a.cols=="number"?a.cols:void 0,rows:typeof a.rows=="number"?a.rows:void 0}),{success:!0}}emitRuntimeEvent(t,r){var n;(n=this.runtimeListeners.get(t))==null||n.forEach(a=>a(r))}}const Wt=new gb;function yb(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=Xa();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Mr=yb(),hi=3e3,vb=3e4;let Rt=null,wb=0;const qr=new Map;let Jt=null,Gs=null;function xi(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Ks(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function jb(e){return e==="connected"?"connected":e}async function Er(e,t,r){const n=Ic(e,r||{}),a=Rt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++wb}_${Date.now()}`;return new Promise((c,l)=>{const d=setTimeout(()=>{qr.delete(i),l(new Error(`WS command timeout: ${t}`))},3e4);qr.set(i,{resolve:f=>{clearTimeout(d),c(f)},reject:f=>{clearTimeout(d),l(f)}}),a.send(JSON.stringify({type:"command",requestId:i,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function da(e,t){const r=Rt;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 kb(e,t,r){const n=Rt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=Ic(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 Sb{constructor(t){Ge(this,"daemonId");Ge(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN}get connectionState(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return Er(this.daemonId,t,r)}async sendInput(t,r){return Er(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Jt&&(clearInterval(Jt),Jt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Er(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const a=await fetch(`data:image/jpeg;base64,${n.base64}`).then(i=>i.blob());Wt.emitScreenshot(this.daemonId,a)}}catch{}};r(),Jt=setInterval(r,2e3)}stopScreenshots(t){Jt&&(clearInterval(Jt),Jt=null)}}let Mt=null;function Nb(e){return(!Mt||Mt.daemonId!==e)&&(Mt=new Sb(e)),Mt}function Cb({children:e}){const t=o.useRef(Ys()),r=Ys();t.current=r;const{setUserName:n}=cs(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),d=o.useCallback((p,h)=>{l(p),Gs==null||Gs(p,h)},[]),f=o.useRef(null),u=o.useRef(),x=o.useRef(hi),m=o.useRef(!0),v=o.useRef(!1),S=o.useRef("initial_connect");return o.useEffect(()=>{m.current=!0,v.current=!1;function p(){var b,N;if(!m.current||((b=f.current)==null?void 0:b.readyState)===WebSocket.OPEN||((N=f.current)==null?void 0:N.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Mr}...`),Ks("connect_attempt",{url:Mr,reason:S.current,delayMs:x.current});let j;try{j=new WebSocket(Mr)}catch(A){console.error("[Standalone WS] Failed to create WebSocket:",A),h();return}f.current=j,j.onopen=()=>{if(!m.current){j.close();return}d("connected"),x.current=hi,Ks("open",{url:Mr,reason:S.current}),qt.resubscribeAll({sendData:da}),console.log("[Standalone WS] Connected")},Rt=j,j.onmessage=A=>{var y,I;try{const k=JSON.parse(A.data);if((k.type==="command_result"||k.type==="error")&&k.requestId){const w=qr.get(k.requestId);w&&(qr.delete(k.requestId),k.type==="error"?w.reject(new Error(((y=k.data)==null?void 0:y.message)||"Command failed")):w.resolve(k.data));return}if(k.type==="session_output"){const w=k.sessionId||k.cliId||k.cliType;w&&Wt.emitSessionOutput(w,typeof k.data=="string"?k.data:"",typeof k.seq=="number"?k.seq:void 0);return}if(k.type==="runtime_snapshot"){Wt.emitRuntimeSnapshot(k.sessionId,typeof k.text=="string"?k.text:"",typeof k.seq=="number"?k.seq:0,!!k.truncated,typeof k.cols=="number"?k.cols:void 0,typeof k.rows=="number"?k.rows:void 0);return}if(k.type==="topic_update"){const w=k.update;w&&qt.publish(w);return}if(k.type==="status"||k.type==="initial_state"){const w=k.data;if(!w)return;const{injectEntries:g,markLoaded:E,getIdes:M}=t.current,C=w.instanceId||"standalone",R=M().find(T=>T.id===C),K=Nb(C);Wt.register(C,K),Wt.setState(C,"connected"),d("connected",C),Wt.emitStatus(C,w);const z=Fr(w,{daemonId:C,existingDaemon:R,existingEntries:M()});xi("ws_status",{type:k.type,daemonId:C,sessions:(w.sessions||[]).map(T=>({id:T.id,parentId:T.parentId,providerType:T.providerType,kind:T.kind,transport:T.transport,unread:T.unread,inboxBucket:T.inboxBucket,lastSeenAt:T.lastSeenAt,lastUpdated:T.lastUpdated,title:T.title})),recentLaunches:(w.recentLaunches||[]).map(T=>({id:T.id,providerType:T.providerType,kind:T.kind,workspace:T.workspace,lastLaunchedAt:T.lastLaunchedAt}))}),xi("entries",{daemonId:C,entries:z.filter(T=>T.type!=="adhdev-daemon").map(T=>({id:T.id,type:T.type,unread:T.unread,inboxBucket:T.inboxBucket,lastSeenAt:T.lastSeenAt,lastUpdated:T.lastUpdated,sessionId:T.sessionId}))}),z.length>0&&g(z,{authoritativeDaemonIds:[C]}),E(),c.current!==C&&((I=i.current)==null||I.call(i),c.current=C,i.current=qt.subscribe({sendData:da},C,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${C}`,params:{includeSessions:!0}},T=>{if(T.topic!=="daemon.metadata")return;const L=t.current.getIdes(),Y=L.find(D=>D.id===C),O=Fr(T.status,{daemonId:C,existingDaemon:Y,existingEntries:L,timestamp:T.timestamp});O.length>0&&t.current.injectEntries(O,{authoritativeDaemonIds:[C]}),T.userName&&a.current&&a.current(T.userName)}))}}catch(k){console.error("[Standalone WS] Parse error:",k)}},j.onclose=A=>{m.current&&(Mt==null||Mt.stopScreenshots(),Mt&&Wt.setState(Mt.daemonId,"disconnected"),d("disconnected"),f.current=null,S.current=`close:${A.code}${A.wasClean?":clean":":unclean"}`,Ks("close",{code:A.code,reason:A.reason||"",wasClean:A.wasClean}),h())},j.onerror=A=>{v.current||!m.current||(S.current="error",Ks("error",{message:A instanceof Event?"event":String(A),readyState:j.readyState}),console.warn("[Standalone WS] Error, will reconnect:",A))}}function h(){if(!m.current)return;clearTimeout(u.current);const j=x.current;console.log(`[Standalone WS] Reconnecting in ${j}ms...`),Ks("schedule_reconnect",{reason:S.current,delayMs:j}),u.current=setTimeout(()=>{x.current=Math.min(x.current*1.5,vb),p()},j)}return p(),()=>{var j;m.current=!1,v.current=!0,(j=i.current)==null||j.call(i),i.current=null,c.current=null,clearTimeout(u.current),f.current&&(f.current.onerror=null,f.current.onclose=null,f.current.close(),f.current=null,Rt=null),Mt&&(Mt.stopScreenshots(),Wt.unregister(Mt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function Ib({children:e}){const[t,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(Gs=(c,l)=>{r(c),l&&a(l)},()=>{Gs=null}),[]);const i=o.useMemo(()=>{const c=t==="connected",l=jb(t),d={};return n&&(d[n]=l),d.standalone=l,{wsStatus:t,isConnected:c,connectionStates:d}},[t,n]);return s.jsx(Nd,{connectionOverrides:i,children:s.jsx(Cb,{children:e})})}const kl="adhdev_standalone_font_preferences",is={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},ln=[{id:"default",label:"Default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS font-family stack"}],tr=[{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"}],Mb=new Set(ln.map(e=>e.id)),Ab=new Set(tr.map(e=>e.id));function Bt(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:$r("chat",t.chat),code:$r("code",t.code),terminal:$r("terminal",t.terminal)}}function $r(e,t){const r=is[e],n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof n.preset=="string"?n.preset.trim():"",i=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?Mb:Ab).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:a}:r}function Br(e,t){var a;const r=$r(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?ln:tr;return((a=n.find(i=>i.id===r.preset))==null?void 0:a.family)||n[0].family}function Tb(e){const t=Bt(e),r=Br("chat",t.chat),n=Br("code",t.code),a=Br("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Zt(e,t=document.documentElement){const r=Bt(e),n=Tb(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))t.style.setProperty(a,i);return r}function ua(e){const t=Bt(e);try{localStorage.setItem(kl,JSON.stringify(t))}catch{}return t}function Lb(){try{const e=localStorage.getItem(kl);if(e)return Bt(JSON.parse(e))}catch{}return is}function Rb(){return Zt(Lb())}function Os(e,t){var n;const r=e==="chat"?ln:tr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const Pb=[{id:"dashboard",path:"/dashboard",icon:s.jsx(Ai,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(ls,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:s.jsx(Yr,{}),label:"Settings"}];function _b({children:e}){const t=As(),r=pa(),n=o.useMemo(()=>Pb.map(i=>({...i,active:r.pathname.startsWith(i.path),onSelect:()=>t(i.path)})),[r.pathname,t]),a=o.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(Li,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Ri,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(Uf,{brand:({collapsed:i})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&s.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:a,footerInfo:({collapsed:i})=>i?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.26"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>s.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:i?"Expand sidebar":"Collapse sidebar",children:[s.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&s.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const Db=[{icon:s.jsx(ls,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Ut,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Pi,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(Nt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Js,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Li,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Eb=[{icon:s.jsx(Od,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Ai,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Xr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(_d,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Ti,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Ed,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],$b=[{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 Bb(){return s.jsxs(Lc,{icon:s.jsx(Ri,{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.26"]}),children:[s.jsx(St,{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(St,{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:Db.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(St,{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:Mc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Tc.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Ac.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(St,{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:Eb.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(St,{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:$b.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(Pc,{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(Xd,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Hn(e,t,r){return{...e,[t]:r}}function Fn({surface:e,title:t,description:r,value:n,options:a,onChange:i}){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:c=>{const l=c.target.value;i(l==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:l})},children:a.map(c=>s.jsx("option",{value:c.id,children:c.label},c.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:c=>i({preset:"custom",customFamily:c.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:Br(e,n)})]})]})]})}function Kb({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:i,onSave:c,onResetToSaved:l,onResetToDefaults:d}){const f=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(Fn,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:ln,onChange:u=>i(Hn(e,"chat",u))}),s.jsx(Fn,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:tr,onChange:u=>i(Hn(e,"code",u))}),s.jsx(Fn,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:tr,onChange:u=>i(Hn(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: ",Os("chat",e.chat.preset)," · Code: ",Os("code",e.code.preset)," · Terminal: ",Os("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Os("chat",is.chat.preset)," / ",Os("code",is.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:c,disabled:r||!f,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),s.jsx("button",{type:"button",onClick:l,disabled:r||!f,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert to saved"}),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 Ob(){const{ides:e}=cs(),t=e.find(V=>V.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=wt(),{userName:a}=cs(),[i,c]=o.useState(a||""),[l,d]=o.useState(null),[f,u]=o.useState(null),[x,m]=o.useState(is),[v,S]=o.useState(!1),[p,h]=o.useState(""),[j,b]=o.useState(""),[N,A]=o.useState("127.0.0.1"),[y,I]=o.useState(""),[k,w]=o.useState(""),[g,E]=o.useState(""),[M,C]=o.useState(""),[R,K]=o.useState(""),[z,T]=o.useState(!1),L=async()=>{const H=await(await Et("/auth/session")).json();d(H)},Y=async()=>{const H=await(await Et("/api/v1/standalone/preferences")).json();u(H),A(H.standaloneBindHost);const Z=Bt(H.standaloneFontPreferences);m(Z),Zt(Z),ua(Z)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([L(),Y()]).catch(V=>{C(V instanceof Error?V.message:String(V))})},[]),o.useEffect(()=>{Zt(x)},[x]);const O=V=>{const H=V.target.value.trim();t!=null&&t.id&&H!==a&&n(t.id,"set_user_name",{userName:H}).catch(console.error)},[D,W]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),Q=V=>{W(V);try{localStorage.setItem("adhdev_sound",V?"1":"0")}catch{}},be=async()=>{h(""),b(""),S(!0);try{const V=Bt(x),H=await Et("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:V})}),Z=await H.json();if(!H.ok)throw new Error((Z==null?void 0:Z.error)||"Failed to save standalone font preferences");const me=Bt(Z.standaloneFontPreferences);u(Z),m(me),Zt(me),ua(me),b("Standalone chat fonts saved for this self-hosted dashboard.")}catch(V){h(V instanceof Error?V.message:String(V))}finally{S(!1)}},pe=()=>{const V=Bt(f==null?void 0:f.standaloneFontPreferences);h(""),b(""),m(V),Zt(V)},ue=()=>{h(""),b(""),m(is),Zt(is)},we=async()=>{C(""),K(""),T(!0);try{const V=await Et("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:N})}),H=await V.json();if(!V.ok)throw new Error((H==null?void 0:H.error)||"Failed to save standalone network preference");u(H),A(H.standaloneBindHost),K(H.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(V){C(V instanceof Error?V.message:String(V))}finally{T(!1)}},ye=async()=>{if(C(""),K(""),k.trim().length<4){C("Password must be at least 4 characters.");return}if(k!==g){C("New password and confirmation do not match.");return}T(!0);try{const V=await Et("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,newPassword:k})}),H=await V.json();if(!V.ok)throw new Error((H==null?void 0:H.error)||"Failed to save password");d(H),await Y(),I(""),w(""),E(""),K(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),jl()}catch(V){C(V instanceof Error?V.message:String(V))}finally{T(!1)}},ve=async()=>{C(""),K(""),T(!0);try{const V=await Et("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,clear:!0})}),H=await V.json();if(!V.ok)throw new Error((H==null?void 0:H.error)||"Failed to clear password");d(H),await Y(),I(""),w(""),E(""),K("Standalone password disabled.")}catch(V){C(V instanceof Error?V.message:String(V))}finally{T(!1)}};return s.jsxs(Lc,{icon:s.jsx(Yr,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(gr,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint."}),(l==null?void 0:l.publicHostWarning)&&s.jsx(gr,{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(St,{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.26"]}),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:(f==null?void 0:f.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Default bind"}),s.jsx("span",{className:"font-mono text-xs",children:(f==null?void 0:f.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Auth"}),s.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),s.jsx(St,{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:N==="127.0.0.1",onChange:()=>A("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:N==="0.0.0.0",onChange:()=>A("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:()=>{we()},disabled:z,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:z?"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 ",(f==null?void 0:f.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),s.jsx(St,{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:l!=null&&l.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),M&&s.jsx(gr,{variant:"error",children:M}),R&&s.jsx(gr,{variant:"success",children:R}),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:l!=null&&l.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:y,onChange:V=>I(V.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:l!=null&&l.hasPasswordAuth?"New password":"New standalone password",value:k,onChange:V=>w(V.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:g,onChange:V=>E(V.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{ye()},disabled:z,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:z?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{ve()},disabled:z,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(St,{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(V=>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 ${V.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:V.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:V.type})]},V.type))})}),s.jsx(St,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(Zf,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(St,{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(rp,{})]}),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(up,{})]}),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(Kb,{value:x,savedValue:Bt(f==null?void 0:f.standaloneFontPreferences),saving:v,error:p,notice:j,onChange:m,onSave:()=>{be()},onResetToSaved:pe,onResetToDefaults:ue})]}),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(pp,{})]})]})}),s.jsx(St,{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(Xf,{}),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Yd,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:D,onChange:Q})]})}),s.jsx(St,{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(Pd,{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:i,onChange:V=>c(V.target.value),onBlur:O,onKeyDown:V=>{V.key==="Enter"&&V.currentTarget.blur()}})]})})})]})}Hf();lp();Rb();const Wb=Ci({baseUrl:"",getToken:Xa});function Hb({children:e}){const[t,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,d]=o.useState(""),[f,u]=o.useState(!1),x=async()=>{a(!0),d("");try{const S=await(await Et("/auth/session")).json();r(S)}catch(v){d(v instanceof Error?v.message:String(v))}finally{a(!1)}};o.useEffect(()=>{x()},[]),o.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let v=!1;return(async()=>{try{const S=await Et("/api/v1/standalone/preferences");if(!S.ok)return;const p=await S.json();if(v)return;const h=Bt(p.standaloneFontPreferences);Zt(h),ua(h)}catch{}})(),()=>{v=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const m=async v=>{v.preventDefault(),u(!0),d("");try{const S=await Et("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),p=await S.json();if(!S.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),c(""),jl()}catch(S){d(S instanceof Error?S.message:String(S))}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:m,children:[s.jsx("input",{type:"password",value:i,onChange:v=>c(v.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:f||!i,className:"rounded-lg bg-accent text-white px-3 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:f?"Signing in…":"Unlock dashboard"})]}):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."}),l&&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:l})]})}):s.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",l||"unknown error"]})}function bi(){const{ides:e,initialLoaded:t}=cs();if(!t)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?s.jsx(Vn,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Vn,{to:"/dashboard",replace:!0})}function Fb(){const e=o.useMemo(()=>({sendCommand:Er,sendData:da,sendPtyInput:kb}),[]);return s.jsx(cd,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Md,{client:Wb,children:s.jsx(Hb,{children:s.jsx(Ib,{children:s.jsx(Td,{value:e,children:s.jsx(_b,{children:s.jsxs(ld,{children:[s.jsx(Yt,{path:"/dashboard",element:s.jsx(Ex,{})}),s.jsx(Yt,{path:"/machine",element:s.jsx(bi,{})}),s.jsx(Yt,{path:"/machines/:id",element:s.jsx(xb,{})}),s.jsx(Yt,{path:"/machines",element:s.jsx(bi,{})}),s.jsx(Yt,{path:"/about",element:s.jsx(Bb,{})}),s.jsx(Yt,{path:"/settings",element:s.jsx(Ob,{})}),s.jsx(Yt,{path:"*",element:s.jsx(Vn,{to:"/dashboard",replace:!0})})]})})})})})})})}of({connectionManager:Wt});dd(document.getElementById("root")).render(s.jsx(Fb,{}));
76
+ `})]})}function Xa(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function bb(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=Xa();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 Et(e,t){return await fetch(bb(e),{credentials:"same-origin",...t})}function jl(){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 gb{constructor(){Ge(this,"adapters",new Map);Ge(this,"states",new Map);Ge(this,"runtimeListeners",new Map);Ge(this,"screenshotCallbacks",new Map);Ge(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,i,c){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:i,rows:c})}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){if(!r)return{success:!1,error:"sessionId is required"};const n=await Et(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`);if(!n.ok){let i=`Runtime snapshot unavailable (${n.status})`;try{const c=await n.json();c!=null&&c.error&&(i=c.error)}catch{}return{success:!1,error:i}}const a=await n.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof a.seq=="number"?a.seq:0,text:typeof a.text=="string"?a.text:"",truncated:!!a.truncated,cols:typeof a.cols=="number"?a.cols:void 0,rows:typeof a.rows=="number"?a.rows:void 0}),{success:!0}}emitRuntimeEvent(t,r){var n;(n=this.runtimeListeners.get(t))==null||n.forEach(a=>a(r))}}const Wt=new gb;function yb(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=Xa();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Mr=yb(),hi=3e3,vb=3e4;let Rt=null,wb=0;const qr=new Map;let Jt=null,Gs=null;function xi(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Ks(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function jb(e){return e==="connected"?"connected":e}async function Er(e,t,r){const n=Ic(e,r||{}),a=Rt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++wb}_${Date.now()}`;return new Promise((c,l)=>{const d=setTimeout(()=>{qr.delete(i),l(new Error(`WS command timeout: ${t}`))},3e4);qr.set(i,{resolve:f=>{clearTimeout(d),c(f)},reject:f=>{clearTimeout(d),l(f)}}),a.send(JSON.stringify({type:"command",requestId:i,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function da(e,t){const r=Rt;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 kb(e,t,r){const n=Rt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=Ic(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 Sb{constructor(t){Ge(this,"daemonId");Ge(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN}get connectionState(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return Er(this.daemonId,t,r)}async sendInput(t,r){return Er(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Jt&&(clearInterval(Jt),Jt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Er(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const a=await fetch(`data:image/jpeg;base64,${n.base64}`).then(i=>i.blob());Wt.emitScreenshot(this.daemonId,a)}}catch{}};r(),Jt=setInterval(r,2e3)}stopScreenshots(t){Jt&&(clearInterval(Jt),Jt=null)}}let Mt=null;function Nb(e){return(!Mt||Mt.daemonId!==e)&&(Mt=new Sb(e)),Mt}function Cb({children:e}){const t=o.useRef(Ys()),r=Ys();t.current=r;const{setUserName:n}=cs(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),d=o.useCallback((p,h)=>{l(p),Gs==null||Gs(p,h)},[]),f=o.useRef(null),u=o.useRef(),x=o.useRef(hi),m=o.useRef(!0),v=o.useRef(!1),S=o.useRef("initial_connect");return o.useEffect(()=>{m.current=!0,v.current=!1;function p(){var b,N;if(!m.current||((b=f.current)==null?void 0:b.readyState)===WebSocket.OPEN||((N=f.current)==null?void 0:N.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Mr}...`),Ks("connect_attempt",{url:Mr,reason:S.current,delayMs:x.current});let j;try{j=new WebSocket(Mr)}catch(A){console.error("[Standalone WS] Failed to create WebSocket:",A),h();return}f.current=j,j.onopen=()=>{if(!m.current){j.close();return}d("connected"),x.current=hi,Ks("open",{url:Mr,reason:S.current}),qt.resubscribeAll({sendData:da}),console.log("[Standalone WS] Connected")},Rt=j,j.onmessage=A=>{var y,I;try{const k=JSON.parse(A.data);if((k.type==="command_result"||k.type==="error")&&k.requestId){const w=qr.get(k.requestId);w&&(qr.delete(k.requestId),k.type==="error"?w.reject(new Error(((y=k.data)==null?void 0:y.message)||"Command failed")):w.resolve(k.data));return}if(k.type==="session_output"){const w=k.sessionId||k.cliId||k.cliType;w&&Wt.emitSessionOutput(w,typeof k.data=="string"?k.data:"",typeof k.seq=="number"?k.seq:void 0);return}if(k.type==="runtime_snapshot"){Wt.emitRuntimeSnapshot(k.sessionId,typeof k.text=="string"?k.text:"",typeof k.seq=="number"?k.seq:0,!!k.truncated,typeof k.cols=="number"?k.cols:void 0,typeof k.rows=="number"?k.rows:void 0);return}if(k.type==="topic_update"){const w=k.update;w&&qt.publish(w);return}if(k.type==="status"||k.type==="initial_state"){const w=k.data;if(!w)return;const{injectEntries:g,markLoaded:E,getIdes:M}=t.current,C=w.instanceId||"standalone",R=M().find(T=>T.id===C),K=Nb(C);Wt.register(C,K),Wt.setState(C,"connected"),d("connected",C),Wt.emitStatus(C,w);const z=Fr(w,{daemonId:C,existingDaemon:R,existingEntries:M()});xi("ws_status",{type:k.type,daemonId:C,sessions:(w.sessions||[]).map(T=>({id:T.id,parentId:T.parentId,providerType:T.providerType,kind:T.kind,transport:T.transport,unread:T.unread,inboxBucket:T.inboxBucket,lastSeenAt:T.lastSeenAt,lastUpdated:T.lastUpdated,title:T.title})),recentLaunches:(w.recentLaunches||[]).map(T=>({id:T.id,providerType:T.providerType,kind:T.kind,workspace:T.workspace,lastLaunchedAt:T.lastLaunchedAt}))}),xi("entries",{daemonId:C,entries:z.filter(T=>T.type!=="adhdev-daemon").map(T=>({id:T.id,type:T.type,unread:T.unread,inboxBucket:T.inboxBucket,lastSeenAt:T.lastSeenAt,lastUpdated:T.lastUpdated,sessionId:T.sessionId}))}),z.length>0&&g(z,{authoritativeDaemonIds:[C]}),E(),c.current!==C&&((I=i.current)==null||I.call(i),c.current=C,i.current=qt.subscribe({sendData:da},C,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${C}`,params:{includeSessions:!0}},T=>{if(T.topic!=="daemon.metadata")return;const L=t.current.getIdes(),Y=L.find(D=>D.id===C),O=Fr(T.status,{daemonId:C,existingDaemon:Y,existingEntries:L,timestamp:T.timestamp});O.length>0&&t.current.injectEntries(O,{authoritativeDaemonIds:[C]}),T.userName&&a.current&&a.current(T.userName)}))}}catch(k){console.error("[Standalone WS] Parse error:",k)}},j.onclose=A=>{m.current&&(Mt==null||Mt.stopScreenshots(),Mt&&Wt.setState(Mt.daemonId,"disconnected"),d("disconnected"),f.current=null,S.current=`close:${A.code}${A.wasClean?":clean":":unclean"}`,Ks("close",{code:A.code,reason:A.reason||"",wasClean:A.wasClean}),h())},j.onerror=A=>{v.current||!m.current||(S.current="error",Ks("error",{message:A instanceof Event?"event":String(A),readyState:j.readyState}),console.warn("[Standalone WS] Error, will reconnect:",A))}}function h(){if(!m.current)return;clearTimeout(u.current);const j=x.current;console.log(`[Standalone WS] Reconnecting in ${j}ms...`),Ks("schedule_reconnect",{reason:S.current,delayMs:j}),u.current=setTimeout(()=>{x.current=Math.min(x.current*1.5,vb),p()},j)}return p(),()=>{var j;m.current=!1,v.current=!0,(j=i.current)==null||j.call(i),i.current=null,c.current=null,clearTimeout(u.current),f.current&&(f.current.onerror=null,f.current.onclose=null,f.current.close(),f.current=null,Rt=null),Mt&&(Mt.stopScreenshots(),Wt.unregister(Mt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function Ib({children:e}){const[t,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(Gs=(c,l)=>{r(c),l&&a(l)},()=>{Gs=null}),[]);const i=o.useMemo(()=>{const c=t==="connected",l=jb(t),d={};return n&&(d[n]=l),d.standalone=l,{wsStatus:t,isConnected:c,connectionStates:d}},[t,n]);return s.jsx(Nd,{connectionOverrides:i,children:s.jsx(Cb,{children:e})})}const kl="adhdev_standalone_font_preferences",is={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},ln=[{id:"default",label:"Default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS font-family stack"}],tr=[{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"}],Mb=new Set(ln.map(e=>e.id)),Ab=new Set(tr.map(e=>e.id));function Bt(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:$r("chat",t.chat),code:$r("code",t.code),terminal:$r("terminal",t.terminal)}}function $r(e,t){const r=is[e],n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof n.preset=="string"?n.preset.trim():"",i=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?Mb:Ab).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:a}:r}function Br(e,t){var a;const r=$r(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?ln:tr;return((a=n.find(i=>i.id===r.preset))==null?void 0:a.family)||n[0].family}function Tb(e){const t=Bt(e),r=Br("chat",t.chat),n=Br("code",t.code),a=Br("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Zt(e,t=document.documentElement){const r=Bt(e),n=Tb(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))t.style.setProperty(a,i);return r}function ua(e){const t=Bt(e);try{localStorage.setItem(kl,JSON.stringify(t))}catch{}return t}function Lb(){try{const e=localStorage.getItem(kl);if(e)return Bt(JSON.parse(e))}catch{}return is}function Rb(){return Zt(Lb())}function Os(e,t){var n;const r=e==="chat"?ln:tr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const Pb=[{id:"dashboard",path:"/dashboard",icon:s.jsx(Ai,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(ls,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:s.jsx(Yr,{}),label:"Settings"}];function _b({children:e}){const t=As(),r=pa(),n=o.useMemo(()=>Pb.map(i=>({...i,active:r.pathname.startsWith(i.path),onSelect:()=>t(i.path)})),[r.pathname,t]),a=o.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(Li,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Ri,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(Uf,{brand:({collapsed:i})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&s.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:a,footerInfo:({collapsed:i})=>i?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.27"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>s.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:i?"Expand sidebar":"Collapse sidebar",children:[s.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&s.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const Db=[{icon:s.jsx(ls,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Ut,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Pi,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(Nt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Js,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Li,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Eb=[{icon:s.jsx(Od,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Ai,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Xr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(_d,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Ti,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Ed,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],$b=[{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 Bb(){return s.jsxs(Lc,{icon:s.jsx(Ri,{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.27"]}),children:[s.jsx(St,{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(St,{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:Db.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(St,{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:Mc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Tc.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Ac.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(St,{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:Eb.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(St,{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:$b.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(Pc,{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(Xd,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Hn(e,t,r){return{...e,[t]:r}}function Fn({surface:e,title:t,description:r,value:n,options:a,onChange:i}){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:c=>{const l=c.target.value;i(l==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:l})},children:a.map(c=>s.jsx("option",{value:c.id,children:c.label},c.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:c=>i({preset:"custom",customFamily:c.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:Br(e,n)})]})]})]})}function Kb({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:i,onSave:c,onResetToSaved:l,onResetToDefaults:d}){const f=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(Fn,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:ln,onChange:u=>i(Hn(e,"chat",u))}),s.jsx(Fn,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:tr,onChange:u=>i(Hn(e,"code",u))}),s.jsx(Fn,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:tr,onChange:u=>i(Hn(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: ",Os("chat",e.chat.preset)," · Code: ",Os("code",e.code.preset)," · Terminal: ",Os("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Os("chat",is.chat.preset)," / ",Os("code",is.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:c,disabled:r||!f,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),s.jsx("button",{type:"button",onClick:l,disabled:r||!f,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert to saved"}),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 Ob(){const{ides:e}=cs(),t=e.find(V=>V.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=wt(),{userName:a}=cs(),[i,c]=o.useState(a||""),[l,d]=o.useState(null),[f,u]=o.useState(null),[x,m]=o.useState(is),[v,S]=o.useState(!1),[p,h]=o.useState(""),[j,b]=o.useState(""),[N,A]=o.useState("127.0.0.1"),[y,I]=o.useState(""),[k,w]=o.useState(""),[g,E]=o.useState(""),[M,C]=o.useState(""),[R,K]=o.useState(""),[z,T]=o.useState(!1),L=async()=>{const H=await(await Et("/auth/session")).json();d(H)},Y=async()=>{const H=await(await Et("/api/v1/standalone/preferences")).json();u(H),A(H.standaloneBindHost);const Z=Bt(H.standaloneFontPreferences);m(Z),Zt(Z),ua(Z)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([L(),Y()]).catch(V=>{C(V instanceof Error?V.message:String(V))})},[]),o.useEffect(()=>{Zt(x)},[x]);const O=V=>{const H=V.target.value.trim();t!=null&&t.id&&H!==a&&n(t.id,"set_user_name",{userName:H}).catch(console.error)},[D,W]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),Q=V=>{W(V);try{localStorage.setItem("adhdev_sound",V?"1":"0")}catch{}},be=async()=>{h(""),b(""),S(!0);try{const V=Bt(x),H=await Et("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:V})}),Z=await H.json();if(!H.ok)throw new Error((Z==null?void 0:Z.error)||"Failed to save standalone font preferences");const me=Bt(Z.standaloneFontPreferences);u(Z),m(me),Zt(me),ua(me),b("Standalone chat fonts saved for this self-hosted dashboard.")}catch(V){h(V instanceof Error?V.message:String(V))}finally{S(!1)}},pe=()=>{const V=Bt(f==null?void 0:f.standaloneFontPreferences);h(""),b(""),m(V),Zt(V)},ue=()=>{h(""),b(""),m(is),Zt(is)},we=async()=>{C(""),K(""),T(!0);try{const V=await Et("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:N})}),H=await V.json();if(!V.ok)throw new Error((H==null?void 0:H.error)||"Failed to save standalone network preference");u(H),A(H.standaloneBindHost),K(H.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(V){C(V instanceof Error?V.message:String(V))}finally{T(!1)}},ye=async()=>{if(C(""),K(""),k.trim().length<4){C("Password must be at least 4 characters.");return}if(k!==g){C("New password and confirmation do not match.");return}T(!0);try{const V=await Et("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,newPassword:k})}),H=await V.json();if(!V.ok)throw new Error((H==null?void 0:H.error)||"Failed to save password");d(H),await Y(),I(""),w(""),E(""),K(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),jl()}catch(V){C(V instanceof Error?V.message:String(V))}finally{T(!1)}},ve=async()=>{C(""),K(""),T(!0);try{const V=await Et("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,clear:!0})}),H=await V.json();if(!V.ok)throw new Error((H==null?void 0:H.error)||"Failed to clear password");d(H),await Y(),I(""),w(""),E(""),K("Standalone password disabled.")}catch(V){C(V instanceof Error?V.message:String(V))}finally{T(!1)}};return s.jsxs(Lc,{icon:s.jsx(Yr,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(gr,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint."}),(l==null?void 0:l.publicHostWarning)&&s.jsx(gr,{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(St,{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.27"]}),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:(f==null?void 0:f.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Default bind"}),s.jsx("span",{className:"font-mono text-xs",children:(f==null?void 0:f.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Auth"}),s.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),s.jsx(St,{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:N==="127.0.0.1",onChange:()=>A("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:N==="0.0.0.0",onChange:()=>A("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:()=>{we()},disabled:z,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:z?"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 ",(f==null?void 0:f.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),s.jsx(St,{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:l!=null&&l.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),M&&s.jsx(gr,{variant:"error",children:M}),R&&s.jsx(gr,{variant:"success",children:R}),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:l!=null&&l.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:y,onChange:V=>I(V.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:l!=null&&l.hasPasswordAuth?"New password":"New standalone password",value:k,onChange:V=>w(V.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:g,onChange:V=>E(V.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{ye()},disabled:z,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:z?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{ve()},disabled:z,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(St,{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(V=>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 ${V.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:V.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:V.type})]},V.type))})}),s.jsx(St,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(Zf,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(St,{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(rp,{})]}),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(up,{})]}),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(Kb,{value:x,savedValue:Bt(f==null?void 0:f.standaloneFontPreferences),saving:v,error:p,notice:j,onChange:m,onSave:()=>{be()},onResetToSaved:pe,onResetToDefaults:ue})]}),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(pp,{})]})]})}),s.jsx(St,{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(Xf,{}),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Yd,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:D,onChange:Q})]})}),s.jsx(St,{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(Pd,{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:i,onChange:V=>c(V.target.value),onBlur:O,onKeyDown:V=>{V.key==="Enter"&&V.currentTarget.blur()}})]})})})]})}Hf();lp();Rb();const Wb=Ci({baseUrl:"",getToken:Xa});function Hb({children:e}){const[t,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,d]=o.useState(""),[f,u]=o.useState(!1),x=async()=>{a(!0),d("");try{const S=await(await Et("/auth/session")).json();r(S)}catch(v){d(v instanceof Error?v.message:String(v))}finally{a(!1)}};o.useEffect(()=>{x()},[]),o.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let v=!1;return(async()=>{try{const S=await Et("/api/v1/standalone/preferences");if(!S.ok)return;const p=await S.json();if(v)return;const h=Bt(p.standaloneFontPreferences);Zt(h),ua(h)}catch{}})(),()=>{v=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const m=async v=>{v.preventDefault(),u(!0),d("");try{const S=await Et("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),p=await S.json();if(!S.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),c(""),jl()}catch(S){d(S instanceof Error?S.message:String(S))}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:m,children:[s.jsx("input",{type:"password",value:i,onChange:v=>c(v.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:f||!i,className:"rounded-lg bg-accent text-white px-3 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:f?"Signing in…":"Unlock dashboard"})]}):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."}),l&&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:l})]})}):s.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",l||"unknown error"]})}function bi(){const{ides:e,initialLoaded:t}=cs();if(!t)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?s.jsx(Vn,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Vn,{to:"/dashboard",replace:!0})}function Fb(){const e=o.useMemo(()=>({sendCommand:Er,sendData:da,sendPtyInput:kb}),[]);return s.jsx(cd,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Md,{client:Wb,children:s.jsx(Hb,{children:s.jsx(Ib,{children:s.jsx(Td,{value:e,children:s.jsx(_b,{children:s.jsxs(ld,{children:[s.jsx(Yt,{path:"/dashboard",element:s.jsx(Ex,{})}),s.jsx(Yt,{path:"/machine",element:s.jsx(bi,{})}),s.jsx(Yt,{path:"/machines/:id",element:s.jsx(xb,{})}),s.jsx(Yt,{path:"/machines",element:s.jsx(bi,{})}),s.jsx(Yt,{path:"/about",element:s.jsx(Bb,{})}),s.jsx(Yt,{path:"/settings",element:s.jsx(Ob,{})}),s.jsx(Yt,{path:"*",element:s.jsx(Vn,{to:"/dashboard",replace:!0})})]})})})})})})})}of({connectionManager:Wt});dd(document.getElementById("root")).render(s.jsx(Fb,{}));