@adhdev/daemon-standalone 0.9.31 → 0.9.33

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 ad=Object.defineProperty;var od=(e,t,r)=>t in e?ad(e,t,{enumerable:!0,config
28
28
 
29
29
  `)))return}const V=(c==null?void 0:c[T.id])??p[T.id];try{const E=await j(T.invokeScript),_=hr(E);if(_&&!_.ok||xr(E))throw new Error((_==null?void 0:_.error)||Ds(E)||`Could not run ${T.label}`);_&&g(T,V??!0,_)}catch(E){$(T,V);const _=E instanceof Error?E.message:`Could not run ${T.label}`;it.showToast(_,"warning")}};return s.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${f}33`,background:`${f}12`,color:f},children:a}),A.map(T=>{const V=String(x[T.id]||""),E=um(T,w,V),_=N===T.id,F=y===T.id,J=Lr(T,w),xe="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(T.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${xe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:_?`${f}55`:"var(--border-default)",background:_?`${f}10`:"var(--surface-tertiary)",color:V?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void L(T),title:T.label,children:[T.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:T.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:F?"Loading…":E||T.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),_&&J.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>I(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:T.label}),J.map(ce=>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:ce.value===V?`${f}14`:"transparent",color:ce.value===V?"var(--text-primary)":"var(--text-secondary)",borderLeft:ce.value===V?`2px solid ${f}`:"2px solid transparent"},title:ce.description||ce.label,onMouseEnter:te=>{te.currentTarget.style.background=`${f}10`},onMouseLeave:te=>{te.currentTarget.style.background=ce.value===V?`${f}14`:"transparent"},onClick:()=>void O(T,ce.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:ce.label}),ce.value===V&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:f},children:"✓"})]},ce.value))]})]})]},T.id);case"cycle":return s.jsxs("button",{type:"button",className:`${xe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:V?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void W(T),title:`Click to cycle: ${J.map(ce=>ce.label).join(" → ")}`,children:[T.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:T.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:E||T.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},T.id);case"toggle":return s.jsxs("button",{type:"button",className:`${xe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:V?`${f}44`:"var(--border-default)",background:V?`${f}14`:"var(--surface-tertiary)",color:V?f:"var(--text-muted)"},onClick:()=>void P(T),"aria-pressed":!!V,children:[T.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:T.icon}),T.label]},T.id);case"action":return s.jsxs("button",{type:"button",className:`${xe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void C(T),children:[T.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:T.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:T.resultDisplay==="inline"&&V?`${T.label}: ${V}`:T.label})]},T.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:V?"var(--text-primary)":"var(--text-muted)"},children:[T.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:T.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:V?`${T.label}: ${V}`:T.label})]},T.id);default:return null}})]})})}function pm({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:u}){const{isVisible:f}=Xi(),d=Na(l,{hostIdeType:a,providerType:i});return!e||t||d.length===0||!f?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx(fm,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:d,controlValues:u})})}function hm({hasDraft:e,isBusy:t=!1}){return!e||t}const nc=o.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:i=null,onSend:c,isActive:l=!0,showControlsToggle:u=!1,animateVisibility:f=!0}){const d=o.useRef(null),[h,m]=o.useState(""),{isVisible:v,toggleVisibility:k}=Xi();o.useEffect(()=>{m("")},[t]),o.useEffect(()=>{var x;l&&((x=d.current)==null||x.focus({preventScroll:!0}))},[t,l]);const p=async()=>{const x=h.trim();if(!x||a)return;await c(x)!==!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:[u&&s.jsx("button",{type:"button",onClick:k,"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:d,type:"text",placeholder:i||`Send message to ${r}...`,value:h,onChange:x=>m(x.target.value),onPaste:x=>{const w=x.clipboardData.getData("text");w&&m(b=>b+w),x.preventDefault()},onKeyDown:x=>{if(x.key==="Enter"){if(x.nativeEvent.isComposing){x.preventDefault();return}x.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:hm({hasDraft:!!h.trim(),isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${h.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:h.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:h.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})]})}),et=e=>e.transport==="pty",Rs=(e,t)=>et(e)?e.mode||"terminal":"chat",ac=(e,t)=>et(e)&&Rs(e)==="terminal",Je=e=>e.transport==="acp";function zt(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 oc(e){return e.machineName||""}function _s(e){return fs(e)}function Bt(e){return e.agentType||""}function Hr(e){return e.hostIdeType||""}function Ca(e){return e.displayPrimary||e.agentName||"Agent"}function ic(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function xm(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Mo(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 bm(e){return Mo(e==null?void 0:e.receivedAt)||Mo(e==null?void 0:e.timestamp)||0}function cc(e){const t=xm(e),r=Ss(t==null?void 0:t.content),n=bm(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 gm(e){return cc(e)||e.displaySecondary||""}function lc(e){return[e.displaySecondary,oc(e)].filter(Boolean)}function Cs(e){return e.agentName||st(Bt(e))}function ym(e){var t,r;if(!zt(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)||Bt(e))}function dc(e){return zt(e)?e.sessionId:e.nativeSessionId}function Ao(e){return zt(e)?"native":e.tabKey}function vm(e){return e.sessionId}function wm(e,t){if(t)return zt(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function jm(e,t){const r=Bt(e),n=zt(e),a=et(e)||Je(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:et(e),isAcp:Je(e),isCliTerminal:ac(e),providerType:r,displayLabel:i,targetEntry:wm(e,t)}}function bt(e){return(typeof e=="string"?e.trim():"")||void 0}function Wt(e,t){const r=bt(t);return r?`${e}:${r}`:void 0}function Ut(e,t,r){const n=Wt(t,r),a=bt(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 uc(e){return bt(e.providerSessionId)||bt(e.sessionId)||bt(e.tabKey)||bt(e.routeId)}function Ia(e){return gs([bt(e.providerSessionId),bt(e.sessionId)])}function ws(e){const t=[];return Ut(t,"provider",e.providerSessionId),Ut(t,"session",e.sessionId),Ut(t,"tab",e.tabKey),Ut(t,"route",e.routeId),gs(t)}function km(e){const t=[];return bt(e.providerSessionId)?(Ut(t,"provider",e.providerSessionId),gs(t)):bt(e.sessionId)?(Ut(t,"session",e.sessionId),gs(t)):bt(e.tabKey)?(Ut(t,"tab",e.tabKey),gs(t)):bt(e.routeId)?(Ut(t,"route",e.routeId),gs(t)):[]}function Ma(e){return Wt("provider",e.providerSessionId)||Wt("session",e.sessionId)||Wt("tab",e.tabKey)||Wt("route",e.routeId)||"unknown:"}function ar(e){return Ia(e)[0]}function Sm(e){const t=bt(e.providerSessionId),r=bt(e.sessionId),n=bt(e.tabKey),a=bt(e.routeId),i=[Wt("provider",t),Wt("session",r),Wt("tab",n),Wt("route",a)].filter(u=>typeof u=="string"),c=ws({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),l=Ma({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:uc({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:ar({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function ea(e,t){const r=Sm(e);return km(t).some(n=>r.lookupKeys.includes(n))}function To(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 Zt(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=To(t==null?void 0:t.receivedAt)||To(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function ta(e,t=0){return Zt(e)||e.lastUpdated||t||0}function mc(e){return Zt(e)||e.lastUpdated||0}function fc(e,t,r=mc){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 sa(e){var r;const t=xt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function Nm(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!sa(e)&&!e.title.trim()}function Cm(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(sa(r))-Number(sa(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:fc(t,r)})[0]||null}function Pt(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=Cm(a);return n?i&&Nm(n)?i:n:i||r[0]||null}function Vt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Aa(e){return ar(e)||e.tabKey||e.routeId||null}function pc(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=Pt(e.conversations,n)||e.conversations.find(i=>i.routeId===n);return a?Aa(a):null}function hc({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=Ts(),c=fs(e),l=oc(e),u=e.transport==="cdp-page"||e.transport==="cdp-webview",f=e.streamSource==="agent-stream"&&!!e.agentName,d=!f&&(e.transport==="pty"||e.transport==="acp"),h=Cs(e),m=ym(e),v=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),k=o.useCallback(()=>{if(r){r();return}const p=Aa(e);p&&i(Vt(p))},[e,i,r]);return s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[u&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:k,title:m,children:[s.jsx(St,{size:12}),s.jsx("span",{children:m})]}):s.jsxs("span",{className:"conversation-meta-chip",title:m,children:[s.jsx(St,{size:12}),s.jsx("span",{children:m})]})),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(Zs,{size:12}),s.jsx("span",{children:h})]}),d&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(Zs,{size:12}),s.jsx("span",{children:h})]}),l&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:v,title:l,children:[s.jsx(cs,{size:12}),s.jsx("span",{children:l})]}):s.jsxs("span",{className:"conversation-meta-chip",title:l,children:[s.jsx(cs,{size:12}),s.jsx("span",{children:l})]}))]})}function bn(e,t){return`${e}:${t}`}function Im(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Es(e,t){Im()&&console.debug(`[subscription-manager] ${e}`,t)}class Mm{constructor(){Ge(this,"active",new Map);Ge(this,"retryTimers",new Map)}subscribe(t,r,n,a,i){var d;const c=bn(n.topic,n.key),l=this.active.get(c);let u=!0;if(l)l.handlers.add(a),l.lastUpdate&&a(l.lastUpdate);else{const h={daemonId:r,request:n,handlers:new Set([a])};this.active.set(c,h),Es("subscribe",{daemonId:r,topic:n.topic,key:n.key}),u=((d=t.sendData)==null?void 0:d.call(t,r,n))??!1,!u&&(i!=null&&i.retryIntervalMs)&&this.scheduleRetry(c,t,i.retryIntervalMs)}const f=()=>{var v;this.clearRetry(c);const h=this.active.get(c);if(!h||(h.handlers.delete(a),h.handlers.size>0))return;this.active.delete(c);const m={type:"unsubscribe",topic:n.topic,key:n.key};Es("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(v=t.sendData)==null||v.call(t,r,m)};return f.initialSendAccepted=u,f}publish(t){const r=bn(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=bn(t,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(t){var r;Es("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);Es("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;Es("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 Gt=new Mm;function Am(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 Tm(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 Ur(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:i,timestamp:c}=t,l=c||e.timestamp||Date.now(),u=e.sessions||[],{topLevel:f,childrenByParent:d}=Tm(u),h=Am(i,n),m=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,v=f.filter(x=>x.kind==="workspace"&&x.transport==="cdp-page"),k=f.filter(x=>x.kind==="agent"&&x.transport==="pty"),p=f.filter(x=>x.kind==="agent"&&x.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},_sessionListAuthoritative:Array.isArray(e.sessions),cdpConnected:v.some(x=>!!x.cdpConnected)});for(const x of v){const w=h.get(x.id),b=Hs(x,w),N=(d.get(x.id)||[]).map(I=>Hs(I,h.get(I.id)));r.push({id:`${n}:ide:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(w==null?void 0:w.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,status:b.cdpConnected?"online":"detected",daemonId:n,instanceId:x.id,workspace:b.workspace,terminals:0,childSessions:N,agents:N.map(I=>({id:I.id,name:I.providerName||I.providerType,type:I.providerType,status:I.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 x of k){const w=h.get(x.id),b=Hs(x,w);r.push({id:`${n}:cli:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(w==null?void 0:w.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:x.id,cliName:b.providerName||b.providerType,mode:b.mode||(w==null?void 0:w.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 x of p){const w=h.get(x.id),b=Hs(x,w);r.push({id:`${n}:acp:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(w==null?void 0:w.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:x.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 Lm=15e3,Rm=15e3,_m=6e4,Pm=1200,Lo=12,Dm=8e3,Em=4e3,gn=new Map,yn=new Map,br=new Set,Vs=new Map;function $m(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 Ro(e,t){const r=Vs.get(e);!r||r.size===0||(Vs.delete(e),r.forEach(n=>n(t)))}function Bm(e,t){return new Promise(r=>{const n=Vs.get(e)||new Set;Vs.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&Vs.delete(e),r(c)},i=setTimeout(()=>a(!1),t);n.add(a)})}function or(){const{sendCommand:e,sendData:t}=vt(),{injectEntries:r,getIdes:n}=Js();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??_m,l=yn.get(a)||0;if(!(i!=null&&i.force)&&br.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const u=gn.get(a);if(u)return u;const f=(async()=>{if(t&&!br.has(a)){const p=Gt.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},x=>{const w=n(),b=w.find(I=>I.id===a),N=Ur(x.status,{daemonId:a,existingDaemon:b,existingEntries:w,timestamp:x.timestamp});N.length>0&&r(N),yn.set(a,Date.now()),Ro(a,!0)});if(p.initialSendAccepted?br.add(a):br.delete(a),!(i!=null&&i.force)&&p.initialSendAccepted&&await Bm(a,Pm))return}const d=await e(a,"get_status_metadata"),h=$m(d);if(!h)return;const m=n(),v=m.find(p=>p.id===a),k=Ur(h,{daemonId:a,existingDaemon:v,existingEntries:m,timestamp:h.timestamp||Date.now()});k.length>0&&r(k,{authoritativeDaemonIds:[a]}),yn.set(a,Date.now()),Ro(a,!0)})().finally(()=>{gn.delete(a)});return gn.set(a,f),f},[n,r,e,t])}function Ta(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:et(e)||Je(e)?{agentType:Bt(e)}:e.streamSource==="agent-stream"?{agentType:Bt(e)}:t}function tr(e){return e?_s(e):""}function $s(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function La(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function Km(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 Om=60,Wm=1e3;function xc(e={}){return e.isCliLike?Wm:Om}function Fm(e={}){return xc(e)}const ir=60,Hm=1e3,Ra=12e4,Um=new Set(["generating","waiting_approval","starting","streaming","working"]),_o=new Map;function _a(e,t){return`${e}::${t}`}function ra(e=ir){return{liveMessages:[],cursor:bc([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function na(e){return Pi(e)}function bc(e,t=ir){return{knownMessageCount:e.length,lastMessageSignature:na(e[e.length-1]),tailLimit:t}}function gr(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 zm(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 Vm{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||Gt,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.snapshot=ra(Math.max(0,t.tailLimit??ir))}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=bc(n,this.snapshot.cursor.tailLimit);gr(this.snapshot.liveMessages)===gr(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:Hm}))}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=na(this.snapshot.liveMessages[this.snapshot.liveMessages.length-1]);if(t.syncMode!=="full"&&r&&n===r){const u={knownMessageCount:Math.max(this.snapshot.cursor.knownMessageCount,Number(t.totalMessages||0)),lastMessageSignature:r,tailLimit:this.snapshot.cursor.tailLimit};this.snapshot.cursor.knownMessageCount===u.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===u.lastMessageSignature||(this.snapshot={...this.snapshot,cursor:u},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:u.knownMessageCount,lastMessageSignature:u.lastMessageSignature}));return}const a=zm(this.snapshot.liveMessages,t),i={knownMessageCount:a.length,lastMessageSignature:typeof t.lastMessageSignature=="string"?t.lastMessageSignature:na(a[a.length-1]),tailLimit:this.snapshot.cursor.tailLimit};gr(this.snapshot.liveMessages)===gr(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 gc(e){const t=_a(e.daemonId,e.sessionId),r=_o.get(t);if(r)return r.updateOptions(e),r;const n=new Vm(e);return _o.set(t,n),n}function Gm(e,t){return{...e,loadHistoryPage:t}}function qm(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function Ym(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(Um.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??Ra)),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 Xm(e=Ra){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Jm(e,t={}){const r=new Set,n=[];for(const a of e){if(!Ym(a,t))continue;const i=_s(a),c=a.sessionId||"";if(!i||!c)continue;const l=_a(i,c);if(r.has(l))continue;r.add(l);const u=ar(a);n.push({daemonId:i,sessionId:c,historySessionId:u||c,subscriptionKey:`daemon:${i}:session:${c}`})}return n.sort(qm),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Qm(e,t){const{sendData:r,sendCommand:n}=vt(),a=(t==null?void 0:t.enabled)!==!1,i=_s(e),c=e.sessionId||"",l=ar(e)||c,u=`daemon:${i}:session:${c}`,f=Math.max(0,(t==null?void 0:t.tailLimit)??ir),d=o.useMemo(()=>!a||!i||!c?null:gc({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:u,sendData:r,tailLimit:f}),[i,a,l,r,c,u,f]),[h,m]=o.useState(()=>(d==null?void 0:d.getSnapshot())||ra(f));o.useEffect(()=>{if(!d){m(ra(f));return}d.retain(),m(d.getSnapshot());const k=d.subscribe(p=>{m(p)});return()=>{k(),d.release()}},[d,f]),o.useEffect(()=>{d&&(d.hydrateLiveMessages(e.messages),m(d.getSnapshot()))},[e.messages,d]);const v=o.useCallback(async()=>{!d||!i||!c||await d.loadHistoryPage(async()=>{const k=e.agentType,p=await n(i,"chat_history",{agentType:k,offset:d.getSnapshot().historyOffset,limit:30,targetSessionId:c,historySessionId:l}),x=p&&typeof p=="object"&&"result"in p?p.result||{}:p||{};return{messages:Array.isArray(x.messages)?x.messages:[],hasMore:x.hasMore===!0}})},[e.agentType,d,i,l,n,c]);return o.useMemo(()=>Gm(h,v),[v,h])}function Zm(e,t){const{sendData:r}=vt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??ir),i=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Ra)),c=Xm(i),[l,u]=o.useState(0),[f,d]=o.useState(()=>new Map);o.useEffect(()=>{if(!n||e.length===0)return;const m=setInterval(()=>{u(v=>v+1)},c);return()=>{clearInterval(m)}},[e.length,n,c]);const h=o.useMemo(()=>Jm(e,{recentActivityMs:i}),[e,i,l]);return o.useEffect(()=>{if(!n||!r||h.descriptors.length===0){d(x=>x.size===0?x:new Map);return}const m=h.descriptors.map(x=>({key:_a(x.daemonId,x.sessionId),controller:gc({...x,sendData:r,tailLimit:a})})),v=new Set(m.map(({key:x})=>x)),k=(x,w)=>{d(b=>{const N=new Map(b);for(const I of N.keys())v.has(I)||N.delete(I);return N.set(x,w),N})},p=m.map(({key:x,controller:w})=>(w.retain(),k(x,w.getSnapshot()),w.subscribe(b=>k(x,b))));return()=>{p.forEach(x=>x()),m.forEach(({controller:x})=>x.release())}},[h.signature,n,r,a]),f}function Po(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 Do(e){for(let t=e.length-1;t>=0;t-=1){const r=Ta(e[t]);if(r>0)return r}return 0}function ef(e){const t=_s(e),r=e.sessionId||"";return t&&r?`${t}::${r}`:""}function tf(e,t){if(t.length===0)return!1;const r=Array.isArray(e.messages)?e.messages:[];if(r.length===0)return!0;const n=Do(r),a=Do(t);if(n<=0||a<=n)return!1;const i=Po(r,e.status),c=Po(t,e.status);return i!==c}function sf(e,t){const r=t[t.length-1],n=Ta(r),a=Ss(r==null?void 0:r.content);return{...e,messages:t,...a?{lastMessagePreview:a}:{},...n>0?{lastMessageAt:n}:{}}}function rf(e,t){const r=(t==null?void 0:t.liveMessages)||[];return r.length>0?r:e.messages}function nf(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 Eo(e,t){if(t.size===0||e.length===0)return e;let r=!1;const n=e.map(a=>{var l;const i=ef(a);if(!i)return a;const c=((l=t.get(i))==null?void 0:l.liveMessages)||[];return tf(a,c)?(r=!0,sf(a,c)):a});return r?n:e}function af(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function of(e){return af(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const cf=60;function aa({activeConv:e,ideEntry:t,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:l,userName:u,showMetaChips:f=!1,scrollToBottomRequestNonce:d,isInputActive:h=!0,isVisible:m=!0}){var be,ge,ve,H,U;const v=o.useRef(new Map),k=or();nr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const p=jt.useMemo(()=>Ls(e),[e.status,e.connectionState]),x=o.useMemo(()=>jm(e,t),[e,t]),w=o.useMemo(()=>{var Q;return Na((Q=x.targetEntry)==null?void 0:Q.providerControls,{hostIdeType:e.hostIdeType,providerType:x.providerType})},[e.hostIdeType,x.providerType,(be=x.targetEntry)==null?void 0:be.providerControls]),b=xc({isCliLike:x.isCli||x.isAcp}),N=Fm({isCliLike:x.isCli||x.isAcp}),I=Qm(e,{enabled:m&&!!e.sessionId,tailLimit:N}),[y,M]=o.useState(b),S=e.tabKey,j=I.historyMessages,g=I.hasMoreHistory,$=I.historyError,A=rf(e,I);o.useEffect(()=>{M(b)},[b,S]);const L=Math.max(0,A.length-y),O=Ca(e),W=_s(e),P=of(e),C=La(e),T=a||C,V=!!C,[E,_]=o.useState(!1);o.useEffect(()=>{const Q=x.targetEntry;W&&(!Q||Q.providerControls===void 0||Q.controlValues===void 0)&&k(W,{minFreshMs:3e4}).catch(()=>{})},[W,x.isAcp,(ge=x.targetEntry)==null?void 0:ge.providerControls,(ve=x.targetEntry)==null?void 0:ve.controlValues,k]);const F=o.useCallback(async()=>{if(!E){if(A.length>y){M(Q=>Math.min(A.length,Q+cf));return}_(!0);try{await I.loadHistoryPage()}finally{_(!1)}}},[I,E,A.length,y]),{allMessages:J,receivedAtMap:xe}=o.useMemo(()=>{const Q=nf({historyMessages:j,liveMessages:A,visibleLiveCount:y}),de={};return Q.forEach((ne,fe)=>{const ae=`${e.tabKey}:${Or(ne,fe)}`;let pe=Ta(ne)||v.current.get(ae)||0;pe||(pe=Date.now(),v.current.set(ae,pe)),de[Or(ne,fe)]=pe}),{allMessages:Q,receivedAtMap:de}},[e.tabKey,L,j,A,y]),ce=o.useMemo(()=>l.filter(Q=>Q.routeId===e.tabKey).sort((Q,de)=>Q.timestamp-de.timestamp),[l,e.tabKey]),te=o.useMemo(()=>{if(A.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")&&_(!1),e.status==="not_monitored"&&P)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(Zs,{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 ",O," 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"&&P)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(Ki,{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 ",O," 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"&&!E)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,P,i,c,E,A.length,O,p.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[f&&s.jsx(hc,{conversation:e,className:"chat-pane-meta-row"}),s.jsx(hu,{messages:J,actionLogs:ce,agentName:Cs(e)||O||"Agent",userName:u,isCliMode:x.isCli||x.isAcp,isWorking:p.isGenerating,contextKey:e.tabKey,receivedAtMap:xe,onLoadMore:F,isLoadingMore:E,hasMoreHistory:g,hiddenLiveCount:L,loadError:$??void 0,emptyState:te,scrollToBottomRequestNonce:d,isVisible:m}),s.jsx(pm,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:x.providerType,displayLabel:x.displayLabel,controls:(H=x.targetEntry)==null?void 0:H.providerControls,controlValues:(U=x.targetEntry)==null?void 0:U.controlValues,isActive:h,isCliTerminal:x.isCliTerminal}),!x.isCliTerminal&&s.jsx(nc,{contextKey:e.tabKey,panelLabel:O,isSending:n,isBusy:V,statusMessage:T,onSend:r,isActive:h,showControlsToggle:w.length>0})]})}let yc=is;function vc(){return yc()}class lf{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 wc=new lf;class df{sendPtyInput(t,r,n){return!1}retryConnection(t){}getState(t){return"disconnected"}sendData(t,r){return!1}get(t){}onScreenshot(t,r){return()=>{}}onRuntimeEvent(t,r,n){return()=>{}}requestRuntimeSnapshot(t,r,n){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let dt=new df;function uf(e){e.dashboardWS&&(wc=e.dashboardWS),e.connectionManager&&(dt=e.connectionManager),e.useDaemonsHook&&(yc=e.useDaemonsHook)}const mf=.5,ff=1.25;function at(e){return Ca(e)}function ds(e){return lc(e).join(" · ")}function jc(e){const t=cc(e);return t||(e.title?e.title:ds(e)||"No messages yet")}function kc(e,t){const{isReconnecting:r,isConnecting:n}=Ls(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function pf(e,t){const r=["Chat",...lc(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function es(e){return kc(e)||ds(e)}function hf(e){return`${at(e)} · ${jc(e)}`}function xf(e){const t=Hr(e),r=t?st(t):Cs(e);return`${at(e)} — ${r||"Agent"}`}function bf(e){return Cs(e)||"CLI"}function Sc(e){return ic(e)}function Nc(e){return e?`Remote · ${at(e)||e.workspaceName||"Session"}`:"Remote"}function gf({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0,isInputActive:l=!0}){var Y;is();const{sendPtyInput:u}=vt(),[f,d]=o.useState(!1),h=o.useRef(!1);h.current=f;const[m,v]=o.useState("Runtime terminal unavailable"),[k,p]=o.useState(!1),[x,w]=o.useState(null),[b,N]=o.useState(1),[I,y]=o.useState({width:0,height:0}),[M,S]=o.useState({width:0,height:0}),j=o.useRef(null),g=o.useRef(null),$=o.useRef(!1),A=o.useRef(!1),L=o.useRef(0),O=o.useRef(!1),W=o.useRef(""),P=o.useRef(null),C=o.useRef(!1),T=o.useRef(null),V=32*1024,E=()=>{var G,X,re,Se;return((X=(G=j.current)==null?void 0:G.ownerDocument)==null?void 0:X.defaultView)||((Se=(re=g.current)==null?void 0:re.ownerDocument)==null?void 0:Se.defaultView)||window},_=G=>{const X=E();return{ownerWindow:X,frameId:X.requestAnimationFrame(G)}},F=()=>{const G=T.current;if(G){try{G.ownerWindow.cancelAnimationFrame(G.frameId)}catch{}T.current=null}},J=()=>{c&&T.current===null&&(T.current=_(()=>{oe()}))},xe=e.tabKey,ce=e.sessionId||"",te=e.daemonId||((Y=e.routeId)==null?void 0:Y.split(":")[0])||e.routeId||"",be=La(e),ge=f?i||be:m,ve=mf,H=ff,U=.05,Q=()=>{const G=M.width,X=M.height;if(!Number.isFinite(I.width)||I.width<=0||!Number.isFinite(I.height)||I.height<=0||!Number.isFinite(G)||G<=0||!Number.isFinite(X)||X<=0)return 1;const re=I.width/G,Se=I.height/X;return Number(Math.min(H,Math.max(ve,Math.min(re,Se))).toFixed(2))},de=Q(),ne=$.current&&b>de,fe=Number.isFinite(M.width)&&M.width>0?Math.max(I.width,Math.round(M.width*b)):I.width,ae=Number.isFinite(M.height)&&M.height>0?Math.max(I.height,Math.round(M.height*b)):I.height,pe=()=>{_(()=>{const G=g.current;G&&(G.scrollLeft=0,G.scrollTop=G.scrollHeight-G.clientHeight)})},le=()=>{var G,X;L.current=0,O.current=!1,W.current="",P.current=null,C.current=!1,$.current||(A.current=!1,N(1)),T.current!==null&&F(),d(!1),v("Runtime terminal unavailable"),w(null),p(!1),(X=(G=r.current)==null?void 0:G.reset)==null||X.call(G)},ue=()=>{var G,X;L.current=0,O.current=!1,W.current="",P.current=null,C.current=!1,T.current!==null&&F(),d(!0),v(""),w(null),p(!1),(X=(G=r.current)==null?void 0:G.reset)==null||X.call(G)},oe=()=>{var re;if(T.current=null,!c)return;const G=W.current;if(!G)return;const X=G.slice(0,V);W.current=G.slice(X.length),(re=r.current)==null||re.write(X),W.current.length>0&&J()},ye=G=>{G&&(W.current+=G,J())},he=(G,X=0,re,Se,Ae={})=>{var Be,Ke,qe,ze;const $e=!!Ae.force;!$e&&X>0&&L.current>=X||!$e&&X===0&&O.current||(L.current=X,d(!0),v(""),typeof re=="number"&&typeof Se=="number"&&re>0&&Se>0&&((Ke=(Be=r.current)==null?void 0:Be.resize)==null||Ke.call(Be,re,Se)),W.current="",(ze=(qe=r.current)==null?void 0:qe.reset)==null||ze.call(qe),G&&ye(G))};o.useEffect(()=>{le()},[ce]),o.useEffect(()=>{var X;if(!ce)return;const G=((X=dt.onRuntimeEvent)==null?void 0:X.call(dt,ce,re=>{if(!(!re||re.sessionId!==ce)){if(re.type==="runtime_snapshot"){if(!c){P.current={text:re.text||"",seq:re.seq||0,cols:re.cols,rows:re.rows,force:!!re.force};return}he(re.text||"",re.seq||0,re.cols,re.rows,{force:!!re.force});return}if(re.type==="session_output"){O.current=!0,typeof re.seq=="number"&&(L.current=Math.max(L.current,re.seq)),h.current||d(!0),h.current||v(""),typeof re.data=="string"&&ye(re.data);return}if(re.type==="session_cleared"){if(!c){C.current=!0,W.current="",P.current=null;return}ue();return}if(re.type==="session_io_error"){const Se=typeof re.error=="string"&&re.error?re.error:typeof re.reason=="string"&&re.reason?re.reason:"unknown error";d(!1),v(`Runtime input failed: ${Se}`);return}}},te))||(()=>{});return()=>{G()}},[te,ce,r,c]);const ke=async(G={})=>{var X;if(!te||!ce)return{success:!1,error:"daemonId and sessionId are required"};G.preserveStatus||v(G.loadingMessage||"Loading runtime terminal...");try{const re=await((X=dt.requestRuntimeSnapshot)==null?void 0:X.call(dt,te,ce,{sinceSeq:G.sinceSeq,force:G.force}));return re&&re.success===!1?(G.preserveStatus||(d(!1),v(`Runtime terminal unavailable: ${re.error}`)),re):re||{success:!0}}catch(re){const Se=(re==null?void 0:re.message)||String(re);return G.preserveStatus||(d(!1),v(`Runtime terminal unavailable: ${Se}`)),{success:!1,error:Se}}},D=async()=>{if(k)return;p(!0),w("Loading older terminal output...");const G=await ke({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:f});if(p(!1),(G==null?void 0:G.success)===!1){w(`Older terminal output unavailable: ${G.error}`);return}w("Older terminal output loaded"),_(()=>{var X;(X=r.current)==null||X.bumpResize()})};return o.useEffect(()=>{var X,re;if(!ce)return;te&&((X=dt.getState)==null?void 0:X.call(dt,te))==="connected"&&ke();const G=(re=dt.onStateChange)==null?void 0:re.call(dt,(Se,Ae)=>{Se!==te||Ae!=="connected"||ke()});return()=>{G==null||G()}},[te,ce,r]),o.useEffect(()=>{t&&le()},[t,xe,r]),o.useEffect(()=>{var Se,Ae;const G=j.current,X=(Ae=(Se=G==null?void 0:G.ownerDocument)==null?void 0:Se.defaultView)==null?void 0:Ae.ResizeObserver;if(!G||!X)return;const re=new X($e=>{const Be=$e[0];if(!Be)return;const{width:Ke,height:qe}=Be.contentRect;y(ze=>{const rt=Math.round(Ke),ct=Math.round(qe);return ze.width===rt&&ze.height===ct?ze:{width:rt,height:ct}})});return re.observe(G),()=>re.disconnect()},[]),o.useEffect(()=>{if($.current)return;const G=Q();!Number.isFinite(G)||G<=0||N(X=>A.current?G<X-U?G:X:(A.current=!0,G))},[M.height,M.width,I.height,I.width]),o.useEffect(()=>{ne&&pe()},[ne,ae,fe]),o.useEffect(()=>{var X;if(!c)return;C.current&&(C.current=!1,ue());const G=P.current;G&&(P.current=null,he(G.text,G.seq,G.cols,G.rows,{force:!!G.force})),te&&ce&&((X=dt.getState)==null?void 0:X.call(dt,te))==="connected"&&ke(),W.current&&T.current===null&&J(),_(()=>{var re;(re=r.current)==null||re.bumpResize()})},[te,c,ce]),o.useEffect(()=>()=>{T.current!==null&&F()},[]),o.useEffect(()=>{const G=Se=>{var $e;const Ae=Se.detail;Ae!=null&&Ae.sessionId&&Ae.sessionId!==ce||f&&(($e=r.current)==null||$e.bumpResize())},X=E(),re=X===window?[window]:[window,X];for(const Se of re)Se.addEventListener("adhdev:fit-cli-terminal",G);return()=>{for(const Se of re)Se.removeEventListener("adhdev:fit-cli-terminal",G)}},[f,ce,r]),s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:j,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[s.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-medium text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{D()},disabled:!ce||k,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:k?"Loading older...":"Load older terminal output"}),x&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:x})]}),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:()=>{$.current=!0,N(G=>{const X=Math.max(de,Number((G-.1).toFixed(2)));return X>de&&pe(),X})},title:"Shrink terminal viewport",children:"-"}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{$.current=!0,N(G=>{const X=Math.min(H,Number((G+.1).toFixed(2)));return X>de&&pe(),X})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:g,className:ne?"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:fe>0?`${fe}px`:"100%",height:ae>0?`${ae}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:M.width>0?`${M.width}px`:"100%",height:M.height>0?`${M.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:b},children:s.jsx(Vi,{ref:r,readOnly:!f||!c,sizingMode:"measured",onViewportMetrics:S,onInput:G=>{!f||(u==null||u(te,ce,G))}})})})}),!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(nc,{contextKey:e.tabKey,panelLabel:at(e),isSending:a,isBusy:!!be,statusMessage:ge,onSend:async G=>be?!1:n(G),isActive:l&&c,showControlsToggle:!1,animateVisibility:!1})]})}const yf=5e3;function vf(e){return e==="disconnected"||e==="reconnecting"}function wf({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=yf}){const i=vf(e),[c,l]=o.useState(()=>!i||a<=0),u=o.useRef(!1);o.useEffect(()=>{if(!i){l(!1);return}if(u.current=!1,a<=0){u.current=!0,l(!0);return}l(!1);const w=setTimeout(()=>{u.current=!0,l(!0)},a);return()=>clearTimeout(w)},[a,i]);const f=i?c:e==="offline"||e==="auth_failed",d=o.useMemo(()=>!t||e!=="connected"?!1:a<=0||u.current,[a,t,e]),h=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)"},k={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",x={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:x,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[h],border:v[h],color:k[h]},children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),s.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&"Network offline",e==="disconnected"&&"Reconnecting",e==="reconnecting"&&"Reconnecting",e==="auth_failed"&&(r?s.jsxs(s.Fragment,{children:["Session expired."," ",s.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — refresh the page or try again shortly.")]}),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"})]})}),d&&s.jsx("div",{className:p,style:x,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 jf({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",u=()=>{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:u,className:"shrink-0 text-[12px] font-semibold px-2 py-1 rounded-md transition-colors",style:{color:"#b45309",background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.18)"},"aria-label":"Dismiss terminal backend warning",title:"Dismiss",children:"Dismiss"})]})}function Pa({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(va,{size:n}):s.jsx(Ft,{size:n})})}const Et="New session",Cc="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 kf({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 Bo({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=Qr(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:u=>{u.stopPropagation(),n()},children:"Mark read"}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),a()},children:"Mark unread"}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),i()},children:"Delete"})]})]})}function Sf({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:i,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:u,onHideConversation:f,hiddenConversations:d=[],onShowConversation:h,onShowAllHidden:m,onResetPanelsToMain:v,inboxOpen:k,onInboxOpenChange:p,hiddenOpen:x,onHiddenOpenChange:w,onOpenNewSession:b,actionShortcuts:N,notifications:I,notificationUnreadCount:y,onOpenNotification:M,onMarkNotificationRead:S,onMarkNotificationUnread:j,onDeleteNotification:g}){const{ides:$,p2pStates:A={}}=is(),L=!!e&&et(e)&&!Je(e),O=!!e&&Je(e),W=l||(e?ac(e)?"terminal":"chat":null),[P,C]=o.useState(!1),T=o.useRef(null),V=o.useRef(null),E=$.filter(H=>H.type==="adhdev-daemon"),_=kf({wsStatus:t,isConnected:r,daemonCount:E.length,p2pStates:A}),F=_.subtitle,J=_.tone==="connected"?"#22c55e":_.tone==="limited"?"#eab308":"#ef4444",xe=_.tone==="connected"?"0 0 4px #22c55e80":_.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",ce=o.useMemo(()=>I.filter(H=>!H.readAt),[I]),te=o.useMemo(()=>I.filter(H=>!!H.readAt),[I]),be=o.useMemo(()=>ce.slice(0,9),[ce]),ge=y;o.useEffect(()=>{if(!k)return;const H=U=>{var Q;(Q=T.current)!=null&&Q.contains(U.target)||p(!1)};return document.addEventListener("mousedown",H),()=>document.removeEventListener("mousedown",H)},[k,p]),o.useEffect(()=>{if(!x)return;const H=U=>{var Q;(Q=V.current)!=null&&Q.contains(U.target)||w(!1)};return document.addEventListener("mousedown",H),()=>document.removeEventListener("mousedown",H)},[x,w]),o.useEffect(()=>{if(!x&&!k)return;const H=U=>{if(!U.altKey)return;const Q=U.code.match(/^Digit([1-9])$/);if(!Q)return;const de=Number(Q[1])-1,ne=x?d[de]:void 0,fe=k?be[de]:void 0;if(!(!ne&&!fe)){if(U.preventDefault(),U.stopPropagation(),ne){h==null||h(ne),w(!1);return}fe&&(M(fe),p(!1))}};return window.addEventListener("keydown",H,!0),()=>window.removeEventListener("keydown",H,!0)},[d,x,k,be,w,p,M,h]);const ve=H=>{if(!H)return;const U=n.find(Q=>Q.tabKey===H);U&&(f==null||f(U))};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(Ft,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?at(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:J,boxShadow:xe}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[s.jsx("span",{title:_.title,className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:J,boxShadow:xe}}),F&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",F]}),b&&s.jsx("button",{type:"button",onClick:b,className:"btn btn-secondary btn-sm ml-2",title:Et,"aria-label":Et,children:s.jsx(Fi,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(L||O||!Je(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:ds(e)||at(e),children:at(e)}),(L||O)&&c&&s.jsxs(s.Fragment,{children:[L&&u&&W&&s.jsx(Pa,{mode:W,onChange:u,compact:!0}),s.jsx("button",{onClick:()=>c(e),className:"btn btn-secondary btn-sm",title:O?"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(yt,{size:14})})]}),!Je(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(ya,{size:14})}),!L&&!Je(e)&&s.jsx("button",{onClick:i,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(St,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:T,children:[s.jsxs("div",{className:`dashboard-header-hidden${P?" is-drop-target":""}`,ref:V,onDragEnter:H=>{H.dataTransfer.types.includes("text/tab-key")&&(H.preventDefault(),C(!0))},onDragOver:H=>{H.dataTransfer.types.includes("text/tab-key")&&(H.preventDefault(),H.dataTransfer.dropEffect="move",C(!0))},onDragLeave:H=>{H.currentTarget.contains(H.relatedTarget)||C(!1)},onDrop:H=>{const U=H.dataTransfer.getData("text/tab-key");H.preventDefault(),C(!1),ve(U)},children:[s.jsxs("button",{type:"button",onClick:()=>w(!x),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(Oi,{size:16}),d.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:d.length})]}),x&&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"}),d.length>0&&m&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{m(),w(!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:at(e)})]}),d.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:d.map(H=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{h==null||h(H),w(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:at(H)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[d.indexOf(H)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",d.indexOf(H)+1]}):null,ds(H)]})]},H.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>p(!k),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(Jr,{size:16}),ge>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:ge})]}),k&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[ce.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),ce.map(H=>s.jsx(Bo,{notification:H,shortcutIndex:be.indexOf(H)>=0?be.indexOf(H)+1:void 0,onOpen:()=>M(H),onMarkRead:()=>S(H.id),onMarkUnread:()=>j(H.id),onDelete:()=>g(H.id)},H.id))]}),te.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),te.map(H=>s.jsx(Bo,{notification:H,onOpen:()=>M(H),onMarkRead:()=>S(H.id),onMarkUnread:()=>j(H.id),onDelete:()=>g(H.id)},H.id))]}),I.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function pt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function Nf(e,t){return String(e||"")!==String(t||"")}function Cf(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(u=>String(u||"").toLowerCase()).join(`
30
30
  `).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!Zi(c.summaryMetadata).map(u=>u.toLowerCase()).join(`
31
- `).includes(a)))}function If(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 Ic(e,t={}){return If(Cf(e,t),t.sortMode||"recent")}function zr(e){return e?"Resume saved history":"Start fresh"}function Da(e){return e?"Resuming saved history…":"Starting fresh…"}function Mf(){return"Start fresh"}function Mc(e,t=!1){return e==="cli"?zr(t):e==="ide"?"Start IDE":"Start ACP session"}function Ac(e,t=!1){return e==="cli"?Da(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Af(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Tf(){return"Open saved history"}function Lf(){return"Saved History"}function Ea(){return"Use saved history when you want continuity in the same provider conversation."}function Rf(){return"No saved history found yet."}function _f(){return"Refresh saved history"}function Pf(){return"Refreshing saved history…"}function ts(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function ss(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 $a(e){return`Resume saved history with ${e}?`}function Ba(){return"Review or change the target workspace before resuming saved history."}function Df(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 Ka({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:u,onClose:f,onNewChat:d,onSwitchSession:h,onRefreshHistory:m,onResumeSavedSession:v}){var j;const k=t.find(g=>g.id===e.routeId),p=(k==null?void 0:k.chats)||[],x=(j=k==null?void 0:k.activeChat)==null?void 0:j.id,w=et(e)&&!Je(e),[b,N]=o.useState(()=>pt()),I=l||b,y=g=>{if(u){u(g);return}N(g)},M=o.useMemo(()=>Ic(a,{textQuery:I.textQuery,workspaceQuery:I.workspaceQuery,modelQuery:I.modelQuery,resumableOnly:I.resumableOnly,sortMode:I.sortMode}),[I.modelQuery,I.resumableOnly,I.sortMode,I.textQuery,I.workspaceQuery,a]),S=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:w?Lf():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:xf(e)}),w&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Ea()})]}),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(yt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!w&&s.jsx("button",{onClick:d,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),w?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:I.textQuery,onChange:g=>y({...I,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:I.workspaceQuery,onChange:g=>y({...I,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:I.modelQuery,onChange:g=>y({...I,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:I.sortMode,onChange:g=>y({...I,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:I.resumableOnly,onChange:g=>y({...I,resumableOnly:g.target.checked})}),"Resume-ready only"]})]}),M.map(g=>{const $=e.providerSessionId===g.providerSessionId,A=$||!g.canResume||!!c;return s.jsxs("button",{type:"button",onClick:()=>{A||!v||v(g)},disabled:A,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${$?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${A?"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 ${$?"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:Df(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",ls(g.summaryMetadata)?` · ${ls(g.summaryMetadata)}`:"",g.messageCount>0?` · ${g.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:$?"ACTIVE":g.canResume?c===g.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},g.id)})]}):p.map(g=>s.jsxs("div",{onClick:()=>{h(e.routeId,g.id),f()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${x===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 ${x===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),"..."]}),x===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)),(w&&!i&&M.length===0||!w&&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(Gd,{size:32})}),s.jsx("div",{className:"text-[13px]",children:w?a.length>0?"No saved history matches these filters.":Rf():"No recent chat sessions found."})]}),w&&i&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:Pf()})})]}),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(rr,{size:13})," ",w?_f():"Refresh History"]})})})]})]});return typeof document>"u"?S:Xs.createPortal(S,document.body)}const Ko={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 Tc({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=Ko[n.type]||Ko.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(yt,{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 Ef=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function $f(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function Bf(e){return e.sessionId||e.instanceId||e.agentType}function vn(e,t){return e||t}function Lc(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Mt(r,{fallbackId:r.id}));return t}function Rc(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 Oa(e,t={}){return Kf(e,Rc(e,t))}function Kf(e,t={}){var d,h,m,v,k,p;const r=[],n=t.machineName,a=t.connectionState,i=$f(e),c=Pu(e.type,{agentName:e.cliName}),l=et(e)||Je(e)?c:st(e.type),u=Array.isArray(e.childSessions)?e.childSessions.map(x=>{var w,b;return{sessionId:x.id,instanceId:x.id,providerSessionId:x.providerSessionId,transport:x.transport,sessionCapabilities:x.capabilities,agentType:x.providerType,agentName:x.providerName||st(x.providerType),status:x.status,title:x.title,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,messages:((w=x.activeChat)==null?void 0:w.messages)||[],activeModal:((b=x.activeChat)==null?void 0:b.activeModal)||void 0,unread:x.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,inboxBucket:x.inboxBucket,surfaceHidden:x.surfaceHidden}}):[],f=Ef(e);if(f){const x=e.sessionId||e.instanceId,w=c,b=(d=e.activeChat)==null?void 0:d.activeModal,N=b&&Array.isArray(b.buttons)&&b.buttons.length>0,I=xt((h=e.activeChat)==null?void 0:h.status,{activeModal:(m=e.activeChat)==null?void 0:m.activeModal})||xt((k=(v=e.agents)==null?void 0:v[0])==null?void 0:k.status)||"idle",y=e.activeChat||{title:"",messages:[]};let M=y.title&&String(y.title).trim()?String(y.title).trim():"";const S=(p=e.activeChat)==null?void 0:p.id,j=e.chats;if(S&&Array.isArray(j)&&j.length>0){const L=j.find(O=>O.id===S||O.id&&String(O.id)===String(S));L!=null&&L.title&&String(L.title).trim()&&(M=String(L.title).trim())}const g=(et(e)||Je(e),e.type),$=(et(e)||Je(e))&&No(M,w,g)?"":M,A=y.messages||[];r.push({routeId:e.id,sessionId:x,providerSessionId:e.providerSessionId,nativeSessionId:x,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:et(e)?e.mode||"terminal":"chat",agentName:w,agentType:g,status:I,title:$,messages:A,resume:e.resume,hostIdeType:!et(e)&&!Je(e)?e.type:void 0,workspaceName:i,displayPrimary:$||i||(et(e)?e.mode==="chat"?w:"Terminal":w),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:vn(x,e.id),machineName:n,connectionState:a})}if(f&&(et(e)||Je(e)))return r;for(const x of u){const w=x.activeModal&&Array.isArray(x.activeModal.buttons)&&x.activeModal.buttons.length>0,b=Du(x),N=Bf(x),I=`${e.id}:${N}`,y=x.title&&String(x.title).trim()||"",M=No(y,x.agentName,x.agentType)?"":y,S=x.messages||[];(x.transport==="cdp-webview"||x.sessionId||x.providerSessionId||S.length>0||w||M||!["idle","panel_hidden","disconnected","not_monitored"].includes(b))&&r.push({routeId:e.id,sessionId:x.sessionId||x.instanceId,providerSessionId:x.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:x.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:x.sessionCapabilities,mode:"chat",agentName:x.agentName,agentType:x.agentType,status:b,title:M,messages:S,hostIdeType:e.type,workspaceName:i,displayPrimary:M||i||x.agentName||l,displaySecondary:`${l} · ${x.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,lastUpdated:x.lastUpdated||e.lastUpdated,modalButtons:w?x.activeModal.buttons:void 0,modalMessage:w?x.activeModal.message:void 0,streamSource:"agent-stream",tabKey:vn(x.sessionId||x.instanceId,I),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:vn(e.sessionId||e.instanceId,e.id),connectionState:a}),r}function Of(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 _c(e,t){const r=Of(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Pc=[{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:"🏄"}],Dc=[{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:"🧩"}],Ec=[{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:"🟠"}],Wf=Pc,Ff=Dc,Hf=Ec;function us(...e){return id(cd(e))}function Uf({icon:e,title:t,subtitle:r,badge:n,actions:a,className:i}){return s.jsxs("div",{className:us("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 $c({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(Uf,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:us("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}const oa="adhdev:themechange";function zf(){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"?zf():e}function Bc(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Rr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(oa,{detail:{preference:e,theme:t}}))}function Vf(){const e=xs(),t=bs(e);Bc(t),Rr(e,t)}function Wa(){const[e,t]=o.useState(xs),[r,n]=o.useState(()=>bs(xs()));o.useEffect(()=>{Bc(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=u=>{if(e==="system"){const f=u.matches?"light":"dark";n(f),Rr("system",f)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=u=>{const f=u.detail||{},d=f.preference,h=f.theme;t(d==="dark"||d==="light"||d==="system"?d:xs()),n(h==="dark"||h==="light"?h:bs(xs()))},l=u=>{if(u.key!=="theme")return;const f=xs(),d=bs(f);t(f),n(d)};return window.addEventListener(oa,c),window.addEventListener("storage",l),()=>{window.removeEventListener(oa,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=bs(c);t(c),n(l);try{localStorage.setItem("theme",c)}catch{}Rr(c,l)},[]),i=o.useCallback(()=>{t(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=bs(l);n(u);try{localStorage.setItem("theme",l)}catch{}return Rr(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const Oo={dark:"Dark",light:"Light",system:"System"};function Gf({collapsed:e}){const{preference:t,cycleTheme:r}=Wa(),n=t==="dark"?s.jsx(Yd,{size:16}):t==="light"?s.jsx(qd,{size:16}):s.jsx(Xd,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Oo[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:Oo[t]})]})}function wn(e,t){return e?typeof e=="function"?e(t):e:null}function qf({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:i,footerActions:c,preMainContent:l,collapsedStorageKey:u="sidebar-collapsed"}){const[f,d]=o.useState(!1),[h,m]=o.useState(()=>{try{return localStorage.getItem(u)==="1"}catch{return!1}}),v=()=>d(!0),k=()=>d(!1),p=()=>{m(N=>{const I=!N;try{localStorage.setItem(u,I?"1":"0")}catch{}return I})},x=o.useMemo(()=>({collapsed:h,mobileMenuOpen:f,openMobileMenu:v,closeMobileMenu:k,toggleCollapsed:p}),[h,f]),w=N=>`nav-item${N.active?" active":""} cursor-pointer ${h?"justify-center py-2.5 px-0":""}${N.className?` ${N.className}`:""}`,b=N=>s.jsxs("div",{className:w(N),id:`nav-${N.id}`,onClick:()=>{N.onSelect(),k()},title:h?N.title??(typeof N.label=="string"?N.label:void 0):N.title,children:[s.jsx("span",{className:"nav-icon",children:N.icon}),!h&&N.label]},N.id);return s.jsxs("div",{className:`app-layout${f?" mobile-menu-open":""}${h?" 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:k,onKeyDown:N=>N.key==="Escape"&&k()}),s.jsxs("aside",{className:`sidebar ${f?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${h?"justify-center gap-0":""}`,children:wn(t,x)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:k,children:s.jsx(yt,{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:[!h&&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),wn(i,x),s.jsx(Gf,{collapsed:h}),wn(c,x)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function kt({title:e,icon:t,description:r,accentColor:n,className:a,children:i}){return s.jsxs("div",{className:us("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 Kc({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:us("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 Yf={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"},Xf={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function yr({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:us("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Yf[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Xf[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 Jf={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 Zf({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:us("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Jf[e],r),children:[s.jsx("span",{className:us("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Qf[e])}),n]})}function Jt({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 ep({onPrefChange:e}){const[t,r]=zu(),[n,a]=o.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);o.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,l)=>{r({[c]:l}),e==null||e(c,l)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Jt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Jr,{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(Jt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(St,{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:()=>{sc().then(a)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:"Allow notifications"})]}),n==="denied"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),n==="unsupported"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),t.globalEnabled&&t.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(Jt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Jd,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(Jt,{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(Jt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Zs,{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 Vr(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function tp(e,t){const r=Vr(e),n=Vr(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 Oc(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function Gs(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||tp(r,t)>=0)return!1;const n=Vr(r),a=Vr(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function sp(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function jn(e,t){return e instanceof Error?e.message:t}function rp({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(Kc,{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(ap,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function Wo({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 Xs.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 np(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Wf,...Ff,...Hf].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 ap({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var W,P;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[f,d]=o.useState(null),[h,m]=o.useState("idle"),[v,k]=o.useState(""),p=e.version||null,x=((W=e.machine)==null?void 0:W.platform)||((P=e.system)==null?void 0:P.platform)||"",w=Mt(e,{fallbackId:e.id}),b=x==="win32"?"🪟":x==="darwin"?"🍎":"🐧",N=t.filter(C=>C.daemonId===e.id&&C.transport==="cdp-page"),I=t.filter(C=>C.daemonId===e.id&&C.transport==="pty"),y=t.filter(C=>C.daemonId===e.id&&C.transport==="acp"),M=e.p2p,S=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const C=sp(await r(e.id,"daemon_upgrade",{}));C.alreadyLatest?(c("done"),u(`Already on v${C.version||"latest"}.`)):C.upgraded||C.success?(c("done"),u(`Upgrade to v${C.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(C.error||"Upgrade failed"))}catch(C){c("error"),u(jn(C,"Connection lost during upgrade"))}}},j=async()=>{if(d(null),!!n){m("loading");try{await n(e.id),m("done"),k("Machine disconnected.")}catch(C){m("error"),k(jn(C,"Failed to disconnect"))}}},g=async()=>{if(d(null),!!a){m("loading");try{await a(e.id),m("done"),k("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(C){m("error"),k(jn(C,"Failed to revoke token"))}}},$="0.9.31",A=Oc(e,$),L=Gs(e,$),O=N.length+I.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:w}),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] ${A?"":"bg-bg-secondary"}`,style:A?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",p,!A&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&A&&s.jsx("button",{onClick:S,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${$}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${L?"↑ Update now":`↑ Update${` to v${$}`}`}`}),n&&s.jsx("button",{onClick:()=>d("disconnect"),disabled:h==="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:()=>d("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(Zf,{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:[M&&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 ${M.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${M.state==="connecting"||M.state==="new"?"animate-pulse":""}`,style:M.state==="connecting"||M.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",M.state==="connected"?"connected":M.state==="connecting"||M.state==="new"?"connecting...":M.state||"off"]}),M.peers!==void 0&&M.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",M.peers," peer",M.peers!==1?"s":"",")"]})]}),M&&O>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),O>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[N.map(C=>{const T=np(C.type),V=C.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:T.icon}),s.jsx("span",{children:T.name}),V!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${V?"bg-green-400":"animate-pulse"}`,style:V?void 0:{background:"var(--status-warning)"},title:V?"CDP connected":"CDP connecting..."})]},C.id)}),I.map(C=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:C.cliName||"CLI"})]},C.id)),y.map(C=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"🔗"}),s.jsx("span",{children:C.cliName||"ACP"})]},C.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||v)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||h==="error"?"text-red-400":i==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:v||l})]}),f==="disconnect"&&s.jsx(Wo,{title:"🔌 Disconnect Machine",message:`Disconnect "${w}" from ADHDev?
31
+ `).includes(a)))}function If(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 Ic(e,t={}){return If(Cf(e,t),t.sortMode||"recent")}function zr(e){return e?"Resume saved history":"Start fresh"}function Da(e){return e?"Resuming saved history…":"Starting fresh…"}function Mf(){return"Start fresh"}function Mc(e,t=!1){return e==="cli"?zr(t):e==="ide"?"Start IDE":"Start ACP session"}function Ac(e,t=!1){return e==="cli"?Da(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Af(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Tf(){return"Open saved history"}function Lf(){return"Saved History"}function Ea(){return"Use saved history when you want continuity in the same provider conversation."}function Rf(){return"No saved history found yet."}function _f(){return"Refresh saved history"}function Pf(){return"Refreshing saved history…"}function ts(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function ss(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 $a(e){return`Resume saved history with ${e}?`}function Ba(){return"Review or change the target workspace before resuming saved history."}function Df(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 Ka({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:u,onClose:f,onNewChat:d,onSwitchSession:h,onRefreshHistory:m,onResumeSavedSession:v}){var j;const k=t.find(g=>g.id===e.routeId),p=(k==null?void 0:k.chats)||[],x=(j=k==null?void 0:k.activeChat)==null?void 0:j.id,w=et(e)&&!Je(e),[b,N]=o.useState(()=>pt()),I=l||b,y=g=>{if(u){u(g);return}N(g)},M=o.useMemo(()=>Ic(a,{textQuery:I.textQuery,workspaceQuery:I.workspaceQuery,modelQuery:I.modelQuery,resumableOnly:I.resumableOnly,sortMode:I.sortMode}),[I.modelQuery,I.resumableOnly,I.sortMode,I.textQuery,I.workspaceQuery,a]),S=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:w?Lf():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:xf(e)}),w&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Ea()})]}),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(yt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!w&&s.jsx("button",{onClick:d,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),w?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:I.textQuery,onChange:g=>y({...I,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:I.workspaceQuery,onChange:g=>y({...I,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:I.modelQuery,onChange:g=>y({...I,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:I.sortMode,onChange:g=>y({...I,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:I.resumableOnly,onChange:g=>y({...I,resumableOnly:g.target.checked})}),"Resume-ready only"]})]}),M.map(g=>{const $=e.providerSessionId===g.providerSessionId,A=$||!g.canResume||!!c;return s.jsxs("button",{type:"button",onClick:()=>{A||!v||v(g)},disabled:A,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${$?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${A?"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 ${$?"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:Df(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",ls(g.summaryMetadata)?` · ${ls(g.summaryMetadata)}`:"",g.messageCount>0?` · ${g.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:$?"ACTIVE":g.canResume?c===g.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},g.id)})]}):p.map(g=>s.jsxs("div",{onClick:()=>{h(e.routeId,g.id),f()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${x===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 ${x===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),"..."]}),x===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)),(w&&!i&&M.length===0||!w&&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(Gd,{size:32})}),s.jsx("div",{className:"text-[13px]",children:w?a.length>0?"No saved history matches these filters.":Rf():"No recent chat sessions found."})]}),w&&i&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:Pf()})})]}),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(rr,{size:13})," ",w?_f():"Refresh History"]})})})]})]});return typeof document>"u"?S:Xs.createPortal(S,document.body)}const Ko={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 Tc({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=Ko[n.type]||Ko.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(yt,{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 Ef=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function $f(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function Bf(e){return e.sessionId||e.instanceId||e.agentType}function vn(e,t){return e||t}function Lc(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Mt(r,{fallbackId:r.id}));return t}function Rc(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 Oa(e,t={}){return Kf(e,Rc(e,t))}function Kf(e,t={}){var d,h,m,v,k,p;const r=[],n=t.machineName,a=t.connectionState,i=$f(e),c=Pu(e.type,{agentName:e.cliName}),l=et(e)||Je(e)?c:st(e.type),u=Array.isArray(e.childSessions)?e.childSessions.map(x=>{var w,b;return{sessionId:x.id,instanceId:x.id,providerSessionId:x.providerSessionId,transport:x.transport,sessionCapabilities:x.capabilities,agentType:x.providerType,agentName:x.providerName||st(x.providerType),status:x.status,title:x.title,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,messages:((w=x.activeChat)==null?void 0:w.messages)||[],activeModal:((b=x.activeChat)==null?void 0:b.activeModal)||void 0,unread:x.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,inboxBucket:x.inboxBucket,surfaceHidden:x.surfaceHidden}}):[],f=Ef(e);if(f){const x=e.sessionId||e.instanceId,w=c,b=(d=e.activeChat)==null?void 0:d.activeModal,N=b&&Array.isArray(b.buttons)&&b.buttons.length>0,I=xt((h=e.activeChat)==null?void 0:h.status,{activeModal:(m=e.activeChat)==null?void 0:m.activeModal})||xt((k=(v=e.agents)==null?void 0:v[0])==null?void 0:k.status)||"idle",y=e.activeChat||{title:"",messages:[]};let M=y.title&&String(y.title).trim()?String(y.title).trim():"";const S=(p=e.activeChat)==null?void 0:p.id,j=e.chats;if(S&&Array.isArray(j)&&j.length>0){const L=j.find(O=>O.id===S||O.id&&String(O.id)===String(S));L!=null&&L.title&&String(L.title).trim()&&(M=String(L.title).trim())}const g=(et(e)||Je(e),e.type),$=(et(e)||Je(e))&&No(M,w,g)?"":M,A=y.messages||[];r.push({routeId:e.id,sessionId:x,providerSessionId:e.providerSessionId,nativeSessionId:x,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:et(e)?e.mode||"terminal":"chat",agentName:w,agentType:g,status:I,title:$,messages:A,resume:e.resume,hostIdeType:!et(e)&&!Je(e)?e.type:void 0,workspaceName:i,displayPrimary:$||i||(et(e)?e.mode==="chat"?w:"Terminal":w),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:vn(x,e.id),machineName:n,connectionState:a})}if(f&&(et(e)||Je(e)))return r;for(const x of u){const w=x.activeModal&&Array.isArray(x.activeModal.buttons)&&x.activeModal.buttons.length>0,b=Du(x),N=Bf(x),I=`${e.id}:${N}`,y=x.title&&String(x.title).trim()||"",M=No(y,x.agentName,x.agentType)?"":y,S=x.messages||[];(x.transport==="cdp-webview"||x.sessionId||x.providerSessionId||S.length>0||w||M||!["idle","panel_hidden","disconnected","not_monitored"].includes(b))&&r.push({routeId:e.id,sessionId:x.sessionId||x.instanceId,providerSessionId:x.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:x.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:x.sessionCapabilities,mode:"chat",agentName:x.agentName,agentType:x.agentType,status:b,title:M,messages:S,hostIdeType:e.type,workspaceName:i,displayPrimary:M||i||x.agentName||l,displaySecondary:`${l} · ${x.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,lastUpdated:x.lastUpdated||e.lastUpdated,modalButtons:w?x.activeModal.buttons:void 0,modalMessage:w?x.activeModal.message:void 0,streamSource:"agent-stream",tabKey:vn(x.sessionId||x.instanceId,I),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:vn(e.sessionId||e.instanceId,e.id),connectionState:a}),r}function Of(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 _c(e,t){const r=Of(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Pc=[{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:"🏄"}],Dc=[{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:"🧩"}],Ec=[{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:"🟠"}],Wf=Pc,Ff=Dc,Hf=Ec;function us(...e){return id(cd(e))}function Uf({icon:e,title:t,subtitle:r,badge:n,actions:a,className:i}){return s.jsxs("div",{className:us("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 $c({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(Uf,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:us("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}const oa="adhdev:themechange";function zf(){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"?zf():e}function Bc(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Rr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(oa,{detail:{preference:e,theme:t}}))}function Vf(){const e=xs(),t=bs(e);Bc(t),Rr(e,t)}function Wa(){const[e,t]=o.useState(xs),[r,n]=o.useState(()=>bs(xs()));o.useEffect(()=>{Bc(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=u=>{if(e==="system"){const f=u.matches?"light":"dark";n(f),Rr("system",f)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=u=>{const f=u.detail||{},d=f.preference,h=f.theme;t(d==="dark"||d==="light"||d==="system"?d:xs()),n(h==="dark"||h==="light"?h:bs(xs()))},l=u=>{if(u.key!=="theme")return;const f=xs(),d=bs(f);t(f),n(d)};return window.addEventListener(oa,c),window.addEventListener("storage",l),()=>{window.removeEventListener(oa,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=bs(c);t(c),n(l);try{localStorage.setItem("theme",c)}catch{}Rr(c,l)},[]),i=o.useCallback(()=>{t(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=bs(l);n(u);try{localStorage.setItem("theme",l)}catch{}return Rr(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const Oo={dark:"Dark",light:"Light",system:"System"};function Gf({collapsed:e}){const{preference:t,cycleTheme:r}=Wa(),n=t==="dark"?s.jsx(Yd,{size:16}):t==="light"?s.jsx(qd,{size:16}):s.jsx(Xd,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Oo[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:Oo[t]})]})}function wn(e,t){return e?typeof e=="function"?e(t):e:null}function qf({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:i,footerActions:c,preMainContent:l,collapsedStorageKey:u="sidebar-collapsed"}){const[f,d]=o.useState(!1),[h,m]=o.useState(()=>{try{return localStorage.getItem(u)==="1"}catch{return!1}}),v=()=>d(!0),k=()=>d(!1),p=()=>{m(N=>{const I=!N;try{localStorage.setItem(u,I?"1":"0")}catch{}return I})},x=o.useMemo(()=>({collapsed:h,mobileMenuOpen:f,openMobileMenu:v,closeMobileMenu:k,toggleCollapsed:p}),[h,f]),w=N=>`nav-item${N.active?" active":""} cursor-pointer ${h?"justify-center py-2.5 px-0":""}${N.className?` ${N.className}`:""}`,b=N=>s.jsxs("div",{className:w(N),id:`nav-${N.id}`,onClick:()=>{N.onSelect(),k()},title:h?N.title??(typeof N.label=="string"?N.label:void 0):N.title,children:[s.jsx("span",{className:"nav-icon",children:N.icon}),!h&&N.label]},N.id);return s.jsxs("div",{className:`app-layout${f?" mobile-menu-open":""}${h?" 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:k,onKeyDown:N=>N.key==="Escape"&&k()}),s.jsxs("aside",{className:`sidebar ${f?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${h?"justify-center gap-0":""}`,children:wn(t,x)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:k,children:s.jsx(yt,{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:[!h&&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),wn(i,x),s.jsx(Gf,{collapsed:h}),wn(c,x)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function kt({title:e,icon:t,description:r,accentColor:n,className:a,children:i}){return s.jsxs("div",{className:us("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 Kc({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:us("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 Yf={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"},Xf={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function yr({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:us("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Yf[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Xf[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 Jf={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 Zf({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:us("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Jf[e],r),children:[s.jsx("span",{className:us("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Qf[e])}),n]})}function Jt({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 ep({onPrefChange:e}){const[t,r]=zu(),[n,a]=o.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);o.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,l)=>{r({[c]:l}),e==null||e(c,l)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Jt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Jr,{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(Jt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(St,{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:()=>{sc().then(a)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:"Allow notifications"})]}),n==="denied"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),n==="unsupported"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),t.globalEnabled&&t.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(Jt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Jd,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(Jt,{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(Jt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Zs,{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 Vr(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function tp(e,t){const r=Vr(e),n=Vr(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 Oc(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function Gs(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||tp(r,t)>=0)return!1;const n=Vr(r),a=Vr(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function sp(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function jn(e,t){return e instanceof Error?e.message:t}function rp({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(Kc,{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(ap,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function Wo({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 Xs.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 np(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Wf,...Ff,...Hf].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 ap({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var W,P;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[f,d]=o.useState(null),[h,m]=o.useState("idle"),[v,k]=o.useState(""),p=e.version||null,x=((W=e.machine)==null?void 0:W.platform)||((P=e.system)==null?void 0:P.platform)||"",w=Mt(e,{fallbackId:e.id}),b=x==="win32"?"🪟":x==="darwin"?"🍎":"🐧",N=t.filter(C=>C.daemonId===e.id&&C.transport==="cdp-page"),I=t.filter(C=>C.daemonId===e.id&&C.transport==="pty"),y=t.filter(C=>C.daemonId===e.id&&C.transport==="acp"),M=e.p2p,S=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const C=sp(await r(e.id,"daemon_upgrade",{}));C.alreadyLatest?(c("done"),u(`Already on v${C.version||"latest"}.`)):C.upgraded||C.success?(c("done"),u(`Upgrade to v${C.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(C.error||"Upgrade failed"))}catch(C){c("error"),u(jn(C,"Connection lost during upgrade"))}}},j=async()=>{if(d(null),!!n){m("loading");try{await n(e.id),m("done"),k("Machine disconnected.")}catch(C){m("error"),k(jn(C,"Failed to disconnect"))}}},g=async()=>{if(d(null),!!a){m("loading");try{await a(e.id),m("done"),k("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(C){m("error"),k(jn(C,"Failed to revoke token"))}}},$="0.9.33",A=Oc(e,$),L=Gs(e,$),O=N.length+I.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:w}),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] ${A?"":"bg-bg-secondary"}`,style:A?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",p,!A&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&A&&s.jsx("button",{onClick:S,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${$}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${L?"↑ Update now":`↑ Update${` to v${$}`}`}`}),n&&s.jsx("button",{onClick:()=>d("disconnect"),disabled:h==="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:()=>d("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(Zf,{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:[M&&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 ${M.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${M.state==="connecting"||M.state==="new"?"animate-pulse":""}`,style:M.state==="connecting"||M.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",M.state==="connected"?"connected":M.state==="connecting"||M.state==="new"?"connecting...":M.state||"off"]}),M.peers!==void 0&&M.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",M.peers," peer",M.peers!==1?"s":"",")"]})]}),M&&O>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),O>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[N.map(C=>{const T=np(C.type),V=C.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:T.icon}),s.jsx("span",{children:T.name}),V!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${V?"bg-green-400":"animate-pulse"}`,style:V?void 0:{background:"var(--status-warning)"},title:V?"CDP connected":"CDP connecting..."})]},C.id)}),I.map(C=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:C.cliName||"CLI"})]},C.id)),y.map(C=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"🔗"}),s.jsx("span",{children:C.cliName||"ACP"})]},C.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||v)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||h==="error"?"text-red-400":i==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:v||l})]}),f==="disconnect"&&s.jsx(Wo,{title:"🔌 Disconnect Machine",message:`Disconnect "${w}" 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:()=>d(null)})]})}const op=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function ip(){const{preference:e,setPreference:t}=Wa();return s.jsx("div",{className:"flex gap-2",children:op.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 cp(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 lp(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function kn(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Fo(e){const{r:t,g:r,b:n}=lp(e);return .2126*kn(t)+.7152*kn(r)+.0722*kn(n)}function Ho(e,t){const r=Fo(e),n=Fo(t),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function Wc(e){const t=cp(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return Ho(t,r)>=Ho(t,n)?r:n}const ia={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},ca={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},dp=[{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"}}}],Fc="adhdev-chat-theme",Hc="adhdev-chat-theme-custom";function _r(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Fc)||"ember"}catch{return"ember"}}function _t(e){try{const t=localStorage.getItem(Hc);if(t){const r=JSON.parse(t);return{...e==="dark"?ia:ca,...r[e]}}}catch{}return e==="dark"?ia:ca}function vr(e,t){try{localStorage.setItem(Hc,JSON.stringify({dark:e,light:t}))}catch{}}function Ct(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 Gr(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 up={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function qs(e,t){var a;const r=(a=up[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",Gr(r,24)),n.style.setProperty("--accent-on-primary",Wc(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Gr(r,18)})`),n.style.setProperty("--border-accent",Ct(r,.35)),n.style.setProperty("--nav-active-bg",Ct(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Ct(r,.06)}`)}function rs(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Ct(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Ct(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Ct(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",Ct(e.borderSubtle,.5)),t.style.setProperty("--border-default",Ct(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Gr(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Wc(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Gr(e.accentColor,40)})`),t.style.setProperty("--border-accent",Ct(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Ct(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Ct(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 ${Ct(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 Fa(){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 mp(e){try{localStorage.setItem(Fc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ns()?"dark":"light";rs(_t(t))}else Fa(),qs(e,ns()?"dark":"light")}function fp(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=_r();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ns()?"dark":"light";rs(_t(t))}else Fa(),qs(e,ns()?"dark":"light")}function ns(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function ht({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 Bs({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 pp({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=o.useState(()=>_t(r));o.useEffect(()=>{a(_t(r))},[r]);const i=o.useCallback((c,l)=>{a(u=>{const f={...u,[c]:l},h=_t(r==="dark"?"light":"dark");return r==="dark"?vr(f,h):vr(h,f),rs(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(Bs,{title:"App Background",children:[s.jsx(ht,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(ht,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(ht,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(Bs,{title:"App Text",children:[s.jsx(ht,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(ht,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(ht,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(Bs,{title:"Borders & Accent",children:[s.jsx(ht,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(ht,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(ht,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Bs,{title:"Chat Bubbles",children:[s.jsx(ht,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(ht,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),s.jsx(ht,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(ht,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(Bs,{title:"Chat Layout",children:[s.jsx(ht,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(ht,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(ht,{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?ia:ca,u=_t(e?"light":"dark");e?vr(c,u):vr(u,c),a(c),rs(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 hp(){const[e,t]=o.useState(_r),[r,n]=o.useState(!0),[a,i]=o.useState(()=>_t("dark"));o.useEffect(()=>{n(ns());const u=new MutationObserver(()=>{const h=ns();n(h);const m=_r();m==="custom"?rs(_t(h?"dark":"light")):qs(m,h?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const f=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{const h=ns();n(h);const m=_r();m==="custom"?rs(_t(h?"dark":"light")):qs(m,h?"dark":"light")};return f.addEventListener("change",d),()=>{u.disconnect(),f.removeEventListener("change",d)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?rs(_t(r?"dark":"light")):(Fa(),qs(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(_t(r?"dark":"light"))},[r]);const c=u=>{t(u),mp(u)},l=[...dp,{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(u=>{const f=e===u.id,d=r?u.preview.dark:u.preview.light,h=u.id==="honey"||u.id==="ember"?"#1a1a1a":u.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>c(u.id),className:"text-left rounded-xl p-3 transition-all",style:{background:f?"var(--bg-glass-hover)":"var(--bg-glass)",border:f?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:f?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:d.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"Hello! How can I help?"}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.userBubble,color:h},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:d.assistantBubble,border:d.assistantBorder,color:d.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:u.id==="custom"?"🎨 Custom":u.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:u.description})]})]})]},u.id)})}),e==="custom"&&s.jsx(pp,{dark:r,onColorsChange:u=>i(u)})]})}const Ha="adhdev_mobileDashboardMode_v1",la="adhdev:mobile-dashboard-mode-change";function Ua(){try{return localStorage.getItem(Ha)==="workspace"?"workspace":"chat"}catch{return"chat"}}function xp(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??Ua())},r=a=>{const i=a.detail;t(i)},n=a=>{a.key&&a.key!==Ha||t()};return window.addEventListener(la,r),window.addEventListener("storage",n),()=>{window.removeEventListener(la,r),window.removeEventListener("storage",n)}}function bp(e){try{localStorage.setItem(Ha,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(la,{detail:e}))}function gp(){const[e,t]=o.useState(!0);return o.useEffect(()=>{t(Ua()==="chat")},[]),s.jsx(Jt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ft,{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),bp(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const Sn=new Map,Uo=new Map;function yp(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 vp(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 Uc(){const{sendCommand:e}=vt(),{injectEntries:t,getIdes:r}=Js();return o.useCallback(async(n,a)=>{if(!n)return;const i=(a==null?void 0:a.minFreshMs)??Rm,c=Uo.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<i)return;const l=Sn.get(n);if(l)return l;const u=(async()=>{const f=await e(n,"get_machine_runtime_stats"),d=yp(f);if(!d)return;const h=r().find(v=>v.id===n),m=vp(h,n,d.machine,d.timestamp||Date.now());t([m]),Uo.set(n,Date.now())})().finally(()=>{Sn.delete(n)});return Sn.set(n,u),u},[r,t,e])}function wp(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 jp(e,t){const{sendData:r}=vt(),{injectEntries:n,getIdes:a}=Js(),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(u=>Gt.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:t==null?void 0:t.intervalMs}},d=>{const h=a().find(v=>v.id===u),m=wp(h,u,d);n([m])}));return()=>{l.forEach(u=>u())}},[i,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function kp(e,t){const{sendData:r}=vt(),[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 u=Gt.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 u.initialSendAccepted?l=setTimeout(()=>{c(!1)},Em):c(!1),()=>{l&&clearTimeout(l),u()}},[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 Sp(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function zc(e){const{sendData:t}=vt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=Sp(e);if(!a||!e.sessionId||!t){n({});return}const i=Gt.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 Vc="adhdev_hiddenTabs";function Np(){try{const e=localStorage.getItem(Vc);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ps(e){try{localStorage.setItem(Vc,JSON.stringify([...e]))}catch{}}function Nn(e){return Ma(e)}function za(e,t){return ws(t).some(r=>e.has(r))}function Cp(){const[e,t]=o.useState(Np),r=o.useCallback(f=>{const d=Nn(f);t(h=>{const m=new Set(h);return m.has(d)?m.delete(d):m.add(d),ps(m),m})},[]),n=o.useCallback(f=>{const d=Nn(f);t(h=>{if(h.has(d))return h;const m=new Set(h);return m.add(d),ps(m),m})},[]),a=o.useCallback(f=>{const d=Nn(f);t(h=>{if(!h.has(d))return h;const m=new Set(h);return m.delete(d),ps(m),m})},[]),i=o.useCallback(()=>{t(f=>{if(f.size===0)return f;const d=new Set;return ps(d),d})},[]),c=o.useCallback((f,d)=>{t(h=>{const m=new Set(h);for(const v of d)m.add(v);return ps(m),m})},[]),l=o.useCallback((f,d)=>{t(h=>{const m=new Set(h);for(const v of d)m.delete(v);return ps(m),m})},[]),u=o.useCallback(f=>za(e,f),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function Gc(e){return e instanceof Error?e.message:String(e||"")}function qc(e){const t=Gc(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 Yc(e){const t=Gc(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Xc({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!et(e)||Je(e))return;const i=Rs(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:Bt(e),mode:t})}catch(l){const u=Yc(l);c&&!u&&a(f=>{const d={...f};return i===Jc(r,c)?delete d[c]:d[c]=i,d}),qc(l)?console.warn(u?"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 zo(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 Ip(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=zo(a,t),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>zo(u,t)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function Jc(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 Mp(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))Jc(t,a)===i&&(delete n[a],r=!0);return r?n:e}function Ap({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{sc()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:Sc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return qu(a),o.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{r(l=>{const u=Date.now(),f={};for(const[d,h]of Object.entries(l))u-h<5e3&&(f[d]=h);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 u=l.filter(f=>f.timestamp>c).slice(-100);return u.length===l.length?l:u})},6e4);return()=>clearInterval(i)},[n]),null}function Tp(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 Cn(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 Lp(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 Vo(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?Lp(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 Rp(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||""),Vo(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||""),Vo(r.activeChat)].join(":"))].join("|")}function _p(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 Pp(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 Dp(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Ep(e){const t=Dp(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 $p({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=o.useMemo(()=>Tp(e),[e]),i=o.useMemo(()=>Lc(e),[e]),c=o.useRef([]),l=o.useRef([]),u=o.useRef([]),f=o.useRef(new Map),d=o.useRef(new Map),h=o.useMemo(()=>{const I=new Map,y=[];for(const g of a){const{connectionState:$="new",machineName:A}=Rc(g,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),L=Rp(g),O=f.current.get(g.id);if(O&&O.ide===g&&O.sourceSignature===L&&O.connectionState===$&&O.machineName===A){I.set(g.id,O),y.push(...O.conversations);continue}const W=Oa(g,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),P={ide:g,sourceSignature:L,connectionState:$,machineName:A,conversations:W};I.set(g.id,P),y.push(...W)}f.current=I;const M=new Map,S=g=>{const $=Ep(g),A=d.current.get(g.tabKey);if(A&&A.signature===$)return M.set(g.tabKey,A),A.timestamp;const L={signature:$,timestamp:mc(g)||(A==null?void 0:A.timestamp)||0};return M.set(g.tabKey,L),L.timestamp},j=[...y].sort((g,$)=>fc(g,$,S));return d.current=M,j},[a,t,i]),m=o.useMemo(()=>{const I=_p(h,r);return Cn(c.current,I)?c.current:(c.current=I,I)},[h,r]),v=o.useMemo(()=>{const I=new Map,y=Array.from(new Set(m.map(M=>M.routeId)));for(const M of y){const S=Pt(m,M);S&&I.set(M,S)}return I},[m]),k=o.useMemo(()=>{const I=new Map;for(const y of m){const M=v.get(y.routeId),S=y.streamSource==="native"&&M?M:y;for(const j of ws({providerSessionId:y.providerSessionId,sessionId:y.sessionId}))I.set(j,S)}return I},[m,v]),p=o.useMemo(()=>Pp(m,v),[m,v]),x=o.useCallback(I=>{if(I)return k.get(I)},[k]),w=o.useCallback(I=>{if(I)return p.get(I)},[p]),b=o.useMemo(()=>{const I=m.filter(y=>!za(n,y));return Cn(l.current,I)?l.current:(l.current=I,I)},[m,n]),N=o.useMemo(()=>{const I=b.map(y=>y.tabKey);return Cn(u.current,I)?u.current:(u.current=I,I)},[b]);return{chatIdes:a,conversations:m,visibleConversations:b,visibleTabKeys:N,resolveConversationBySessionId:x,resolveConversationByTarget:w}}function Bp({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 u=new URLSearchParams(l);return u.delete("activeTab"),u},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function Kp({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){o.useEffect(()=>{it.setIdes(e)},[e]),o.useEffect(()=>{it.setResolveAction((a,i,c)=>{t(a,i,c).catch(()=>{})})},[t]),o.useEffect(()=>{const a=it.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(u=>u.id!==i.id)),c)});return()=>{a()}},[r]),o.useEffect(()=>{const a=wc.on("status_event",i=>{it.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 u=l.targetSessionId||l.targetKey||l.daemonId,f=n(u),d=(f==null?void 0:f.routeId)||l.daemonId;if(!d)return;const h=Number(l.buttonIndex),m=l.button||((p=f==null?void 0:f.modalButtons)==null?void 0:p[h])||"Approve",v=String(m).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(v);t(d,"resolve_action",{action:k?"approve":"reject",button:m,...Number.isFinite(h)&&{buttonIndex:h},...(f==null?void 0:f.sessionId)&&{targetSessionId:f.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(x=>console.error("[SW Action] approval failed:",x))};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 Op="adhdev_dashboardLayout_v1",Wp="adhdev_dashboardDockview_v1",Fp="adhdev_dashboardDockviewHiddenRestore_v1",Ks={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Va(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function Hp(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Qc(e){return`${Op}:${e}`}function Up(e){const t=Qc(e);return Va(t,null)}function zp(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=Qc(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Zc(e){return`${Wp}:${e}`}function Vp(e){const t=Zc(e);return Va(t,null)}function Gp(e,t){try{const r=Zc(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function el(e){return`${Fp}:${e}`}function qp(e){const t=el(e);return Va(t,{})}function Yp(e,t){try{const r=el(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Xp(){return{groupAssignments:[...Ks.groupAssignments],focusedGroup:Ks.focusedGroup,groupActiveTabIds:{...Ks.groupActiveTabIds},groupTabOrders:{...Ks.groupTabOrders},groupSizes:[...Ks.groupSizes]}}function Jp(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function Qp(){const[e]=o.useState(()=>Hp(typeof window<"u"?window.innerWidth:1280)),[t,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,u]=o.useState({}),[f,d]=o.useState([]),[h,m]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[v,k]=o.useState(!1),p=o.useCallback(()=>{if(v)return;const g=Up(e)??Xp();r(new Map(g.groupAssignments)),a(g.focusedGroup),c(g.groupActiveTabIds),u(g.groupTabOrders),d(g.groupSizes),k(!0)},[v,e]);o.useEffect(()=>{v&&zp(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)"),$=A=>m(A.matches);return g.addEventListener("change",$),()=>g.removeEventListener("change",$)},[]);const x=o.useCallback(g=>{r(g)},[]),w=o.useCallback(g=>{a(g)},[]),b=o.useCallback(g=>{c(g)},[]),N=o.useCallback(g=>{u(g)},[]),I=o.useCallback(g=>{d(g)},[]),y=o.useCallback(g=>{w(g)},[w]),M=o.useCallback((g,$)=>{c(A=>(A[g]??null)===($??null)?A:{...A,[g]:$})},[]),S=o.useCallback((g,$)=>{u(A=>{const L=A[g];return Jp(L,$)?A:{...A,[g]:$}})},[]),j=o.useCallback((g,$)=>{const A=$.get(g)??0;return M(A,g),y(A),A},[y,M]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:x,focusedGroup:n,updateFocusedGroup:w,focusGroup:y,groupActiveTabIds:i,updateGroupActiveTabIds:b,setGroupActiveTab:M,groupTabOrders:l,updateGroupTabOrders:N,setGroupTabOrder:S,groupSizes:f,updateGroupSizes:I,isMobile:h,hasHydratedStoredLayout:v,hydrateStoredLayout:p,focusConversationTab:j}}function Zp(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=Ia(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function eh({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,focusConversationTab:c,setSearchParams:l,historyModalOpen:u,activeConv:f,isRefreshingHistory:d,ides:h,handleRefreshHistory:m}){const v=o.useRef(!1),k=o.useRef(!1),p=o.useRef(null),x=o.useRef(!1);o.useEffect(()=>{if(!e||v.current||t.length===0)return;if(!a){i();return}const w=r(e);w&&(c(w.tabKey,n),v.current=!0,k.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(!(k.current||a)&&t.length!==0){if(!e){i(),k.current=!0;return}if(v.current){k.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(k.current||a)&&(i(),k.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,t.length,a,i]),o.useEffect(()=>{if(!u){x.current=!1;return}if(!f||x.current||d)return;const w=h.find(b=>b.id===f.routeId);w&&(!w.chats||w.chats.length===0||Zp(w.chats,f))&&(x.current=!0,m())},[u,f,d,h,m]),o.useEffect(()=>{if(!f)return;let w=null,b=0,N=-1,I=0;const y=()=>{w=null;const M=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(j=>j.offsetParent!==null);if(M.length===0){b<18&&(b+=1,w=requestAnimationFrame(y));return}let S=0;for(const j of M)j.scrollTop=j.scrollHeight,S+=j.scrollHeight;S===N?I+=1:(I=0,N=S),b+=1,!(I>=2||b>=18)&&(w=requestAnimationFrame(y))};return w=requestAnimationFrame(y),()=>{w!=null&&cancelAnimationFrame(w)}},[f==null?void 0:f.tabKey])}function In(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=Ia(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function tl({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:i}){const[c,l]=o.useState(!1),[u,f]=o.useState(!1),d=o.useCallback(async k=>{try{await e("standalone","launch_ide",{ideType:k,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),h=o.useCallback(async(k,p)=>{try{const x=k||(t==null?void 0:t.daemonId)||"",w=await e(x,"switch_chat",{id:p,sessionId:p,...js(t)}),b=w==null?void 0:w.result;if((w==null?void 0:w.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?$s(a,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?$s(a,`⚠️ Switch error: ${b}`):$s(a,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),$s(a,`❌ Switch failed: ${x.message||"connection error"}`)}},[t,e,a]),m=o.useCallback(async()=>{if(!(!t||c)){l(!0);try{const k=tr(t);await e(k,"new_chat",{...js(t)}),i(p=>({...p,[t.tabKey]:Date.now()}))}catch(k){console.error("New chat failed",k)}finally{l(!1)}}},[t,c,e,i]),v=o.useCallback(async()=>{var k,p;if(!(!t||u)){f(!0);try{const x=tr(t),w=async()=>e(x,"list_chats",{forceExpand:!0,...js(t)});let b=await w(),N=(b==null?void 0:b.chats)||((k=b==null?void 0:b.result)==null?void 0:k.chats);In(N,t)&&(await new Promise(I=>setTimeout(I,450)),b=await w(),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),In(N,t)&&!In(r,t)&&$s(a,"⚠️ History dialog did not fully open — try once more"))}catch(x){console.error("Refresh history failed",x)}finally{f(!1)}}},[t,r,u,e,n,a]);return{isCreatingChat:c,isRefreshingHistory:u,handleLaunchIde:d,handleSwitchSession:h,handleNewChat:m,handleRefreshHistory:v}}function th(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 sh(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function Go(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 wr(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 u=a[l];typeof u=="number"&&u>0&&i.set(c,u)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function qo(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 rh(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 nh(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 Yo(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 Xo(e){return Array(e).fill(100/e)}function ah({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:i,updateGroupSizes:c,isMobile:l,visibleConversations:u,visibleTabKeys:f}){const d=o.useRef(null),h=o.useMemo(()=>wr(e,f),[e,f]),m=h.assignments,v=o.useMemo(()=>l?1:h.groupCount,[h.groupCount,l]),k=v>1,p=o.useCallback((y,M)=>{t(S=>{const j=new Map(wr(S,f).assignments);return M===0?j.delete(y):j.set(y,M),j}),n(S=>({...S,[M]:y})),r(M)},[t,f,n,r]),x=o.useCallback(y=>{t(M=>{const S=wr(M,f).assignments,j=new Map;for(const[g,$]of S)$!==y&&($>y?j.set(g,$-1):j.set(g,$));return j}),c(M=>{if(M.length<=1)return[];const S=[...M];S.splice(y,1);const j=S.reduce((g,$)=>g+$,0);return j>0?S.map(g=>g/j*100):[]}),r(0)},[t,f,c,r]),w=o.useCallback((y,M)=>{M.preventDefault();const S=d.current;if(!S)return;const j=M.clientX,g=S.offsetWidth,$=i.length===v?[...i]:Xo(v),A=O=>{const P=(O.clientX-j)/g*100,C=[...$];C[y]=Math.max(15,$[y]+P),C[y+1]=Math.max(15,$[y+1]-P),c(C)},L=()=>{document.removeEventListener("mousemove",A),document.removeEventListener("mouseup",L),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",A),document.addEventListener("mouseup",L)},[i,v,c]),b=o.useCallback((y,M,S)=>{if(v>=4)return;const j=S==="left"?M:M+1;t(g=>{const $=wr(g,f).assignments,A=new Map;for(const L of u){const O=$.get(L.tabKey)??0,W=O>=j?O+1:O;W>0&&A.set(L.tabKey,W)}return j>0&&A.set(y,j),A}),c(g=>{const $=g.length===v?[...g]:Xo(v),A=$[M]??100/v,L=Math.max(15,A/2),O=Math.max(15,A/2),W=[...$];W[M]=L,W.splice(j,0,O);const P=W.reduce((C,T)=>C+T,0);return W.map(C=>C/P*100)}),n(g=>{const $=Yo(g,j);return $[j]=y,$}),a(g=>{const $=Yo(g,j);return $[j]=[y],$}),r(j)},[v,t,f,u,c,n,a,r]);o.useEffect(()=>{th(e,m)||t(m)},[e,m,t]),o.useEffect(()=>{const{mapping:y,usedGroups:M}=h;n(S=>{const j=qo(S,y);return Go(S,j)?S:j}),a(S=>{const j=qo(S,y);return Go(S,j)?S:j}),r(S=>{const j=l?0:rh(S,M,y);return S===j?S:j}),c(S=>{const j=l?[]:nh(S,M,h.groupCount);return sh(S,j)?S:j})},[h,l,n,a,r,c]);const N=o.useMemo(()=>{const y=Array.from({length:v},()=>[]);for(const M of u){const S=m.get(M.tabKey)??0,j=Math.min(S,v-1);y[j].push(M)}return y},[u,m,v]),I=o.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:d,normalizedGroupAssignments:m,numGroups:v,isSplitMode:k,groupedConvs:N,moveTabToGroup:p,closeGroup:x,handleResizeStart:w,splitTabRelative:b,clearAllSplits:I}}function oh({ides:e,sendDaemonCommand:t}){const r="0.9.31",n=o.useMemo(()=>e.filter(d=>d.type!=="adhdev-daemon"?!1:Oc(d,r)).sort((d,h)=>Number(Gs(h,r))-Number(Gs(d,r))),[r,e]),a=o.useMemo(()=>n.some(d=>Gs(d,r)),[r,n]),[i,c]=o.useState(!1),[l,u]=o.useState({}),f=o.useCallback(async d=>{var h,m;u(v=>({...v,[d]:"upgrading"}));try{const v=await t(d,"daemon_upgrade",{});(h=v==null?void 0:v.result)!=null&&h.upgraded||(m=v==null?void 0:v.result)!=null&&m.success?u(k=>({...k,[d]:"done"})):u(k=>({...k,[d]:"error"}))}catch{u(v=>({...v,[d]:"error"}))}},[t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:f}}const sl=80;function Pr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function ih(e){return{...e,createdAt:Pr(e.createdAt),updatedAt:Pr(e.updatedAt,e.createdAt),lastEventAt:Pr(e.lastEventAt,e.updatedAt||e.createdAt)}}function ch(e){const t=Ma(e);return t==="unknown:"?e.id:t}function lh(e){return[e.type,uc(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function dh(e,t=sl){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=ch(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 uh(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=Zr(a,t),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const u=Pr(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),f=lh({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(ih({id:f,dedupKey:f,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:ic(a),preview:gm(a),createdAt:u,updatedAt:u,lastEventAt:u}))}return dh(n)}function mh(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function fh(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=sl}=e,a=o.useMemo(()=>uh(t,r).slice(0,Math.max(0,n)),[t,r,n]),i=o.useMemo(()=>mh(a),[a]);return{notifications:a,unreadCount:i}}function ph({notifications:e,sendDaemonCommand:t}){const r=o.useCallback(i=>{const c=e.find(u=>u.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 sn(...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 hh(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 rn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=hh(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 xh(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 bh(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function nn(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=bh(n);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(n==null?void 0:n.error)||"Could not browse folder");const i=typeof(a==null?void 0:a.path)=="string"?a.path:r,c=i.includes("\\")?"\\":"/",l=(f,d)=>/^[A-Za-z]:\\?$/.test(f)?`${f.replace(/\\?$/,"\\")}${d}`:f==="/"||f==="\\"?`${c}${d}`:`${f.replace(/[\\/]+$/,"")}${c}${d}`,u=Array.isArray(a==null?void 0:a.files)?a.files.filter(f=>(f==null?void 0:f.type)==="directory"&&typeof(f==null?void 0:f.name)=="string").map(f=>({name:f.name,path:typeof(f==null?void 0:f.path)=="string"&&f.path.trim()?f.path:l(i,f.name)})).sort((f,d)=>f.name.localeCompare(d.name)):[];return{path:i,directories:u}}function gh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Jo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function yh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function vh({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=Jo(n.workspacePath),l=e.find(f=>{var k,p,x,w;if(!f||f.type==="adhdev-daemon"||gh(f.daemonId||f.id)!==n.machineId||(er(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=Jo(f.workspace||f.runtimeWorkspaceLabel);return b?b===c:!1}return Number(f.lastUpdated||f._lastUpdate||f.timestamp||((w=(x=(p=(k=f.activeChat)==null?void 0:k.messages)==null?void 0:p.at)==null?void 0:x.call(p,-1))==null?void 0:w.timestamp)||0)>=n.startedAt-5e3});if(!l)return;const u=pc({entrySessionId:l.sessionId,entryInstanceId:l.instanceId,entryRouteId:l.id,conversations:t});u&&(a(null),r(u))},[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 wh({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:i}){const c=o.useCallback(async(m,v)=>nn(e,m,v),[e]),l=o.useCallback(async(m,v)=>{if(!v.trim())return{ok:!1,error:"Choose a workspace path first."};try{const k=await e(m,"workspace_add",{path:v.trim()});return k!=null&&k.success?{ok:!0}:{ok:!1,error:(k==null?void 0:k.error)||"Could not save workspace"}}catch(k){return{ok:!1,error:k instanceof Error?k.message:"Could not save workspace"}}},[e]),u=o.useCallback(async(m,v,k)=>{var p;try{const x={ideType:v,enableCdp:!0};(p=k==null?void 0:k.workspacePath)!=null&&p.trim()&&(x.workspace=k.workspacePath.trim());const w=await e(m,"launch_ide",x);return!(w!=null&&w.success)&&(w==null?void 0:w.success)!==void 0?{ok:!1,error:(w==null?void 0:w.error)||"Could not launch IDE"}:(t({machineId:m,kind:"ide",providerType:v,workspacePath:(k==null?void 0:k.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(x){return{ok:!1,error:x instanceof Error?x.message:"Could not launch IDE"}}},[e,t]),f=o.useCallback(async(m,v,k,p)=>{var w,b,N;const x=Date.now();try{const I={cliType:k};(w=p==null?void 0:p.workspacePath)!=null&&w.trim()?I.dir=p.workspacePath.trim():p!=null&&p.workspaceId&&(I.workspaceId=p.workspaceId),(b=p==null?void 0:p.resumeSessionId)!=null&&b.trim()&&(I.resumeSessionId=p.resumeSessionId.trim()),Array.isArray(p==null?void 0:p.cliArgs)&&p.cliArgs.length>0&&(I.cliArgs=p.cliArgs),(N=p==null?void 0:p.initialModel)!=null&&N.trim()&&(I.initialModel=p.initialModel.trim());const y=await e(m,"launch_cli",I),M=(y==null?void 0:y.result)||y,S=(M==null?void 0:M.sessionId)||(M==null?void 0:M.id);return y!=null&&y.success&&S?(r(S),{ok:!0}):y!=null&&y.success?(t({machineId:m,kind:v,providerType:k,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:x}),{ok:!0}):{ok:!1,error:(y==null?void 0:y.error)||(M==null?void 0:M.error)||`Could not launch ${v.toUpperCase()} session`}}catch(I){return yh(I)?(t({machineId:m,kind:v,providerType:k,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:x}),{ok:!0}):{ok:!1,error:I instanceof Error?I.message:`Could not launch ${v.toUpperCase()} session`}}},[r,e,t]),d=o.useCallback(async(m,v)=>{if(!m||!v)return[];try{const k=await e(m,"list_saved_sessions",{providerType:v,kind:"cli",limit:30}),p=(k==null?void 0:k.result)??k;return Array.isArray(p==null?void 0:p.sessions)?p.sessions:[]}catch(k){return console.error("List saved sessions failed",k),[]}},[e]),h=o.useCallback(async m=>{await Xc({conversation:n,mode:m,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:i})},[n,a,e,i]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:l,handleLaunchMachineIde:u,handleLaunchMachineProvider:f,handleListMachineSavedSessions:d,setActiveCliViewMode:h}}function jh(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 kh(e,t,r=Date.now()){return!e||!jh(t)?null:{tabKey:e,nonce:r}}function Sh({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:i,setSearchParams:c}){const[l,u]=o.useState(null),[f,d]=o.useState(null),h=o.useMemo(()=>{var x,w;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((x=i[a])==null?void 0:x[0])||((w=i[0])==null?void 0:w[0])},[t,l,a,n,i,e,r]),m=o.useCallback(p=>{u(p)},[]),v=o.useCallback(p=>{u(p.tabKey),c(x=>{const w=new URLSearchParams(x),b=vm(p);return b?w.set("activeTab",b):w.delete("activeTab"),w},{replace:!0})},[c]),k=o.useCallback((p,x)=>{const w=kh(p,x);w&&d(w)},[]);return{activeConv:h,openDesktopConversation:v,requestScrollToBottom:k,scrollToBottomRequest:f,setDesktopActiveTab:m}}function Nh({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:i,setToasts:c,setClearedTabs:l,setSearchParams:u}){var C;const[f,d]=o.useState(!1),[h,m]=o.useState([]),[v,k]=o.useState(()=>pt()),[p,x]=o.useState(!1),[w,b]=o.useState(null),N=o.useRef(null),I=o.useMemo(()=>r||t||e,[e,r,t]),y=!!I&&et(I)&&!Je(I),M=o.useMemo(()=>{if(!I||!y)return null;const T=I.daemonId||I.routeId||"",V=Bt(I);return`${T}:${V}`},[I,y]),{isCreatingChat:S,isRefreshingHistory:j,handleSwitchSession:g,handleNewChat:$,handleRefreshHistory:A}=tl({sendDaemonCommand:a,activeConv:I,chats:(C=n.find(T=>T.id===(I==null?void 0:I.routeId)))==null?void 0:C.chats,updateRouteChats:i,setToasts:c,setClearedTabs:l}),L=o.useCallback(()=>{d(!0)},[]),O=o.useCallback(()=>{d(!1)},[]),W=o.useCallback(async()=>{if(!(!I||!y||p)){x(!0);try{const T=I.daemonId||I.routeId,V=Bt(I),E=await a(T,"list_saved_sessions",{agentType:V,providerType:V,kind:"cli",limit:50}),_=(E==null?void 0:E.result)??E;m(Array.isArray(_==null?void 0:_.sessions)?_.sessions:[])}catch(T){console.error("Refresh saved sessions failed",T),m([])}finally{x(!1)}}},[I,p,y,a]);o.useEffect(()=>{if(!f){N.current=null;return}if(!y){N.current=null,m([]),x(!1);return}!M||p||N.current!==M&&(N.current=M,W())},[W,f,p,y,M]);const P=o.useCallback(async T=>{if(!I||!y||!T.providerSessionId||!T.workspace)return;const V=I.daemonId||I.routeId,E=Bt(I);try{b(T.providerSessionId);const _=await a(V,"launch_cli",{cliType:E,dir:T.workspace,resumeSessionId:T.providerSessionId,initialModel:ec(T.summaryMetadata,"model",{preferShortValue:!0})||void 0}),F=(_==null?void 0:_.result)??_,J=typeof(F==null?void 0:F.sessionId)=="string"?F.sessionId:typeof(F==null?void 0:F.id)=="string"?F.id:"";J&&u(xe=>{const ce=new URLSearchParams(xe);return ce.set("activeTab",J),ce},{replace:!0}),O()}catch(_){console.error("Resume saved session failed",_)}finally{b(null)}},[O,I,y,a,u]);return{historyModalOpen:f,openHistoryModal:L,closeHistoryModal:O,historyTargetConv:I,isSavedSessionHistoryTarget:y,isHistoryCreatingChat:S,isHistoryRefreshingHistory:j,handleHistorySwitchSession:g,handleHistoryNewChat:$,handleHistoryRefresh:A,savedHistorySessions:h,savedHistoryFilters:v,setSavedHistoryFilters:k,isSavedHistoryLoading:p,resumingSavedHistorySessionId:w,handleRefreshSavedHistory:W,handleResumeSavedHistorySession:P}}function Ch({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[u,f]=o.useState(null),[d,h]=o.useState(null),m=o.useMemo(()=>{if(e||!n)return null;const w=l(n);return w&&!et(w)&&!Je(w)?w:null},[e,n,l]),v=o.useMemo(()=>{const w=u==null?void 0:u.routeId;if(!w)return null;const b=u!=null&&u.tabKey?i.find(N=>N.tabKey===u.tabKey):a?i.find(N=>N.tabKey===a):null;return(b==null?void 0:b.routeId)===w?b:Pt(i,w)},[i,u,a]),k=o.useMemo(()=>{if(v)return c.find(w=>w.id===v.routeId)},[c,v]);o.useEffect(()=>{m&&(f({routeId:m.routeId,tabKey:Ao(m)}),h(m),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,m]);const p=o.useCallback(w=>{w&&(f({routeId:w.routeId,tabKey:Ao(w)}),h(w))},[]),x=o.useCallback(()=>{f(null),h(null)},[]);return{remoteDialogConv:v,remoteDialogIdeEntry:k,remoteDialogActiveConv:d,setRemoteDialogActiveConv:h,openRemoteDialog:p,closeRemoteDialog:x}}function Ih({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l,activeConv:u,sendDaemonCommand:f}){const{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:m,setRemoteDialogActiveConv:v,openRemoteDialog:k,closeRemoteDialog:p}=Ch({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}),[x,w]=o.useState(!1),[b,N]=o.useState(null),I=o.useCallback(async S=>{const j=S||u;!j||!et(j)&&!Je(j)||(N(j),w(!0))},[u]),y=o.useCallback(()=>{w(!1),N(null)},[]),M=o.useCallback(async S=>{const j=b||u;if(!j||!et(j)&&!Je(j)){y();return}w(!1);try{const g=Bt(j),$=j.routeId||j.daemonId||"";await f($,"stop_cli",{cliType:g,targetSessionId:j.sessionId,mode:S})}catch(g){console.error("Stop CLI failed:",g)}finally{N(null)}},[u,y,b,f]);return{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:m,setRemoteDialogActiveConv:v,openRemoteDialog:k,closeRemoteDialog:p,cliStopDialogOpen:x,cliStopTargetConv:b,requestCliStop:I,cancelCliStop:y,confirmCliStop:M}}function rl(){return"select_session"}function Mh(){return"open_panel"}function Ah({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function Th(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function Qo(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function Zo(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Ga(e){return e instanceof Error?e.message:String(e||"")}function ei(e){const t=Ga(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function ti(e,t){const r=Ga(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function an({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,i]=o.useState(!1),[c,l]=o.useState(!1),[u,f]=o.useState(null),d=o.useRef(!1),h=o.useRef(null);o.useEffect(()=>{f(null)},[t==null?void 0:t.tabKey]);const m=o.useCallback(async x=>{if(!t)return!1;const w=x.trim(),b=La(t);if(Ah({hasMessage:!!w,blockedMessage:b,sendInFlight:d.current}))return b&&f(b),!1;const N=Date.now(),I={tabKey:t.tabKey,message:w,timestamp:N};if(Th(h.current,I))return f(null),!0;d.current=!0,l(!0),f(null),h.current=I;try{const y=tr(t);if(!y)return h.current=Qo(h.current,I),f("Unable to send message right now."),!1;const M=await e(y,"send_chat",{message:w,...js(t)}),S=Zo(M);if(S!=null&&S.deduplicated)return f(null),!0;if((S==null?void 0:S.sent)===!1)throw new Error((S==null?void 0:S.error)||"Send failed");if((S==null?void 0:S.success)===!1)throw new Error((S==null?void 0:S.error)||"Send failed");return f(null),!0}catch(y){const M=Ga(y);return M.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",M):console.warn("Send blocked/failed",y),h.current=Qo(h.current,I),f(Km(y)),!1}finally{d.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(x){console.error("Relaunch failed",x)}},[t,e]),k=o.useCallback(async x=>{if(t)try{const b=(t.modalButtons||[]).indexOf(x),N=x.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),I=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(N),y=tr(t);if(!y)return;const M=await e(y,"resolve_action",{button:x,action:I?"approve":"reject",...b>=0&&{buttonIndex:b},...js(t)}),S=Zo(M);S.success||r(j=>[...j,{routeId:t.tabKey,text:ti(x,S==null?void 0:S.error),timestamp:Date.now()}])}catch(w){ei(w)||console.error("[ModalButton] Error:",w),r(b=>[...b,{routeId:t.tabKey,text:ei(w)?ti(x,w):`❌ **${x}** error`,timestamp:Date.now()}])}},[t,e,r]),p=o.useCallback(async()=>{if(!(!t||a)){i(!0);try{await e(t.routeId,Mh(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(x){console.error("Focus agent failed",x)}finally{i(!1)}}},[t,a,e]);return{isSendingChat:c,sendFeedbackMessage:u,isFocusingAgent:a,handleSendChat:m,handleRelaunch:v,handleModalButton:k,handleFocusAgent:p}}function Mn(e,t=!0){return(e??!0)&&t}const qa=o.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d=null,handleFocusAgent:h,isFocusingAgent:m,actionLogs:v,userName:k,scrollToBottomRequestNonce:p,isInputActive:x=!0,isVisible:w=!0}){const[b,N]=o.useState(n),I=o.useRef(n);o.useEffect(()=>{const L=I.current;if(I.current=n,!n){N(!1);return}if(L){N(!0);return}N(!1);let O=0,W=0;return O=window.requestAnimationFrame(()=>{W=window.requestAnimationFrame(()=>{N(!0)})}),()=>{window.cancelAnimationFrame(O),window.cancelAnimationFrame(W)}},[n]);const y=n&&b,M=!n||!b,S=Mn(w,n),j=Mn(w,M),g=Mn(w),$=zc(t),A=$.status||$.modalMessage||$.modalButtons?{...t,...$.status?{status:$.status}:{},...$.modalMessage!==void 0?{modalMessage:$.modalMessage}:{},...$.modalButtons!==void 0?{modalButtons:$.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(Yi,{activeConv:A,onModalButton:c}),A.transport!=="pty"&&A.transport!=="acp"&&A.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(Qs,{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,A.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(gf,{activeConv:A,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,isVisible:S,isInputActive:x&&S})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:M?"visible":"hidden",pointerEvents:M?"auto":"none"},children:s.jsx(aa,{activeConv:A,ideEntry:a,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:m,actionLogs:v,userName:k,scrollToBottomRequestNonce:p,isInputActive:x&&j,isVisible:j})})]}):s.jsx(aa,{activeConv:A,ideEntry:a,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:m,actionLogs:v,userName:k,scrollToBottomRequestNonce:p,isInputActive:x&&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 Lh({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:u,onBack:f,onOpenNativeConversation:d,onOpenMachine:h,onOpenHistory:m,onOpenRemote:v,onHideConversation:k,onStopCli:p,cliViewMode:x,onSetCliViewMode:w,handleSendChat:b,handleFocusAgent:N,handleModalButton:I,handleRelaunch:y}){const M=o.useRef(null),S=et(e)&&!t,j=S&&x==="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(ga,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:at(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(hc,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>h(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[S&&x&&s.jsx(Pa,{mode:x,onChange:w,compact:!0}),S&&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(yt,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>m(e),type:"button",children:s.jsx(ya,{size:14})}),!t&&!S&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>v(e),type:"button",children:s.jsx(St,{size:14})}),k&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>k(e),type:"button",title:"Close chat",children:s.jsx(yt,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(qa,{activeConv:e,clearToken:0,isCliTerminal:j,ideEntry:n,terminalRef:M,handleModalButton:I,handleRelaunch:y,handleSendChat:b,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:N,isFocusingAgent:u,actionLogs:a,userName:i})})]})}const An={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 Rh(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function nl(){const[e,t]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{t(Rh())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(An[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:An[c].prompt}),s.jsx("span",{className:"flex-1 break-all",children:An[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 al({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:St},{key:"chats",label:"Chats",icon:Ft}];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 jr({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 Os({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 kr({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:u,isConnecting:f}=Ls(e.conversation),d=at(e.conversation),h=ds(e.conversation),m=kc(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",k=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",x=c?"text-text-muted":"text-text-secondary",w=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 ${k}`,style:a?{color:"var(--accent-on-primary)"}:void 0,children:r(d)}),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:d}),!i&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${b}`,children:qi(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${x}`,children:[h,u?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] ${w}`,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 si({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 _h({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:u,onShowConversation:f,onShowAllHidden:d,onOpenNewSession:h,onOpenMachine:m,onOpenSettings:v,onSectionChange:k,wsStatus:p="connected",isStandalone:x=!1}){const w=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,I=e==="machines"?"Machines":"Chats",y=x?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",M=x?"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:I}),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(Jr,{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(Xr,{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] ${M}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:w?s.jsx(Os,{icon:s.jsx(si,{label:"Reconnecting…"}),title:p==="offline"?"Network offline":p==="auth_failed"?"Session expired":"Reconnecting",subtitle:p==="offline"?"Waiting for network…":p==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):c.length===0?s.jsx(Os,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:x?"Waiting for your daemon":"Connect your machines",subtitle:x?"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:!x&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(nl,{})})}):s.jsx(hs,{children:c.map((S,j)=>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] ${j>0?"border-t border-border-subtle/70":""}`,onClick:()=>m(S.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(S.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:S.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:S.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[S.unread," new"]}):S.total>0?`${S.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:S.subtitle}),S.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[S.total," chat",S.total!==1?"s":"",S.unread>0?` · ${S.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},S.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(jr,{title:"Needs attention",className:"mb-0"}),s.jsx(hs,{children:t.map((S,j)=>s.jsx("div",{className:j>0?"border-t border-border-subtle/70":"",children:s.jsx(kr,{item:S,type:"needs_attention",getAvatarText:l,onOpenConversation:u})},S.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(jr,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(hs,{children:r.map((S,j)=>s.jsx("div",{className:j>0?"border-t border-border-subtle/70":"",children:s.jsx(kr,{item:S,type:"task_complete",getAvatarText:l,onOpenConversation:u})},S.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(jr,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(hs,{children:n.map((S,j)=>s.jsx("div",{className:j>0?"border-t border-border-subtle/70":"",children:s.jsx(kr,{item:S,type:"working",getAvatarText:l,onOpenConversation:u})},S.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(jr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(hs,{children:a.map((S,j)=>s.jsx("div",{className:j>0?"border-t border-border-subtle/70":"",children:s.jsx(kr,{item:S,type:"earlier",getAvatarText:l,onOpenConversation:u})},S.conversation.tabKey))}):N?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):w?s.jsx(Os,{icon:s.jsx(si,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):b?s.jsx(Os,{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(Ft,{size:20})}),title:"No conversations yet",subtitle:Cc,children:h&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:h,"aria-label":Et,title:Et,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:Et})]})}):s.jsx(Os,{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:d,children:"Restore all"})]}),s.jsx(hs,{className:"bg-bg-secondary/25",children:i.map((S,j)=>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 ${j>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(S),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(at(S))}),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:at(S)}),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:ds(S)}),s.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},S.tabKey))})]})]}),e==="chats"&&h&&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:h,"aria-label":Et,title:Et,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(al,{section:e,onSectionChange:k})]})}function Ph(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 ol(e){const t=[e.workspace||"Workspace unknown"],r=ls(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=Ph(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function on({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:u,onConfirm:f}){const[d,h]=o.useState(r);o.useEffect(()=>{h(r)},[r]);const m=xh(r),v=d.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(yt,{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||u(m)},disabled:!m||a,children:[s.jsx(ga,{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:d,onChange:k=>h(k.target.value),onKeyDown:k=>{k.key!=="Enter"||!v||a||(k.preventDefault(),u(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||u(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(k=>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:()=>u(k.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:k.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:k.path})]})]},k.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 Ya({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:u=!1,showArgsInput:f,argsValue:d,onArgsChange:h,showModelInput:m,modelValue:v,onModelChange:k,historyProviderNode:p,onConfirm:x,onCancel:w}){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:w,"aria-label":"Close launch confirmation",children:s.jsx(yt,{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:u,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&&k&&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=>k(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:u})]}),f&&h&&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:d||"",onChange:N=>h(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:u})]})]}),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:w,disabled:u,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:x,disabled:u,children:[s.jsx(wa,{size:14}),u?l:c]})]})]})})}function ri(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function as(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 u of t.workspaces||[])i.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${ri(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const c=(r==null?void 0:r.trim())||"",l=c?(t.workspaces||[]).find(u=>u.path===c):null;if(c&&!l&&i.push({key:`custom:${c}`,label:ri(c),description:c,workspaceId:null,workspacePath:c}),n){const u=`saved:${n}`;if(i.some(f=>f.key===u))return{options:i,selectedKey:u}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function Dh(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Eh(e){return[Dh(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function $h(e){return e.lastLaunchedAt?Qr(e.lastLaunchedAt):""}function il(e){return{metaText:Eh(e),updatedLabel:$h(e)}}function Tn(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function Bh({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var ct,mt,lt,ut;const c=or(),[l,u]=o.useState(!1),f=(((ct=e.detectedIdes)==null?void 0:ct.length)||0)>0,d=o.useMemo(()=>(e.workspaces||[]).map(Ie=>({id:Ie.id,path:Ie.path,label:Ie.label})),[e]),h=e.defaultWorkspaceId||null,[m,v]=o.useState(h||((mt=d[0])==null?void 0:mt.id)||""),[k,p]=o.useState(""),[x,w]=o.useState(""),[b,N]=o.useState([]),[I,y]=o.useState(!1),[M,S]=o.useState(""),[j,g]=o.useState(!1),[$,A]=o.useState(Tn(f,t.length,r.length)),L=o.useRef(null),[O,W]=o.useState(null),P=o.useRef("__home__"),[C,T]=o.useState("__home__"),[V,E]=o.useState(""),[_,F]=o.useState(""),[J,xe]=o.useState(""),[ce,te]=o.useState([]),[be,ge]=o.useState(()=>pt().textQuery),[ve,H]=o.useState(()=>pt().workspaceQuery),[U,Q]=o.useState(()=>pt().modelQuery),[de,ne]=o.useState(()=>pt().resumableOnly),[fe,ae]=o.useState(()=>pt().sortMode),[pe,le]=o.useState(!1),[ue,oe]=o.useState(!1),ye=o.useRef(null),he=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const ke=m==="__custom__"?k.trim():((lt=d.find(Ie=>Ie.id===m))==null?void 0:lt.path)||"",D=m==="__custom__"&&!!ke&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),Y=m!=="__custom__"&&((ut=d.find(Ie=>Ie.id===m))==null?void 0:ut.path)||"",G=o.useMemo(()=>(e.recentLaunches||[]).map(Ie=>Ie.workspace),[e]),X=o.useCallback(async Ie=>{y(!0),S("");try{const Ee=await a(Ie);w(Ee.path),p(Ee.path),N(Ee.directories)}catch(Ee){S(Ee instanceof Error?Ee.message:"Could not load folder")}finally{y(!1)}},[a]),re=o.useCallback(()=>{var Ee;v("__custom__"),g(!0);const Ie=rn(e.platform,sn(k.trim(),Y,G,e.defaultWorkspacePath,(Ee=d.find(Qe=>Qe.id===h))==null?void 0:Ee.path,d.map(Qe=>Qe.path)));X(Ie)},[k,h,X,G,Y,e.platform,d]),Se=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("")},[]),Ae=o.useCallback(Ie=>{if(v(Ie),Ie==="__custom__"){re();return}p("")},[re]),$e=o.useCallback(Ie=>{v("__custom__"),p(Ie)},[]),Be=o.useCallback((Ie,Ee)=>{L.current=Ee,P.current=Ie.selectedWorkspaceKey||"__home__",T(Ie.selectedWorkspaceKey||"__home__"),E(Ie.initialArgs||""),F(Ie.initialModel||""),xe(""),te([]);const Qe=Ie.providerType?`${e.id}:${Ie.providerType}`:null;if(Nf(he.current,Qe)){const Ve=pt();ge(Ve.textQuery),H(Ve.workspaceQuery),Q(Ve.modelQuery),ne(Ve.resumableOnly),ae(Ve.sortMode)}he.current=Qe,W(Ie),Ie.providerType&&i&&(le(!0),i(Ie.providerType).then(Ve=>te(Ve||[])).catch(Ve=>console.warn("Failed to load saved sessions",Ve)).finally(()=>le(!1)))},[i,e.id]),Ke=o.useMemo(()=>Ic(ce,{textQuery:be,workspaceQuery:ve,modelQuery:U,resumableOnly:de,sortMode:fe}),[U,de,ce,fe,be,ve]);o.useEffect(()=>{J&&(Ke.some(Ie=>Ie.providerSessionId===J)||xe(""))},[Ke,J]);const qe=o.useCallback(()=>{L.current&&(oe(!0),L.current().finally(()=>{L.current=null,oe(!1),W(null)}))},[]),ze=o.useCallback(()=>{L.current=null,W(null)},[]),rt=o.useCallback(Ie=>{P.current=Ie,T(Ie)},[]);return o.useEffect(()=>{var Ie;ye.current!==e.id&&(ye.current=e.id,v(h||((Ie=d[0])==null?void 0:Ie.id)||"__custom__"),p(""),w(""),N([]),S(""),g(!1),ge(pt().textQuery),H(pt().workspaceQuery),Q(pt().modelQuery),ne(pt().resumableOnly),ae(pt().sortMode),he.current=null,A(Tn(f,t.length,r.length)))},[r.length,t.length,h,f,e.id,d]),o.useEffect(()=>{var Ie;m!=="__custom__"&&(m&&d.some(Ee=>Ee.id===m)||v(h||((Ie=d[0])==null?void 0:Ie.id)||"__custom__"))},[h,m,d]),o.useEffect(()=>{$==="ide"&&f||$==="cli"&&t.length>0||$==="acp"&&r.length>0||A(Tn(f,t.length,r.length))},[$,r.length,t.length,f]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:f,workspaceRows:d,defaultWorkspaceId:h,workspaceChoice:m,customWorkspacePath:k,browseCurrentPath:x,browseDirectories:b,browseBusy:I,browseError:M,browseDialogOpen:j,activeLauncherKind:$,launchConfirm:O,launchConfirmWorkspaceKeyRef:P,launchConfirmWorkspaceKey:C,launchConfirmArgs:V,launchConfirmModel:_,launchConfirmResumeId:J,launchConfirmSavedSessions:ce,launchConfirmTextFilter:be,launchConfirmWorkspaceFilter:ve,launchConfirmModelFilter:U,launchConfirmResumableOnly:de,launchConfirmSortMode:fe,filteredLaunchConfirmSavedSessions:Ke,launchConfirmSessionsLoading:pe,launchConfirmBusy:ue,resolvedWorkspacePath:ke,canCreateMissingWorkspace:D,openBrowseDialog:re,loadBrowsePath:X,handleWorkspaceChoiceChange:Ae,chooseCustomWorkspacePath:$e,setCustomWorkspacePath:p,setBrowseDialogOpen:g,setActiveLauncherKind:A,openLaunchConfirm:Be,handleConfirmLaunch:qe,closeLaunchConfirm:ze,setWorkspaceSelectionFromOption:Se,setLaunchConfirmWorkspaceKeyAndSync:rt,setLaunchConfirmArgs:E,setLaunchConfirmModel:F,setLaunchConfirmResumeId:xe,setLaunchConfirmTextFilter:ge,setLaunchConfirmWorkspaceFilter:H,setLaunchConfirmModelFilter:Q,setLaunchConfirmResumableOnly:ne,setLaunchConfirmSortMode:ae}}function Kh({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:u,section:f,showBottomNav:d,onBack:h,onSectionChange:m,onOpenConversation:v,onOpenRecent:k,onOpenMachineDetails:p,onMachineUpgrade:x,onLaunchDetectedIde:w,onAddWorkspace:b,onBrowseDirectory:N,onLaunchWorkspaceProvider:I,onListSavedSessions:y}){const M=C=>C==="ide"?"IDE":C==="cli"?"CLI":"ACP",S=r.slice(0,4),j=t.slice(0,3),g=Bh({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:N,onListSavedSessions:y}),$=o.useMemo(()=>S.map(C=>{const{metaText:T,updatedLabel:V}=il(C);return{key:`recent-launch:${C.id}`,primary:C.label,secondary:T,updatedLabel:V,onClick:()=>{const{options:E,selectedKey:_}=as({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspacePath:C.workspace});g.openLaunchConfirm({title:C.kind==="ide"?ts("restart-ide",C.label):C.providerSessionId?$a(C.label):ts("start-fresh",C.label),description:C.kind==="ide"?ss("restart-ide"):C.providerSessionId?Ba():ss("start-fresh"),confirmLabel:C.kind==="ide"?Is("restart-ide"):C.providerSessionId?zr(!0):Is("start-fresh"),busyLabel:C.kind==="ide"?Ms("restart-ide"):C.providerSessionId?Da(!0):Ms("start-fresh"),workspaceOptions:E,selectedWorkspaceKey:_,details:[{label:"Mode",value:M(C.kind)},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]},async()=>{const F=E.find(J=>J.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(F),await k({...C,workspace:(F==null?void 0:F.workspacePath)??null})})}}}),[g,k,S]),A=o.useMemo(()=>j.map(C=>({key:`recent-chat:${C.conversation.tabKey}`,primary:at(C.conversation),secondary:pf(C.conversation,{timestampLabel:C.timestamp?qi(C.timestamp):null}),unread:C.unread,onClick:()=>v(C.conversation)})),[v,j]),L=g.showAllRecent?$:$.slice(0,4),O=$.length>0,W=A.length>0,P=u?"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 ${P} 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:h,type:"button","aria-label":"Back",children:s.jsx(ga,{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:Mt(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:[W&&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:A.map(C=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${C.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:C.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))})]}),O&&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:L.map(C=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:C.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:C.primary}),C.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:C.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))}),$.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(C=>!C),children:g.showAllRecent?"Show fewer":`Show ${$.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:C=>g.handleWorkspaceChoiceChange(C.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:g.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[g.workspaceRows.map(C=>s.jsxs("option",{value:C.id,children:[C.id===g.defaultWorkspaceId?"⭐ ":"",en(C.path,C.label)||C.path]},C.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(C=>s.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const{options:T,selectedKey:V}=as({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspaceId:g.workspaceChoice!=="__custom__"?g.workspaceChoice:null,currentWorkspacePath:g.resolvedWorkspacePath});g.openLaunchConfirm({title:`Launch ${C.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:T,selectedWorkspaceKey:V,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:C.name}]},async()=>{const E=T.find(_=>_.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(E),w(C.type,{workspacePath:(E==null?void 0:E.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:C.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:g.resolvedWorkspacePath||"Use selected workspace"})]},C.type)):(g.activeLauncherKind==="cli"?n:a).map(C=>s.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const T=g.activeLauncherKind==="cli"?"cli":"acp",{options:V,selectedKey:E}=as({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspaceId:g.workspaceChoice!=="__custom__"?g.workspaceChoice:null,currentWorkspacePath:g.resolvedWorkspacePath});g.openLaunchConfirm({title:`Launch ${C.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${T.toUpperCase()}`,workspaceOptions:V,selectedWorkspaceKey:E,details:[{label:"Mode",value:T.toUpperCase()},{label:"Provider",value:C.displayName}],showArgsInput:!0,showModelInput:T==="acp",initialArgs:"",initialModel:"",providerType:C.type},async()=>{const _=V.find(F=>F.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(_),I(T,C.type,{workspaceId:(_==null?void 0:_.workspaceId)??null,workspacePath:(_==null?void 0:_.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:[C.icon?`${C.icon} `:"",C.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:g.resolvedWorkspacePath||"Use selected workspace"})]},C.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:x,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(on,{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:C=>{g.loadBrowsePath(C)},onConfirm:C=>{g.chooseCustomWorkspacePath(C),g.setBrowseDialogOpen(!1)}}),g.launchConfirm&&s.jsx(Ya,{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?zr(!!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:Ea()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:g.launchConfirmTextFilter,onChange:C=>g.setLaunchConfirmTextFilter(C.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:g.launchConfirmWorkspaceFilter,onChange:C=>g.setLaunchConfirmWorkspaceFilter(C.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:g.launchConfirmModelFilter,onChange:C=>g.setLaunchConfirmModelFilter(C.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),s.jsxs("select",{value:g.launchConfirmSortMode,onChange:C=>g.setLaunchConfirmSortMode(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled: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:C=>g.setLaunchConfirmResumableOnly(C.target.checked),disabled:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:g.launchConfirmResumeId,onChange:C=>g.setLaunchConfirmResumeId(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:g.launchConfirmBusy||g.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Mf()}),g.filteredLaunchConfirmSavedSessions.map(C=>s.jsxs("option",{value:C.providerSessionId,disabled:!C.canResume,children:[C.title||C.providerSessionId," ",C.canResume?"":"(workspace missing)"]},C.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 C=g.filteredLaunchConfirmSavedSessions.find(V=>V.providerSessionId===g.launchConfirmResumeId);if(!C)return null;const T=ol(C);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:T.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:T.providerSessionId}),s.jsx("div",{className:"mt-1",children:T.metaLine}),T.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:T.updatedLabel}),T.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:T.preview})]})})()]}),onConfirm:g.handleConfirmLaunch,onCancel:g.closeLaunchConfirm}),d&&s.jsx(al,{section:f,onSectionChange:m})]})}function Oh(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 Wh(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:ls(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,u,f,d;const a=er(n)?"cli":ys(n)?"acp":"ide",i=ls(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(er(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:((d=(f=(u=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:u.at)==null?void 0:f.call(u,-1))==null?void 0:d.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function Fh(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((h,m)=>m.timestamp-h.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=Qn(n),u=a.filter(h=>h.unread||h.requiresAction).length,f=Oh(n),d=[n.platform||"machine",f].filter(Boolean);return{id:n.id,label:Mt(n,{fallbackId:n.id}),subtitle:d.join(" · "),unread:u,total:a.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?hf(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 Hh(e){return e==="chat"}function Sr(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 Uh({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:f,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:m,onRequestedMobileSectionConsumed:v,setSelectedTabKey:k,setScreen:p,setSelectedMachineId:x,setSection:w,setMachineBackTarget:b,resetMachineAction:N}){const I=o.useRef(null),y=o.useCallback(M=>{if(!(M!=null&&M.sessionId))return;const S=Wr(M,c),j=Math.max(Date.now(),Zt(M),S.lastUpdated||0);Sr("mark_read:start",{tabKey:M.tabKey,sessionId:M.sessionId,displayPrimary:at(M),inboxBucket:S.inboxBucket,unread:S.unread,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,activityAt:Zt(M),readAt:j}),l(fs(M)||M.routeId,"mark_session_seen",{sessionId:M.sessionId,providerSessionId:M.providerSessionId,seenAt:j,completionMarker:S.completionMarker}).then(g=>{Sr("mark_read:result",{tabKey:M.tabKey,sessionId:M.sessionId,result:g})}).catch(g=>{Sr("mark_read:error",{tabKey:M.tabKey,sessionId:M.sessionId,error:g instanceof Error?g.message:String(g)})})},[c,l]);return o.useEffect(()=>{var S;if(!n){Hh(i)&&p("inbox"),k(((S=e[0])==null?void 0:S.tabKey)||null),I.current=null;return}if(i!=="chat"){I.current=null;return}const M=`${n.tabKey}:${n.sessionId||""}`;I.current!==M&&(I.current=M,y(n))},[e,y,i,n,p,k]),o.useEffect(()=>{if(!u)return;const M=e.find(S=>S.tabKey===u);M&&(k(M.tabKey),p("chat"),f==null||f())},[e,f,u,p,k]),o.useEffect(()=>{if(!d)return;const M=t.find(S=>S.id===d);M&&(x(M.id),N(),w("machines"),b("inbox"),p("machine"),h==null||h())},[t,h,d,N,b,p,w,x]),o.useEffect(()=>{m&&(w(m),p("inbox"),v==null||v())},[v,m,p,w]),o.useEffect(()=>{const M=r.filter(S=>S.inboxBucket==="task_complete"||S.unread);M.length!==0&&Sr("inbox_state",{screen:i,selectedTabKey:a,items:M.map(S=>{const j=Wr(S.conversation,c);return{liveState:j,tabKey:S.conversation.tabKey,sessionId:S.conversation.sessionId,displayPrimary:at(S.conversation),serverBucket:j.inboxBucket,computedBucket:S.inboxBucket,serverUnread:j.unread,computedUnread:S.unread,lastSeenAt:j.lastSeenAt,lastUpdated:j.lastUpdated,activityAt:Zt(S.conversation)}})})},[r,c,i,a]),{markConversationRead:y}}function zh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function ni(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Vh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Gh({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[u,f]=o.useState(null),d=o.useCallback(()=>{i("idle"),l(""),f(null)},[]),h=o.useCallback(async(b,N,I)=>{var y;try{i("loading"),l(`Launching ${N}…`);const M={ideType:N,enableCdp:!0};(y=I==null?void 0:I.workspacePath)!=null&&y.trim()&&(M.workspace=I.workspacePath.trim()),await e(b,"launch_ide",M),i("done"),l(`${N} launch requested`)}catch(M){i("error"),l(M instanceof Error?M.message:"Launch IDE failed"),console.error("Launch IDE failed",M)}},[e]),m=o.useCallback(async(b,N,I)=>{if(N.trim())try{i("loading"),l(I!=null&&I.createIfMissing?"Creating folder…":"Saving workspace…");const y=await e(b,"workspace_add",{path:N.trim(),createIfMissing:(I==null?void 0:I.createIfMissing)===!0});if(y!=null&&y.success){i("done"),l(I!=null&&I.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,I,y,M,S,j;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${((I=g==null?void 0:g.result)==null?void 0:I.version)||"latest"}.`);return}if((y=g==null?void 0:g.result)!=null&&y.upgraded||(M=g==null?void 0:g.result)!=null&&M.success){i("done"),l(`Upgrade to v${((S=g==null?void 0:g.result)==null?void 0:S.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((j=g==null?void 0:g.result)==null?void 0:j.error)||"Upgrade failed")}catch(g){i("error"),l(g instanceof Error?g.message:"Upgrade failed")}},[e]),k=o.useCallback(async(b,N,I,y)=>{var j,g,$;const M=Date.now(),S={machineId:b,kind:N,providerType:I,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:M};try{i("loading"),l(`Launching ${I}…`),f(S);const A={cliType:I};(j=y==null?void 0:y.workspacePath)!=null&&j.trim()?A.dir=y.workspacePath.trim():y!=null&&y.workspaceId&&(A.workspaceId=y.workspaceId),y!=null&&y.resumeSessionId&&(A.resumeSessionId=y.resumeSessionId),(g=y==null?void 0:y.args)!=null&&g.trim()&&(A.cliArgs=y.args.trim().split(/\s+/).filter(Boolean)),($=y==null?void 0:y.model)!=null&&$.trim()&&(A.initialModel=y.model.trim());const L=await e(b,"launch_cli",A),O=(L==null?void 0:L.result)||L,W=(O==null?void 0:O.sessionId)||(O==null?void 0:O.id);if(L!=null&&L.success&&W){f(null),i("done"),l(`${I} launched`),t(Vt(W));return}if(L!=null&&L.success){i("loading"),l(`${I} launch requested — waiting for session…`);return}f(null),i("error"),l((L==null?void 0:L.error)||(O==null?void 0:O.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(A){if(Vh(A)){i("loading"),l(`${I} launch requested — waiting for session…`);return}f(null),i("error"),l(A instanceof Error?A.message:`Could not launch ${N.toUpperCase()} workspace`)}},[t,e]),p=o.useCallback(async(b,N)=>{try{const I=await e(b,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),y=(I==null?void 0:I.result)??I;return Array.isArray(y==null?void 0:y.sessions)?y.sessions:[]}catch(I){return console.error("Failed to list saved sessions on mobile:",I),[]}},[e]),x=o.useCallback(async(b,N)=>nn(e,b,N),[e]);o.useEffect(()=>{if(!u)return;const b=ni(u.workspacePath),N=r.find(y=>{var A,L,O,W;if(!y||y.type==="adhdev-daemon"||zh(y.daemonId||y.id)!==u.machineId||(y.transport==="acp"?"acp":y.transport==="pty"?"cli":null)!==u.kind||String(y.agentType||y.type||"")!==u.providerType)return!1;const g=String(y.providerSessionId||"");if(u.resumeSessionId&&g)return g===u.resumeSessionId;if(b){const P=ni(y.workspace||y.runtimeWorkspaceLabel);return P?P===b:!1}return Number(y.lastUpdated||y._lastUpdate||y.timestamp||((W=(O=(L=(A=y.activeChat)==null?void 0:A.messages)==null?void 0:L.at)==null?void 0:O.call(L,-1))==null?void 0:W.timestamp)||0)>=u.startedAt-5e3});if(!N)return;const I=pc({entrySessionId:N.sessionId,entryInstanceId:N.instanceId,entryRouteId:N.id,conversations:n});I&&(f(null),i("done"),l(`${u.providerType} launched`),t(Vt(I)))},[n,r,t,u]),o.useEffect(()=>{if(!u)return;const b=window.setTimeout(()=>{f(N=>!N||N.startedAt!==u.startedAt?N:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(b)},[u]);const w=o.useCallback(async(b,N)=>{if(N.kind==="ide"&&N.providerType){await h(b,N.providerType,{workspacePath:N.workspace||null});return}(N.kind==="cli"||N.kind==="acp")&&N.providerType&&await k(b,N.kind,N.providerType,{workspacePath:N.workspace||null,resumeSessionId:N.providerSessionId||null})},[h,k]);return{machineAction:{state:a,message:c},resetMachineAction:d,handleLaunchDetectedIde:h,handleAddWorkspace:m,handleMachineUpgrade:v,handleLaunchWorkspaceProvider:k,handleListSavedSessions:p,handleBrowseDirectory:x,handleOpenRecent:w}}function qh({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:f}){const d=o.useCallback(w=>{i(w.tabKey),c("chat"),n(w)},[n,c,i]),h=o.useCallback(w=>{const b=e.find(N=>N.routeId===w.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((w,b="inbox")=>{l(w),a(),u("machines"),f(b),c("machine")},[a,f,c,u,l]),k=o.useCallback(w=>{const b=fs(w);b&&v(b,"chat")},[v]),p=o.useCallback(()=>{a(),c(r)},[r,a,c]),x=o.useCallback(w=>{u(w),c("inbox")},[c,u]);return{openConversation:d,openNativeConversation:h,backFromConversation:m,openMachine:v,openConversationMachine:k,backFromMachine:p,changeMachineSection:x}}function ms(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled!==!0||e.machineStatus!=="detected"?!1:e.installed!==!1}function Yh(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function Nr(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Xh({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,userName:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:f,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:m,onRequestedMobileSectionConsumed:v,onOpenHistory:k,onOpenRemote:p,onStopCli:x,wsStatus:w,isConnected:b,onShowHiddenConversation:N,onShowAllHiddenConversations:I,onHideConversation:y,onOpenNewSession:M,liveSessionInboxState:S,setCliViewModeOverrides:j}){const[g,$]=o.useState(()=>{var Y;return((Y=e[0])==null?void 0:Y.tabKey)||null}),[A,L]=o.useState(()=>e[0]?"chat":"inbox"),[O,W]=o.useState("chats"),[P,C]=o.useState(null),[T,V]=o.useState("inbox"),E=Ts(),_="0.9.31",F=o.useMemo(()=>e.find(Y=>Y.tabKey===g)||e[0]||null,[e,g]),J=o.useMemo(()=>F?r.find(Y=>Y.id===F.routeId):void 0,[r,F]),xe=o.useMemo(()=>!F||Je(F)||!et(F)?null:Rs(F),[F]),ce=o.useMemo(()=>r.filter(Y=>Y.type==="adhdev-daemon").sort(ka),[r]),te=o.useMemo(()=>ce.find(Y=>Y.id===P)||null,[ce,P]),be=an({sendDaemonCommand:a,activeConv:F||void 0,setActionLogs:i,isStandalone:c}),ge=Gh({sendDaemonCommand:a,navigate:E,ides:r,conversations:e}),ve=o.useMemo(()=>e.map(Y=>{const G=A==="chat"&&(F==null?void 0:F.tabKey)===Y.tabKey,X=Zr(Y,S,{hideOpenTaskCompleteUnread:!0,isOpenConversation:G}),re=Zt(Y),Se=jc(Y);return{conversation:Y,timestamp:re,preview:Se,unread:X.unread,requiresAction:X.requiresAction,isWorking:X.isWorking,inboxBucket:X.inboxBucket}}),[e,S,A,F]),{markConversationRead:H}=Uh({conversations:e,machineEntries:ce,items:ve,selectedConversation:F,selectedTabKey:g,screen:A,liveSessionInboxState:S,sendDaemonCommand:a,requestedActiveTabKey:u,onRequestedActiveTabConsumed:f,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:m,onRequestedMobileSectionConsumed:v,setSelectedTabKey:$,setScreen:L,setSelectedMachineId:C,setSection:W,setMachineBackTarget:V,resetMachineAction:ge.resetMachineAction}),U=qh({conversations:e,selectedConversation:F,machineBackTarget:T,markConversationRead:H,resetMachineAction:ge.resetMachineAction,setSelectedTabKey:$,setScreen:L,setSelectedMachineId:C,setSection:W,setMachineBackTarget:V}),Q=o.useMemo(()=>Nr(ve.filter(Y=>Y.requiresAction)),[ve]),de=o.useMemo(()=>Nr(ve.filter(Y=>Y.unread&&!Y.requiresAction)),[ve]),ne=o.useMemo(()=>Nr(ve.filter(Y=>!Y.unread&&!Y.requiresAction&&Y.isWorking)),[ve]),fe=o.useMemo(()=>Nr(ve.filter(Y=>!Y.unread&&!Y.requiresAction&&!Y.isWorking)),[ve]),ae=o.useMemo(()=>te?ve.filter(Y=>fs(Y.conversation)===te.id):[],[ve,te]),pe=o.useMemo(()=>Wh(te,r),[r,te]),le=(te==null?void 0:te.version)||null,ue=!!te&&!!le&&!0&&le!==_,oe=o.useMemo(()=>(te==null?void 0:te.availableProviders)||[],[te]),ye=o.useMemo(()=>oe.filter(Y=>ms(Y,"cli")).map(Y=>({type:Y.type,displayName:Y.displayName||Y.type,icon:Y.icon})),[oe]),he=o.useMemo(()=>oe.filter(Y=>ms(Y,"acp")).map(Y=>({type:Y.type,displayName:Y.displayName||Y.type,icon:Y.icon})),[oe]),ke=o.useMemo(()=>Fh(ce,ve),[ve,ce]),D=o.useCallback(async Y=>{te&&await ge.handleOpenRecent(te.id,Y)},[ge,te]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:A==="chat"&&F?s.jsx(Lh,{selectedConversation:F,isAcp:Je(F),isStandalone:c,selectedIdeEntry:J,actionLogs:n,userName:l,isSendingChat:be.isSendingChat,sendFeedbackMessage:be.sendFeedbackMessage,isFocusingAgent:be.isFocusingAgent,handleModalButton:be.handleModalButton,handleRelaunch:be.handleRelaunch,onBack:U.backFromConversation,onOpenNativeConversation:U.openNativeConversation,onOpenMachine:U.openConversationMachine,onHideConversation:y,onOpenHistory:k,onOpenRemote:p,onStopCli:x,cliViewMode:xe,onSetCliViewMode:async Y=>{await Xc({conversation:F,mode:Y,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:j})},handleSendChat:be.handleSendChat,handleFocusAgent:be.handleFocusAgent}):A==="machine"&&te?s.jsx(Kh,{selectedMachineEntry:te,selectedMachineConversations:ae,selectedMachineRecentLaunches:pe,cliProviders:ye,acpProviders:he,selectedMachineNeedsUpgrade:ue,appVersion:_,machineAction:ge.machineAction,isStandalone:c,section:O,showBottomNav:T==="inbox",onBack:U.backFromMachine,onSectionChange:U.changeMachineSection,onOpenConversation:U.openConversation,onOpenRecent:D,onOpenMachineDetails:()=>E(`/machines/${te.id}`),onMachineUpgrade:()=>ge.handleMachineUpgrade(te.id),onLaunchDetectedIde:(Y,G)=>ge.handleLaunchDetectedIde(te.id,Y,G),onAddWorkspace:(Y,G)=>ge.handleAddWorkspace(te.id,Y,G),onBrowseDirectory:Y=>ge.handleBrowseDirectory(te.id,Y),onLaunchWorkspaceProvider:(Y,G,X)=>ge.handleLaunchWorkspaceProvider(te.id,Y,G,X),onListSavedSessions:Y=>ge.handleListSavedSessions(te.id,Y)}):s.jsx(_h,{section:O,attentionItems:Q,unreadItems:de,workingItems:ne,completedItems:fe,hiddenConversations:t,machineCards:ke,getAvatarText:Yh,onOpenConversation:U.openConversation,onShowConversation:N,onShowAllHidden:I,onOpenNewSession:M,onOpenMachine:U.openMachine,onOpenSettings:()=>E("/settings"),onSectionChange:W,wsStatus:w,isConnected:b,isStandalone:c})})}function Ln(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function Jh({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,u]=o.useState(!1),[f,d]=o.useState(null),h=o.useCallback(()=>{c.current=0,u(!1),d(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const m=o.useCallback(x=>{x.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),v=o.useCallback(x=>{if(!x.dataTransfer.types.includes("text/tab-key"))return;if(x.preventDefault(),!Ln(t,r)){d("merge");return}const w=x.currentTarget.getBoundingClientRect(),b=x.clientX-w.left,N=w.width/3;b<N?d("split-left"):b>N*2?d("split-right"):d("merge")},[t,r]),k=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,u(!1),d(null))},[]),p=o.useCallback(x=>{c.current=0,u(!1);const w=x.dataTransfer.getData("text/tab-key"),b=w?e.some(I=>I.tabKey===w):!1,N=f;if(d(null),i(),!!w){if(x.preventDefault(),N==="split-left"&&Ln(t,r)){r==null||r(w,"split-left");return}if(N==="split-right"&&Ln(t,r)){r==null||r(w,"split-right");return}if(b){a(w);return}n==null||n(w)}},[e,f,t,r,n,a,i]);return{dragOver:l,dropAction:f,resetDragState:h,handleDragEnter:m,handleDragOver:v,handleDragLeave:k,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 Zh({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(t??null),[l,u]=o.useState(r??[]),[f,d]=o.useState(null),h=o.useRef(null),m=o.useRef(null),v=o.useRef(n),k=o.useRef(a);o.useEffect(()=>{v.current=n},[n]),o.useEffect(()=>{k.current=a},[a]),o.useEffect(()=>{t&&t!==i&&c(t)},[t,i]),o.useEffect(()=>{u(S=>{const j=Qh(S,e);return j.length===S.length&&j.every((g,$)=>g===S[$])?S:j})},[e]);const p=o.useMemo(()=>{const S=f??l;if(S.length===0)return e;const j=new Map(S.map((g,$)=>[g,$]));return[...e].sort((g,$)=>{const A=j.get(g.tabKey)??999,L=j.get($.tabKey)??999;return A-L})},[e,f,l]);o.useEffect(()=>{var j,g;if(p.length===0){i!==null&&(c(null),(j=v.current)==null||j.call(v,null));return}if(i&&p.some($=>$.tabKey===i))return;const S=p[0].tabKey;S!==i&&(c(S),(g=v.current)==null||g.call(v,S))},[p,i]);const x=o.useMemo(()=>p.find(S=>S.tabKey===i),[p,i]),w=o.useCallback(S=>{var j;c(S),(j=v.current)==null||j.call(v,S)},[]),b=o.useCallback((S,j,g)=>{u($=>{var W;const A=$.filter(P=>P!==S),L=A.indexOf(j);if(L<0)return $;const O=g==="left"?L:L+1;return A.splice(O,0,S),(W=k.current)==null||W.call(k,A),A}),d(null)},[]),N=o.useCallback((S,j,g)=>{const A=(l.length>0?l:e.map(W=>W.tabKey)).filter(W=>W!==S),L=A.indexOf(j);if(L<0)return;const O=g==="left"?L:L+1;A.splice(O,0,S),h.current=A,d(A)},[l,e]),I=o.useCallback(()=>{var j;const S=h.current;S&&(u(S),(j=k.current)==null||j.call(k,S))},[]),y=o.useCallback(()=>{h.current=null,d(null)},[]),M=o.useCallback(S=>{u(j=>{var $;const g=j.filter(A=>A!==S);return g.push(S),($=k.current)==null||$.call(k,g),g})},[]);return{activeTabId:i,activeConv:x,sortedConversations:p,previewOrderRef:h,draggingTabRef:m,selectTab:w,handleTabReorder:b,updatePreviewOrder:N,commitPreviewOrder:I,clearPreviewOrder:y,moveTabToEnd:M,setDraggingTabKey:S=>{m.current=S}}}function ex({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 Xa({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,u=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",f=n?Cc: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:u}),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:Et,"aria-label":Et,children:[s.jsx(Fi,{size:14}),s.jsx("span",{children:Et})]})}),c&&s.jsx(nl,{}),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 cl="adhdev-tab-shortcuts";function ll(){try{return JSON.parse(localStorage.getItem(cl)||"{}")}catch{return{}}}function dl({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>ll()),[l,u]=o.useState(null),f=o.useCallback(h=>{const m=[];return h.metaKey&&m.push(a?"⌘":"Meta"),h.ctrlKey&&m.push("Ctrl"),h.altKey&&m.push(a?"⌥":"Alt"),h.shiftKey&&m.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(m.push(h.key.length===1?h.key.toUpperCase():h.key),m.join("+"))},[a]),d=o.useCallback(h=>{c(h);try{localStorage.setItem(cl,JSON.stringify(h))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const h=m=>{if(m.preventDefault(),m.stopPropagation(),m.key==="Escape"){u(null);return}const v=f(m);if(!v)return;const k={...i};for(const[p,x]of Object.entries(k))x===v&&delete k[p];k[l]=v,d(k),u(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,l,i,d,f]),o.useEffect(()=>{if(!e)return;const h=m=>{if(!(!m.ctrlKey&&!m.metaKey&&!m.altKey)){for(const[v,k]of Object.entries(i))if(t.includes(v)&&f(m)===k){m.preventDefault(),r(),n(v);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,i,t,r,n,f]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:u,saveShortcuts:d}}const tx=o.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:u,onSelectTab:f,onConversationActivated:d,onPreviewReorder:h,onReorderTab:m,onCommitPreviewOrder:v,onClearPreviewOrder:k,onDragStateReset:p,onDragTabKeyChange:x,onReceiveTab:w,onOpenContextMenu:b,longPressTimer:N,isGroupActive:I}){const y=Ls(t),M=y.isGenerating?"agent-tab-generating":y.isWaiting?"agent-tab-waiting":"",S=y.isReconnecting,j=o.useCallback(T=>{l.current=t.tabKey,x(t.tabKey),T.dataTransfer.setData("text/tab-key",t.tabKey),T.dataTransfer.effectAllowed="move"},[t.tabKey,l,x]),g=o.useCallback(()=>{l.current=null,x(null),v(),k(),p()},[l,x,v,k,p]),$=o.useCallback(T=>{const V=l.current;if(!(!V||V===t.tabKey)&&T.dataTransfer.types.includes("text/tab-key")){T.preventDefault(),T.stopPropagation();const E=T.currentTarget.getBoundingClientRect(),_=T.clientX<E.left+E.width/2?"left":"right";h(V,t.tabKey,_)}},[t.tabKey,l,h]),A=o.useCallback(T=>{T.preventDefault(),T.stopPropagation();const V=T.dataTransfer.getData("text/tab-key");if(V&&V!==t.tabKey){const E=T.currentTarget.getBoundingClientRect(),_=T.clientX<E.left+E.width/2?"left":"right";c.includes(V)?m(V,t.tabKey,_):w&&w(V)}k()},[t.tabKey,c,m,w,k]),L=o.useCallback(T=>{T.stopPropagation(),u(),f(t.tabKey),d(t)},[t,d,u,f]),O=o.useCallback(T=>{T.preventDefault(),b(T.clientX,T.clientY,t.tabKey)},[t.tabKey,b]),W=o.useCallback(T=>{const V=T.touches[0];N.current=setTimeout(()=>{b(V.clientX,V.clientY,t.tabKey)},600)},[t.tabKey,N,b]),P=o.useCallback(()=>{N.current&&clearTimeout(N.current)},[N]),C=["adhdev-dockview-tab",M,r&&"is-active",I&&"is-group-active",S&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:C,draggable:!0,onDragStart:j,onDragEnd:g,onDragOver:$,onDrop:A,onClick:L,onContextMenu:O,onTouchStart:W,onTouchEnd:P,onTouchMove:P,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:"▲"}):S?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:at(t),children:at(t)}),s.jsx("span",{className:"adhdev-dockview-tab-meta",children:S?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:es(t)}):y.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[es(t),s.jsx("span",{className:"connecting-dots"})]}):es(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 sx({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:f,onCommitPreviewOrder:d,onClearPreviewOrder:h,onDragStateReset:m,onDragTabKeyChange:v,onReceiveTab:k,onHideTab:p,isGroupActive:x,allowTabShortcuts:w=!0}){const[b,N]=o.useState(null),I=o.useRef(null),y=o.useRef(null),M=o.useMemo(()=>e.map(O=>O.tabKey),[e]);nr("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(b==null?void 0:b.tabKey)||null});const{isMac:S,tabShortcuts:j,shortcutListening:g,setShortcutListening:$,saveShortcuts:A}=dl({enabled:w,sortedTabKeys:e.map(O=>O.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!b)return;const O=W=>{const P=document.querySelector("[data-pane-context-menu]");P&&P.contains(W.target)||N(null)};return window.addEventListener("mousedown",O,!0),()=>window.removeEventListener("mousedown",O,!0)},[b]),o.useEffect(()=>{const O=y.current;if(!O)return;const W=P=>{Math.abs(P.deltaY)<=Math.abs(P.deltaX)||(P.preventDefault(),O.scrollLeft+=P.deltaY)};return O.addEventListener("wheel",W,{passive:!1}),()=>O.removeEventListener("wheel",W)},[]);const L=o.useCallback((O,W,P)=>{N({x:O,y:W,tabKey:P})},[]);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(O=>s.jsx(tx,{conv:O,isActive:t===O.tabKey,isDraggedTab:a.current===O.tabKey,isTaskCompleteUnread:n.has(O.tabKey),shortcut:w?j[O.tabKey]:void 0,conversationKeys:M,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:f,onCommitPreviewOrder:d,onClearPreviewOrder:h,onDragStateReset:m,onDragTabKeyChange:v,onReceiveTab:k,onOpenContextMenu:L,longPressTimer:I,isGroupActive:x},O.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:[w&&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:O=>{O.stopPropagation(),$(b.tabKey),N(null)},children:["⌨ ",j[b.tabKey]?`Change shortcut (${j[b.tabKey]})`:"Set shortcut"]}),j[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 O={...j};delete O[b.tabKey],A(O),N(null)},children:"✕ Remove shortcut"})]}),p&&s.jsxs(s.Fragment,{children:[w&&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"})]})]}),w&&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:()=>$(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:O=>O.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. ",S?"⌘+1":"Ctrl+1",", ",S?"⌥+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 rx({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,userName:u,groupIndex:f,onFocus:d,isSplitMode:h,numGroups:m,onMoveTab:v,onReceiveTab:k,style:p,onActiveTabChange:x,initialActiveTabId:w,initialTabOrder:b,onTabOrderChange:N,onHideTab:I,isFocused:y,allowTabShortcuts:M=!0,onOpenNewSession:S,liveSessionInboxState:j}){const{sendCommand:g}=vt(),$=o.useRef(null),{activeTabId:A,activeConv:L,sortedConversations:O,draggingTabRef:W,selectTab:P,handleTabReorder:C,updatePreviewOrder:T,commitPreviewOrder:V,clearPreviewOrder:E,moveTabToEnd:_,setDraggingTabKey:F}=Zh({conversations:e,initialActiveTabId:w,initialTabOrder:b,onActiveTabChange:x,onTabOrderChange:N}),J=an({sendDaemonCommand:a,activeConv:L,setActionLogs:i,isStandalone:c}),{dragOver:xe,dropAction:ce,resetDragState:te,handleDragEnter:be,handleDragOver:ge,handleDragLeave:ve,handleDrop:H}=Jh({conversations:e,numGroups:m,onMoveTab:v,onReceiveTab:k,onOwnTabDrop:_,onClearPreviewOrder:E}),U=L&&!Je(L)&&Rs(L)==="terminal",Q=o.useMemo(()=>L?t.find(ae=>ae.id===L.routeId):void 0,[t,L]),de=o.useMemo(()=>L?n.filter(ae=>ae.routeId===L.tabKey):[],[n,L]),ne=o.useMemo(()=>new Set(O.filter(ae=>Cu(ae,j,{isOpenConversation:ae.tabKey===A})).map(ae=>ae.tabKey)),[A,j,O]);nr("PaneGroup",{groupIndex:f,conversationCount:e.length,activeTabId:A,dragOver:xe});const fe=o.useCallback(ae=>{ae.streamSource==="agent-stream"&&ae.agentType&&g(ae.routeId,rl(),{agentType:ae.agentType,...ae.sessionId&&{targetSessionId:ae.sessionId}}).catch(()=>{})},[g]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:d,style:{...p,outline:xe?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(sx,{conversations:O,activeTabId:A,groupIndex:f,numGroups:m,unreadTabKeys:ne,draggingTabRef:W,onFocus:d,onSelectTab:P,onConversationActivated:fe,onPreviewReorder:T,onReorderTab:C,onCommitPreviewOrder:V,onClearPreviewOrder:E,onDragStateReset:te,onDragTabKeyChange:F,onMoveTab:v,onReceiveTab:k,onHideTab:I,isGroupActive:y??!1,allowTabShortcuts:M}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:be,onDragOver:ge,onDragLeave:ve,onDrop:H,children:[xe&&s.jsx(ex,{dropAction:ce,canSplit:!!(m<4&&v)}),L?s.jsx(qa,{activeConv:L,clearToken:r[L.tabKey]||0,isCliTerminal:!!U,ideEntry:Q,terminalRef:$,handleModalButton:J.handleModalButton,handleRelaunch:J.handleRelaunch,handleSendChat:J.handleSendChat,isSendingChat:J.isSendingChat,sendFeedbackMessage:J.sendFeedbackMessage,handleFocusAgent:J.handleFocusAgent,isFocusingAgent:J.isFocusingAgent,actionLogs:de,userName:u,isInputActive:!h||!!y}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(Xa,{conversationsCount:e.length,isSplitMode:h,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:S})})]})]})}function nx({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setActionLogs:f,isStandalone:d,hasRegisteredMachines:h,userName:m,focusedGroup:v,focusGroup:k,moveTabToGroup:p,splitTabRelative:x,closeGroup:w,handleResizeStart:b,groupActiveTabIds:N,setGroupActiveTab:I,groupTabOrders:y,setGroupTabOrder:M,toggleHiddenTab:S,onOpenNewSession:j,allowTabShortcuts:g=!0,liveSessionInboxState:$}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((A,L)=>{const O=t&&n.length===r?`${n[L]}%`:void 0;return s.jsxs(jt.Fragment,{children:[t&&L>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:W=>b(L-1,W),onDoubleClick:()=>w(L),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(rx,{style:t?{flexBasis:O??`${100/r}%`,flexGrow:O?0:1,flexShrink:O?0:1}:void 0,conversations:A,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setActionLogs:f,isStandalone:d,hasRegisteredMachines:h,userName:m,groupIndex:L,isFocused:t&&v===L,onFocus:()=>k(L),isSplitMode:t,numGroups:r,onMoveTab:(W,P)=>{P==="left"&&L>0?p(W,L-1):P==="right"&&L<r-1?p(W,L+1):P==="split-left"&&r<4?x(W,L,"left"):P==="split-right"&&r<4&&x(W,L,"right")},onReceiveTab:W=>p(W,L),onActiveTabChange:W=>I(L,W),initialActiveTabId:N[L],initialTabOrder:y[L],onTabOrderChange:W=>M(L,W),onHideTab:S,onOpenNewSession:j,allowTabShortcuts:g,liveSessionInboxState:$})]},L)})})}function ul({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?dt.onScreenshot("ide-page",(d,h)=>{if(d!==e)return;const m=new FileReader;m.onload=()=>i(m.result),m.readAsDataURL(h)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var d;return e?((d=dt.onStatus)==null?void 0:d.call(dt,(h,m)=>{h===e&&m!=null&&m.screenshotUsage&&l(m.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,t]),o.useEffect(()=>{const f=e?dt.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 u=o.useCallback(async(f,d)=>{const h=e?dt.get(e):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(f,d,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:u}}const ml="adhdev-dashboard-action-shortcuts",ax=1200,ox={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function ix(){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 fl(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 da(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function qr(e){const t=Object.fromEntries(fl(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(ml)||"{}"),n={...t,...r};for(const[a,i]of Object.entries(ox))n[a]===i&&(n[a]=t[a]);return n}catch{return t}}function pl(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function cx({enabled:e=!0,onTrigger:t}){const r=ix(),[n,a]=o.useState(()=>qr(r)),[i,c]=o.useState(null),[l,u]=o.useState([]),f=o.useRef({parts:[],timer:null}),d=o.useCallback(p=>{const x=[];return p.metaKey&&x.push(r?"⌘":"Meta"),p.ctrlKey&&x.push("Ctrl"),p.altKey&&x.push(r?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&x.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(x.push(pl(p.key)),x.join("+"))},[r]),h=o.useCallback(p=>{a(p);try{localStorage.setItem(ml,JSON.stringify(p))}catch{}},[]);o.useEffect(()=>{const p=qr(r),x=Object.entries(n),w=Object.entries(p);x.length===w.length&&x.every(([b,N])=>p[b]===N)||h(p)},[n,r,h]);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}},ax))},[]);o.useEffect(()=>{if(!i)return;const p=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){c(null),u([]);return}const w=d(x);if(!w)return;const N=!(x.metaKey||x.ctrlKey||x.altKey)&&/^[A-Z0-9]$/.test(w);if(l.length===0&&N){u([w]);return}const y=[...l,w].slice(0,2).join(" "),M={...n};for(const[S,j]of Object.entries(M))j===y&&delete M[S];M[i]=y,h(M),c(null),u([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,d,h,i,l]),o.useEffect(()=>{if(!e||i)return;const p=x=>{if(x.defaultPrevented)return;const w=d(x);if(!w)return;const b=x.metaKey||x.ctrlKey||x.altKey;if(da(x.target)&&!b)return;const N=f.current.parts,I=b?[w]:[...N.slice(-1),w].slice(-2),y=I.join(" "),M=I[I.length-1],S=Object.entries(n).filter(([,L])=>!!L),j=S.find(([,L])=>L===y);if(j){x.preventDefault(),m(),t(j[0]);return}if(S.some(([,L])=>L.startsWith(`${y} `))){x.preventDefault(),f.current.parts=I,v();return}const $=S.find(([,L])=>L===M);if($){x.preventDefault(),m(),t($[0]);return}if(S.some(([,L])=>L.startsWith(`${M} `))){x.preventDefault(),f.current.parts=[M],v();return}m()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,v,e,d,t,m,i]),o.useEffect(()=>()=>m(),[m]);const k=o.useMemo(()=>fl(r),[r]);return{isMac:r,actionDefinitions:k,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:h}}function lx({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 hl(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function ai({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!hl(n):!0}function dx({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:hl(r)}const xl=o.createContext(null);function cn(){const e=o.useContext(xl);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Dr(e){return at(e)||e.tabKey}function ux(e){return`remote:${e}`}function Lt(e){return e.startsWith("remote:")}function oi(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Rn(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,u;try{t.focus(),(u=(l=e==null?void 0:e.body)==null?void 0:l.focus)==null||u.call(l)}catch{}})}catch{}}function Cr(e,t){e.classList.remove(zn.className,Vn.className),e.classList.add(t==="light"?zn.className:Vn.className)}function ii(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 mx(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 fx(e,t,r){var c;const n=[t];let a;for(const l of n){let u;for(const f of l){const d=e.addPanel({id:f.tabKey,component:"conversation",title:Dr(f),params:{kind:"conversation",tabKey:f.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});u||(u=d.id)}a=u??a}return r??((c=t[0])==null?void 0:c.tabKey)??null}function ci(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!==Dr(n)&&a.api.setTitle(Dr(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:Dr(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 li(e,t,r){var u,f;const n=r?ux(r):null;for(const d of[...e.panels])Lt(d.id)&&(!n||d.id!==n)&&e.removePanel(d);if(!r||!n)return;const a=Pt(t,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=Nc(a);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((f=e.panels.find(d=>!Lt(d.id)))==null?void 0:f.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function px({params:e,api:t}){var h;const r=cn(),n=o.useRef(null),[a,i]=o.useState(t.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=an({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 u=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(Xa,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const d=!Je(c)&&Rs(c)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(qa,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:d,ideEntry:u,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:f,userName:r.userName,scrollToBottomRequestNonce:((h=r.scrollToBottomRequest)==null?void 0:h.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:a})})}function hx({params:e}){var u;const t=cn(),r=o.useMemo(()=>Pt([...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)||((u=r==null?void 0:r.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:l}=ul({doId:a,targetSessionId:r?dc(r):(n==null?void 0:n.sessionId)||(n==null?void 0:n.instanceId),connState:(r==null?void 0:r.connectionState)||"new",viewMode:"remote"});return r?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(Gi,{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 xx(){const e=cn();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(Xa,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function bx(e){var v,k;mx(e);const t=cn(),r=o.useCallback(p=>{"button"in p&&p.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const p=Pt([...t.conversationsByTabKey.values()],e.params.routeId),x=((v=e.api.group.activePanel)==null?void 0:v.id)===e.api.id,w=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${x?" is-active":""}${w?" 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=((k=e.api.group.activePanel)==null?void 0:k.id)===e.api.id,i=e.api.isGroupActive,c=Zr(n,t.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,u=c.isConnecting,f=c.isGenerating,d=c.isWaiting,h=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:at(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:p=>{var x;p.preventDefault(),r(p),t.openTabContextMenu({x:p.clientX,y:p.clientY,tabKey:n.tabKey,sourceDocument:((x=p.target)==null?void 0:x.ownerDocument)??document})},children:[h&&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"}):d?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:"○"}):u?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:at(n)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:es(n)}):u?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:es(n)}):s.jsx("span",{children:es(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 gx({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:u,userName:f,toggleHiddenTab:d,actionShortcuts:h,registerActionHandlers:m,onActiveTabChange:v,onOpenNewSession:k,onRequestScrollToBottom:p,requestedActiveTabKey:x,requestedRemoteIdeId:w,onRequestedActiveTabConsumed:b,scrollToBottomRequest:N,liveSessionInboxState:I,layoutProfile:y}){var ft,At,gt;const{theme:M}=Wa(),{sendCommand:S}=vt(),j=o.useRef(null),g=o.useRef(null),$=o.useRef(!1),A=o.useRef(!1),L=o.useRef(!1),O=o.useRef(null),W=o.useRef([]),[P,C]=o.useState(null),[T,V]=o.useState(!1),[E,_]=o.useState(!1),[F,J]=o.useState(0),xe=o.useRef(null),ce=o.useRef(typeof window>"u"?{}:qp(y)),te=o.useMemo(()=>new Map(e.map(K=>[K.tabKey,K])),[e]),be=o.useMemo(()=>{const K=j.current;return K?K.groups.some(B=>{try{const z=B.model.location.type;return z!=="floating"&&z!=="popout"?!1:B.panels.some(q=>te.has(q.id))}catch{return!1}}):!1},[te,F,e]),ge=o.useCallback(()=>{var K;(K=j.current)==null||K.focus()},[]),ve=o.useCallback((K,B)=>{p==null||p(K,B)},[p]),H=o.useCallback(K=>{const B=document,z=K.document;for(const Ne of B.querySelectorAll('link[rel="stylesheet"]')){const se=z.createElement("link");se.rel="stylesheet",se.href=Ne.href,Ne.crossOrigin&&(se.crossOrigin=Ne.crossOrigin),z.head.appendChild(se)}for(const Ne of B.querySelectorAll("style")){const se=z.createElement("style");se.textContent=Ne.textContent,z.head.appendChild(se)}const q=[];for(const Ne of B.styleSheets)try{for(const se of Ne.cssRules)se instanceof CSSStyleRule&&(se.selectorText===":root"||se.selectorText==="html")&&q.push(se.cssText)}catch{}if(q.length>0){const Ne=z.createElement("style");Ne.textContent=q.join(`
42
+ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:g,onCancel:()=>d(null)})]})}const op=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function ip(){const{preference:e,setPreference:t}=Wa();return s.jsx("div",{className:"flex gap-2",children:op.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 cp(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 lp(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function kn(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Fo(e){const{r:t,g:r,b:n}=lp(e);return .2126*kn(t)+.7152*kn(r)+.0722*kn(n)}function Ho(e,t){const r=Fo(e),n=Fo(t),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function Wc(e){const t=cp(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return Ho(t,r)>=Ho(t,n)?r:n}const ia={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},ca={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},dp=[{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"}}}],Fc="adhdev-chat-theme",Hc="adhdev-chat-theme-custom";function _r(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Fc)||"ember"}catch{return"ember"}}function _t(e){try{const t=localStorage.getItem(Hc);if(t){const r=JSON.parse(t);return{...e==="dark"?ia:ca,...r[e]}}}catch{}return e==="dark"?ia:ca}function vr(e,t){try{localStorage.setItem(Hc,JSON.stringify({dark:e,light:t}))}catch{}}function Ct(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 Gr(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 up={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function qs(e,t){var a;const r=(a=up[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",Gr(r,24)),n.style.setProperty("--accent-on-primary",Wc(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Gr(r,18)})`),n.style.setProperty("--border-accent",Ct(r,.35)),n.style.setProperty("--nav-active-bg",Ct(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Ct(r,.06)}`)}function rs(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Ct(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Ct(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Ct(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",Ct(e.borderSubtle,.5)),t.style.setProperty("--border-default",Ct(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Gr(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Wc(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Gr(e.accentColor,40)})`),t.style.setProperty("--border-accent",Ct(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Ct(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Ct(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 ${Ct(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 Fa(){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 mp(e){try{localStorage.setItem(Fc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ns()?"dark":"light";rs(_t(t))}else Fa(),qs(e,ns()?"dark":"light")}function fp(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=_r();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ns()?"dark":"light";rs(_t(t))}else Fa(),qs(e,ns()?"dark":"light")}function ns(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function ht({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 Bs({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 pp({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=o.useState(()=>_t(r));o.useEffect(()=>{a(_t(r))},[r]);const i=o.useCallback((c,l)=>{a(u=>{const f={...u,[c]:l},h=_t(r==="dark"?"light":"dark");return r==="dark"?vr(f,h):vr(h,f),rs(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(Bs,{title:"App Background",children:[s.jsx(ht,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(ht,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(ht,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(Bs,{title:"App Text",children:[s.jsx(ht,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(ht,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(ht,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(Bs,{title:"Borders & Accent",children:[s.jsx(ht,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(ht,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(ht,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Bs,{title:"Chat Bubbles",children:[s.jsx(ht,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(ht,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),s.jsx(ht,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(ht,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(Bs,{title:"Chat Layout",children:[s.jsx(ht,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(ht,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(ht,{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?ia:ca,u=_t(e?"light":"dark");e?vr(c,u):vr(u,c),a(c),rs(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 hp(){const[e,t]=o.useState(_r),[r,n]=o.useState(!0),[a,i]=o.useState(()=>_t("dark"));o.useEffect(()=>{n(ns());const u=new MutationObserver(()=>{const h=ns();n(h);const m=_r();m==="custom"?rs(_t(h?"dark":"light")):qs(m,h?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const f=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{const h=ns();n(h);const m=_r();m==="custom"?rs(_t(h?"dark":"light")):qs(m,h?"dark":"light")};return f.addEventListener("change",d),()=>{u.disconnect(),f.removeEventListener("change",d)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?rs(_t(r?"dark":"light")):(Fa(),qs(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(_t(r?"dark":"light"))},[r]);const c=u=>{t(u),mp(u)},l=[...dp,{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(u=>{const f=e===u.id,d=r?u.preview.dark:u.preview.light,h=u.id==="honey"||u.id==="ember"?"#1a1a1a":u.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>c(u.id),className:"text-left rounded-xl p-3 transition-all",style:{background:f?"var(--bg-glass-hover)":"var(--bg-glass)",border:f?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:f?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:d.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"Hello! How can I help?"}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.userBubble,color:h},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:d.assistantBubble,border:d.assistantBorder,color:d.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:u.id==="custom"?"🎨 Custom":u.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:u.description})]})]})]},u.id)})}),e==="custom"&&s.jsx(pp,{dark:r,onColorsChange:u=>i(u)})]})}const Ha="adhdev_mobileDashboardMode_v1",la="adhdev:mobile-dashboard-mode-change";function Ua(){try{return localStorage.getItem(Ha)==="workspace"?"workspace":"chat"}catch{return"chat"}}function xp(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??Ua())},r=a=>{const i=a.detail;t(i)},n=a=>{a.key&&a.key!==Ha||t()};return window.addEventListener(la,r),window.addEventListener("storage",n),()=>{window.removeEventListener(la,r),window.removeEventListener("storage",n)}}function bp(e){try{localStorage.setItem(Ha,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(la,{detail:e}))}function gp(){const[e,t]=o.useState(!0);return o.useEffect(()=>{t(Ua()==="chat")},[]),s.jsx(Jt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ft,{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),bp(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const Sn=new Map,Uo=new Map;function yp(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 vp(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 Uc(){const{sendCommand:e}=vt(),{injectEntries:t,getIdes:r}=Js();return o.useCallback(async(n,a)=>{if(!n)return;const i=(a==null?void 0:a.minFreshMs)??Rm,c=Uo.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<i)return;const l=Sn.get(n);if(l)return l;const u=(async()=>{const f=await e(n,"get_machine_runtime_stats"),d=yp(f);if(!d)return;const h=r().find(v=>v.id===n),m=vp(h,n,d.machine,d.timestamp||Date.now());t([m]),Uo.set(n,Date.now())})().finally(()=>{Sn.delete(n)});return Sn.set(n,u),u},[r,t,e])}function wp(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 jp(e,t){const{sendData:r}=vt(),{injectEntries:n,getIdes:a}=Js(),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(u=>Gt.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:t==null?void 0:t.intervalMs}},d=>{const h=a().find(v=>v.id===u),m=wp(h,u,d);n([m])}));return()=>{l.forEach(u=>u())}},[i,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function kp(e,t){const{sendData:r}=vt(),[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 u=Gt.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 u.initialSendAccepted?l=setTimeout(()=>{c(!1)},Em):c(!1),()=>{l&&clearTimeout(l),u()}},[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 Sp(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function zc(e){const{sendData:t}=vt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=Sp(e);if(!a||!e.sessionId||!t){n({});return}const i=Gt.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 Vc="adhdev_hiddenTabs";function Np(){try{const e=localStorage.getItem(Vc);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ps(e){try{localStorage.setItem(Vc,JSON.stringify([...e]))}catch{}}function Nn(e){return Ma(e)}function za(e,t){return ws(t).some(r=>e.has(r))}function Cp(){const[e,t]=o.useState(Np),r=o.useCallback(f=>{const d=Nn(f);t(h=>{const m=new Set(h);return m.has(d)?m.delete(d):m.add(d),ps(m),m})},[]),n=o.useCallback(f=>{const d=Nn(f);t(h=>{if(h.has(d))return h;const m=new Set(h);return m.add(d),ps(m),m})},[]),a=o.useCallback(f=>{const d=Nn(f);t(h=>{if(!h.has(d))return h;const m=new Set(h);return m.delete(d),ps(m),m})},[]),i=o.useCallback(()=>{t(f=>{if(f.size===0)return f;const d=new Set;return ps(d),d})},[]),c=o.useCallback((f,d)=>{t(h=>{const m=new Set(h);for(const v of d)m.add(v);return ps(m),m})},[]),l=o.useCallback((f,d)=>{t(h=>{const m=new Set(h);for(const v of d)m.delete(v);return ps(m),m})},[]),u=o.useCallback(f=>za(e,f),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function Gc(e){return e instanceof Error?e.message:String(e||"")}function qc(e){const t=Gc(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 Yc(e){const t=Gc(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Xc({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!et(e)||Je(e))return;const i=Rs(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:Bt(e),mode:t})}catch(l){const u=Yc(l);c&&!u&&a(f=>{const d={...f};return i===Jc(r,c)?delete d[c]:d[c]=i,d}),qc(l)?console.warn(u?"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 zo(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 Ip(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=zo(a,t),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>zo(u,t)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function Jc(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 Mp(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))Jc(t,a)===i&&(delete n[a],r=!0);return r?n:e}function Ap({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{sc()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:Sc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return qu(a),o.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{r(l=>{const u=Date.now(),f={};for(const[d,h]of Object.entries(l))u-h<5e3&&(f[d]=h);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 u=l.filter(f=>f.timestamp>c).slice(-100);return u.length===l.length?l:u})},6e4);return()=>clearInterval(i)},[n]),null}function Tp(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 Cn(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 Lp(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 Vo(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?Lp(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 Rp(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||""),Vo(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||""),Vo(r.activeChat)].join(":"))].join("|")}function _p(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 Pp(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 Dp(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Ep(e){const t=Dp(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 $p({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=o.useMemo(()=>Tp(e),[e]),i=o.useMemo(()=>Lc(e),[e]),c=o.useRef([]),l=o.useRef([]),u=o.useRef([]),f=o.useRef(new Map),d=o.useRef(new Map),h=o.useMemo(()=>{const I=new Map,y=[];for(const g of a){const{connectionState:$="new",machineName:A}=Rc(g,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),L=Rp(g),O=f.current.get(g.id);if(O&&O.ide===g&&O.sourceSignature===L&&O.connectionState===$&&O.machineName===A){I.set(g.id,O),y.push(...O.conversations);continue}const W=Oa(g,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),P={ide:g,sourceSignature:L,connectionState:$,machineName:A,conversations:W};I.set(g.id,P),y.push(...W)}f.current=I;const M=new Map,S=g=>{const $=Ep(g),A=d.current.get(g.tabKey);if(A&&A.signature===$)return M.set(g.tabKey,A),A.timestamp;const L={signature:$,timestamp:mc(g)||(A==null?void 0:A.timestamp)||0};return M.set(g.tabKey,L),L.timestamp},j=[...y].sort((g,$)=>fc(g,$,S));return d.current=M,j},[a,t,i]),m=o.useMemo(()=>{const I=_p(h,r);return Cn(c.current,I)?c.current:(c.current=I,I)},[h,r]),v=o.useMemo(()=>{const I=new Map,y=Array.from(new Set(m.map(M=>M.routeId)));for(const M of y){const S=Pt(m,M);S&&I.set(M,S)}return I},[m]),k=o.useMemo(()=>{const I=new Map;for(const y of m){const M=v.get(y.routeId),S=y.streamSource==="native"&&M?M:y;for(const j of ws({providerSessionId:y.providerSessionId,sessionId:y.sessionId}))I.set(j,S)}return I},[m,v]),p=o.useMemo(()=>Pp(m,v),[m,v]),x=o.useCallback(I=>{if(I)return k.get(I)},[k]),w=o.useCallback(I=>{if(I)return p.get(I)},[p]),b=o.useMemo(()=>{const I=m.filter(y=>!za(n,y));return Cn(l.current,I)?l.current:(l.current=I,I)},[m,n]),N=o.useMemo(()=>{const I=b.map(y=>y.tabKey);return Cn(u.current,I)?u.current:(u.current=I,I)},[b]);return{chatIdes:a,conversations:m,visibleConversations:b,visibleTabKeys:N,resolveConversationBySessionId:x,resolveConversationByTarget:w}}function Bp({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 u=new URLSearchParams(l);return u.delete("activeTab"),u},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function Kp({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){o.useEffect(()=>{it.setIdes(e)},[e]),o.useEffect(()=>{it.setResolveAction((a,i,c)=>{t(a,i,c).catch(()=>{})})},[t]),o.useEffect(()=>{const a=it.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(u=>u.id!==i.id)),c)});return()=>{a()}},[r]),o.useEffect(()=>{const a=wc.on("status_event",i=>{it.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 u=l.targetSessionId||l.targetKey||l.daemonId,f=n(u),d=(f==null?void 0:f.routeId)||l.daemonId;if(!d)return;const h=Number(l.buttonIndex),m=l.button||((p=f==null?void 0:f.modalButtons)==null?void 0:p[h])||"Approve",v=String(m).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(v);t(d,"resolve_action",{action:k?"approve":"reject",button:m,...Number.isFinite(h)&&{buttonIndex:h},...(f==null?void 0:f.sessionId)&&{targetSessionId:f.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(x=>console.error("[SW Action] approval failed:",x))};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 Op="adhdev_dashboardLayout_v1",Wp="adhdev_dashboardDockview_v1",Fp="adhdev_dashboardDockviewHiddenRestore_v1",Ks={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Va(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function Hp(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Qc(e){return`${Op}:${e}`}function Up(e){const t=Qc(e);return Va(t,null)}function zp(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=Qc(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Zc(e){return`${Wp}:${e}`}function Vp(e){const t=Zc(e);return Va(t,null)}function Gp(e,t){try{const r=Zc(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function el(e){return`${Fp}:${e}`}function qp(e){const t=el(e);return Va(t,{})}function Yp(e,t){try{const r=el(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Xp(){return{groupAssignments:[...Ks.groupAssignments],focusedGroup:Ks.focusedGroup,groupActiveTabIds:{...Ks.groupActiveTabIds},groupTabOrders:{...Ks.groupTabOrders},groupSizes:[...Ks.groupSizes]}}function Jp(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function Qp(){const[e]=o.useState(()=>Hp(typeof window<"u"?window.innerWidth:1280)),[t,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,u]=o.useState({}),[f,d]=o.useState([]),[h,m]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[v,k]=o.useState(!1),p=o.useCallback(()=>{if(v)return;const g=Up(e)??Xp();r(new Map(g.groupAssignments)),a(g.focusedGroup),c(g.groupActiveTabIds),u(g.groupTabOrders),d(g.groupSizes),k(!0)},[v,e]);o.useEffect(()=>{v&&zp(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)"),$=A=>m(A.matches);return g.addEventListener("change",$),()=>g.removeEventListener("change",$)},[]);const x=o.useCallback(g=>{r(g)},[]),w=o.useCallback(g=>{a(g)},[]),b=o.useCallback(g=>{c(g)},[]),N=o.useCallback(g=>{u(g)},[]),I=o.useCallback(g=>{d(g)},[]),y=o.useCallback(g=>{w(g)},[w]),M=o.useCallback((g,$)=>{c(A=>(A[g]??null)===($??null)?A:{...A,[g]:$})},[]),S=o.useCallback((g,$)=>{u(A=>{const L=A[g];return Jp(L,$)?A:{...A,[g]:$}})},[]),j=o.useCallback((g,$)=>{const A=$.get(g)??0;return M(A,g),y(A),A},[y,M]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:x,focusedGroup:n,updateFocusedGroup:w,focusGroup:y,groupActiveTabIds:i,updateGroupActiveTabIds:b,setGroupActiveTab:M,groupTabOrders:l,updateGroupTabOrders:N,setGroupTabOrder:S,groupSizes:f,updateGroupSizes:I,isMobile:h,hasHydratedStoredLayout:v,hydrateStoredLayout:p,focusConversationTab:j}}function Zp(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=Ia(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function eh({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,focusConversationTab:c,setSearchParams:l,historyModalOpen:u,activeConv:f,isRefreshingHistory:d,ides:h,handleRefreshHistory:m}){const v=o.useRef(!1),k=o.useRef(!1),p=o.useRef(null),x=o.useRef(!1);o.useEffect(()=>{if(!e||v.current||t.length===0)return;if(!a){i();return}const w=r(e);w&&(c(w.tabKey,n),v.current=!0,k.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(!(k.current||a)&&t.length!==0){if(!e){i(),k.current=!0;return}if(v.current){k.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(k.current||a)&&(i(),k.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,t.length,a,i]),o.useEffect(()=>{if(!u){x.current=!1;return}if(!f||x.current||d)return;const w=h.find(b=>b.id===f.routeId);w&&(!w.chats||w.chats.length===0||Zp(w.chats,f))&&(x.current=!0,m())},[u,f,d,h,m]),o.useEffect(()=>{if(!f)return;let w=null,b=0,N=-1,I=0;const y=()=>{w=null;const M=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(j=>j.offsetParent!==null);if(M.length===0){b<18&&(b+=1,w=requestAnimationFrame(y));return}let S=0;for(const j of M)j.scrollTop=j.scrollHeight,S+=j.scrollHeight;S===N?I+=1:(I=0,N=S),b+=1,!(I>=2||b>=18)&&(w=requestAnimationFrame(y))};return w=requestAnimationFrame(y),()=>{w!=null&&cancelAnimationFrame(w)}},[f==null?void 0:f.tabKey])}function In(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=Ia(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function tl({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:i}){const[c,l]=o.useState(!1),[u,f]=o.useState(!1),d=o.useCallback(async k=>{try{await e("standalone","launch_ide",{ideType:k,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),h=o.useCallback(async(k,p)=>{try{const x=k||(t==null?void 0:t.daemonId)||"",w=await e(x,"switch_chat",{id:p,sessionId:p,...js(t)}),b=w==null?void 0:w.result;if((w==null?void 0:w.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?$s(a,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?$s(a,`⚠️ Switch error: ${b}`):$s(a,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),$s(a,`❌ Switch failed: ${x.message||"connection error"}`)}},[t,e,a]),m=o.useCallback(async()=>{if(!(!t||c)){l(!0);try{const k=tr(t);await e(k,"new_chat",{...js(t)}),i(p=>({...p,[t.tabKey]:Date.now()}))}catch(k){console.error("New chat failed",k)}finally{l(!1)}}},[t,c,e,i]),v=o.useCallback(async()=>{var k,p;if(!(!t||u)){f(!0);try{const x=tr(t),w=async()=>e(x,"list_chats",{forceExpand:!0,...js(t)});let b=await w(),N=(b==null?void 0:b.chats)||((k=b==null?void 0:b.result)==null?void 0:k.chats);In(N,t)&&(await new Promise(I=>setTimeout(I,450)),b=await w(),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),In(N,t)&&!In(r,t)&&$s(a,"⚠️ History dialog did not fully open — try once more"))}catch(x){console.error("Refresh history failed",x)}finally{f(!1)}}},[t,r,u,e,n,a]);return{isCreatingChat:c,isRefreshingHistory:u,handleLaunchIde:d,handleSwitchSession:h,handleNewChat:m,handleRefreshHistory:v}}function th(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 sh(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function Go(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 wr(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 u=a[l];typeof u=="number"&&u>0&&i.set(c,u)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function qo(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 rh(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 nh(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 Yo(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 Xo(e){return Array(e).fill(100/e)}function ah({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:i,updateGroupSizes:c,isMobile:l,visibleConversations:u,visibleTabKeys:f}){const d=o.useRef(null),h=o.useMemo(()=>wr(e,f),[e,f]),m=h.assignments,v=o.useMemo(()=>l?1:h.groupCount,[h.groupCount,l]),k=v>1,p=o.useCallback((y,M)=>{t(S=>{const j=new Map(wr(S,f).assignments);return M===0?j.delete(y):j.set(y,M),j}),n(S=>({...S,[M]:y})),r(M)},[t,f,n,r]),x=o.useCallback(y=>{t(M=>{const S=wr(M,f).assignments,j=new Map;for(const[g,$]of S)$!==y&&($>y?j.set(g,$-1):j.set(g,$));return j}),c(M=>{if(M.length<=1)return[];const S=[...M];S.splice(y,1);const j=S.reduce((g,$)=>g+$,0);return j>0?S.map(g=>g/j*100):[]}),r(0)},[t,f,c,r]),w=o.useCallback((y,M)=>{M.preventDefault();const S=d.current;if(!S)return;const j=M.clientX,g=S.offsetWidth,$=i.length===v?[...i]:Xo(v),A=O=>{const P=(O.clientX-j)/g*100,C=[...$];C[y]=Math.max(15,$[y]+P),C[y+1]=Math.max(15,$[y+1]-P),c(C)},L=()=>{document.removeEventListener("mousemove",A),document.removeEventListener("mouseup",L),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",A),document.addEventListener("mouseup",L)},[i,v,c]),b=o.useCallback((y,M,S)=>{if(v>=4)return;const j=S==="left"?M:M+1;t(g=>{const $=wr(g,f).assignments,A=new Map;for(const L of u){const O=$.get(L.tabKey)??0,W=O>=j?O+1:O;W>0&&A.set(L.tabKey,W)}return j>0&&A.set(y,j),A}),c(g=>{const $=g.length===v?[...g]:Xo(v),A=$[M]??100/v,L=Math.max(15,A/2),O=Math.max(15,A/2),W=[...$];W[M]=L,W.splice(j,0,O);const P=W.reduce((C,T)=>C+T,0);return W.map(C=>C/P*100)}),n(g=>{const $=Yo(g,j);return $[j]=y,$}),a(g=>{const $=Yo(g,j);return $[j]=[y],$}),r(j)},[v,t,f,u,c,n,a,r]);o.useEffect(()=>{th(e,m)||t(m)},[e,m,t]),o.useEffect(()=>{const{mapping:y,usedGroups:M}=h;n(S=>{const j=qo(S,y);return Go(S,j)?S:j}),a(S=>{const j=qo(S,y);return Go(S,j)?S:j}),r(S=>{const j=l?0:rh(S,M,y);return S===j?S:j}),c(S=>{const j=l?[]:nh(S,M,h.groupCount);return sh(S,j)?S:j})},[h,l,n,a,r,c]);const N=o.useMemo(()=>{const y=Array.from({length:v},()=>[]);for(const M of u){const S=m.get(M.tabKey)??0,j=Math.min(S,v-1);y[j].push(M)}return y},[u,m,v]),I=o.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:d,normalizedGroupAssignments:m,numGroups:v,isSplitMode:k,groupedConvs:N,moveTabToGroup:p,closeGroup:x,handleResizeStart:w,splitTabRelative:b,clearAllSplits:I}}function oh({ides:e,sendDaemonCommand:t}){const r="0.9.33",n=o.useMemo(()=>e.filter(d=>d.type!=="adhdev-daemon"?!1:Oc(d,r)).sort((d,h)=>Number(Gs(h,r))-Number(Gs(d,r))),[r,e]),a=o.useMemo(()=>n.some(d=>Gs(d,r)),[r,n]),[i,c]=o.useState(!1),[l,u]=o.useState({}),f=o.useCallback(async d=>{var h,m;u(v=>({...v,[d]:"upgrading"}));try{const v=await t(d,"daemon_upgrade",{});(h=v==null?void 0:v.result)!=null&&h.upgraded||(m=v==null?void 0:v.result)!=null&&m.success?u(k=>({...k,[d]:"done"})):u(k=>({...k,[d]:"error"}))}catch{u(v=>({...v,[d]:"error"}))}},[t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:f}}const sl=80;function Pr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function ih(e){return{...e,createdAt:Pr(e.createdAt),updatedAt:Pr(e.updatedAt,e.createdAt),lastEventAt:Pr(e.lastEventAt,e.updatedAt||e.createdAt)}}function ch(e){const t=Ma(e);return t==="unknown:"?e.id:t}function lh(e){return[e.type,uc(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function dh(e,t=sl){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=ch(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 uh(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=Zr(a,t),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const u=Pr(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),f=lh({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(ih({id:f,dedupKey:f,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:ic(a),preview:gm(a),createdAt:u,updatedAt:u,lastEventAt:u}))}return dh(n)}function mh(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function fh(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=sl}=e,a=o.useMemo(()=>uh(t,r).slice(0,Math.max(0,n)),[t,r,n]),i=o.useMemo(()=>mh(a),[a]);return{notifications:a,unreadCount:i}}function ph({notifications:e,sendDaemonCommand:t}){const r=o.useCallback(i=>{const c=e.find(u=>u.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 sn(...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 hh(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 rn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=hh(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 xh(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 bh(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function nn(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=bh(n);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(n==null?void 0:n.error)||"Could not browse folder");const i=typeof(a==null?void 0:a.path)=="string"?a.path:r,c=i.includes("\\")?"\\":"/",l=(f,d)=>/^[A-Za-z]:\\?$/.test(f)?`${f.replace(/\\?$/,"\\")}${d}`:f==="/"||f==="\\"?`${c}${d}`:`${f.replace(/[\\/]+$/,"")}${c}${d}`,u=Array.isArray(a==null?void 0:a.files)?a.files.filter(f=>(f==null?void 0:f.type)==="directory"&&typeof(f==null?void 0:f.name)=="string").map(f=>({name:f.name,path:typeof(f==null?void 0:f.path)=="string"&&f.path.trim()?f.path:l(i,f.name)})).sort((f,d)=>f.name.localeCompare(d.name)):[];return{path:i,directories:u}}function gh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Jo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function yh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function vh({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=Jo(n.workspacePath),l=e.find(f=>{var k,p,x,w;if(!f||f.type==="adhdev-daemon"||gh(f.daemonId||f.id)!==n.machineId||(er(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=Jo(f.workspace||f.runtimeWorkspaceLabel);return b?b===c:!1}return Number(f.lastUpdated||f._lastUpdate||f.timestamp||((w=(x=(p=(k=f.activeChat)==null?void 0:k.messages)==null?void 0:p.at)==null?void 0:x.call(p,-1))==null?void 0:w.timestamp)||0)>=n.startedAt-5e3});if(!l)return;const u=pc({entrySessionId:l.sessionId,entryInstanceId:l.instanceId,entryRouteId:l.id,conversations:t});u&&(a(null),r(u))},[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 wh({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:i}){const c=o.useCallback(async(m,v)=>nn(e,m,v),[e]),l=o.useCallback(async(m,v)=>{if(!v.trim())return{ok:!1,error:"Choose a workspace path first."};try{const k=await e(m,"workspace_add",{path:v.trim()});return k!=null&&k.success?{ok:!0}:{ok:!1,error:(k==null?void 0:k.error)||"Could not save workspace"}}catch(k){return{ok:!1,error:k instanceof Error?k.message:"Could not save workspace"}}},[e]),u=o.useCallback(async(m,v,k)=>{var p;try{const x={ideType:v,enableCdp:!0};(p=k==null?void 0:k.workspacePath)!=null&&p.trim()&&(x.workspace=k.workspacePath.trim());const w=await e(m,"launch_ide",x);return!(w!=null&&w.success)&&(w==null?void 0:w.success)!==void 0?{ok:!1,error:(w==null?void 0:w.error)||"Could not launch IDE"}:(t({machineId:m,kind:"ide",providerType:v,workspacePath:(k==null?void 0:k.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(x){return{ok:!1,error:x instanceof Error?x.message:"Could not launch IDE"}}},[e,t]),f=o.useCallback(async(m,v,k,p)=>{var w,b,N;const x=Date.now();try{const I={cliType:k};(w=p==null?void 0:p.workspacePath)!=null&&w.trim()?I.dir=p.workspacePath.trim():p!=null&&p.workspaceId&&(I.workspaceId=p.workspaceId),(b=p==null?void 0:p.resumeSessionId)!=null&&b.trim()&&(I.resumeSessionId=p.resumeSessionId.trim()),Array.isArray(p==null?void 0:p.cliArgs)&&p.cliArgs.length>0&&(I.cliArgs=p.cliArgs),(N=p==null?void 0:p.initialModel)!=null&&N.trim()&&(I.initialModel=p.initialModel.trim());const y=await e(m,"launch_cli",I),M=(y==null?void 0:y.result)||y,S=(M==null?void 0:M.sessionId)||(M==null?void 0:M.id);return y!=null&&y.success&&S?(r(S),{ok:!0}):y!=null&&y.success?(t({machineId:m,kind:v,providerType:k,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:x}),{ok:!0}):{ok:!1,error:(y==null?void 0:y.error)||(M==null?void 0:M.error)||`Could not launch ${v.toUpperCase()} session`}}catch(I){return yh(I)?(t({machineId:m,kind:v,providerType:k,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:x}),{ok:!0}):{ok:!1,error:I instanceof Error?I.message:`Could not launch ${v.toUpperCase()} session`}}},[r,e,t]),d=o.useCallback(async(m,v)=>{if(!m||!v)return[];try{const k=await e(m,"list_saved_sessions",{providerType:v,kind:"cli",limit:30}),p=(k==null?void 0:k.result)??k;return Array.isArray(p==null?void 0:p.sessions)?p.sessions:[]}catch(k){return console.error("List saved sessions failed",k),[]}},[e]),h=o.useCallback(async m=>{await Xc({conversation:n,mode:m,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:i})},[n,a,e,i]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:l,handleLaunchMachineIde:u,handleLaunchMachineProvider:f,handleListMachineSavedSessions:d,setActiveCliViewMode:h}}function jh(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 kh(e,t,r=Date.now()){return!e||!jh(t)?null:{tabKey:e,nonce:r}}function Sh({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:i,setSearchParams:c}){const[l,u]=o.useState(null),[f,d]=o.useState(null),h=o.useMemo(()=>{var x,w;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((x=i[a])==null?void 0:x[0])||((w=i[0])==null?void 0:w[0])},[t,l,a,n,i,e,r]),m=o.useCallback(p=>{u(p)},[]),v=o.useCallback(p=>{u(p.tabKey),c(x=>{const w=new URLSearchParams(x),b=vm(p);return b?w.set("activeTab",b):w.delete("activeTab"),w},{replace:!0})},[c]),k=o.useCallback((p,x)=>{const w=kh(p,x);w&&d(w)},[]);return{activeConv:h,openDesktopConversation:v,requestScrollToBottom:k,scrollToBottomRequest:f,setDesktopActiveTab:m}}function Nh({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:i,setToasts:c,setClearedTabs:l,setSearchParams:u}){var C;const[f,d]=o.useState(!1),[h,m]=o.useState([]),[v,k]=o.useState(()=>pt()),[p,x]=o.useState(!1),[w,b]=o.useState(null),N=o.useRef(null),I=o.useMemo(()=>r||t||e,[e,r,t]),y=!!I&&et(I)&&!Je(I),M=o.useMemo(()=>{if(!I||!y)return null;const T=I.daemonId||I.routeId||"",V=Bt(I);return`${T}:${V}`},[I,y]),{isCreatingChat:S,isRefreshingHistory:j,handleSwitchSession:g,handleNewChat:$,handleRefreshHistory:A}=tl({sendDaemonCommand:a,activeConv:I,chats:(C=n.find(T=>T.id===(I==null?void 0:I.routeId)))==null?void 0:C.chats,updateRouteChats:i,setToasts:c,setClearedTabs:l}),L=o.useCallback(()=>{d(!0)},[]),O=o.useCallback(()=>{d(!1)},[]),W=o.useCallback(async()=>{if(!(!I||!y||p)){x(!0);try{const T=I.daemonId||I.routeId,V=Bt(I),E=await a(T,"list_saved_sessions",{agentType:V,providerType:V,kind:"cli",limit:50}),_=(E==null?void 0:E.result)??E;m(Array.isArray(_==null?void 0:_.sessions)?_.sessions:[])}catch(T){console.error("Refresh saved sessions failed",T),m([])}finally{x(!1)}}},[I,p,y,a]);o.useEffect(()=>{if(!f){N.current=null;return}if(!y){N.current=null,m([]),x(!1);return}!M||p||N.current!==M&&(N.current=M,W())},[W,f,p,y,M]);const P=o.useCallback(async T=>{if(!I||!y||!T.providerSessionId||!T.workspace)return;const V=I.daemonId||I.routeId,E=Bt(I);try{b(T.providerSessionId);const _=await a(V,"launch_cli",{cliType:E,dir:T.workspace,resumeSessionId:T.providerSessionId,initialModel:ec(T.summaryMetadata,"model",{preferShortValue:!0})||void 0}),F=(_==null?void 0:_.result)??_,J=typeof(F==null?void 0:F.sessionId)=="string"?F.sessionId:typeof(F==null?void 0:F.id)=="string"?F.id:"";J&&u(xe=>{const ce=new URLSearchParams(xe);return ce.set("activeTab",J),ce},{replace:!0}),O()}catch(_){console.error("Resume saved session failed",_)}finally{b(null)}},[O,I,y,a,u]);return{historyModalOpen:f,openHistoryModal:L,closeHistoryModal:O,historyTargetConv:I,isSavedSessionHistoryTarget:y,isHistoryCreatingChat:S,isHistoryRefreshingHistory:j,handleHistorySwitchSession:g,handleHistoryNewChat:$,handleHistoryRefresh:A,savedHistorySessions:h,savedHistoryFilters:v,setSavedHistoryFilters:k,isSavedHistoryLoading:p,resumingSavedHistorySessionId:w,handleRefreshSavedHistory:W,handleResumeSavedHistorySession:P}}function Ch({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[u,f]=o.useState(null),[d,h]=o.useState(null),m=o.useMemo(()=>{if(e||!n)return null;const w=l(n);return w&&!et(w)&&!Je(w)?w:null},[e,n,l]),v=o.useMemo(()=>{const w=u==null?void 0:u.routeId;if(!w)return null;const b=u!=null&&u.tabKey?i.find(N=>N.tabKey===u.tabKey):a?i.find(N=>N.tabKey===a):null;return(b==null?void 0:b.routeId)===w?b:Pt(i,w)},[i,u,a]),k=o.useMemo(()=>{if(v)return c.find(w=>w.id===v.routeId)},[c,v]);o.useEffect(()=>{m&&(f({routeId:m.routeId,tabKey:Ao(m)}),h(m),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,m]);const p=o.useCallback(w=>{w&&(f({routeId:w.routeId,tabKey:Ao(w)}),h(w))},[]),x=o.useCallback(()=>{f(null),h(null)},[]);return{remoteDialogConv:v,remoteDialogIdeEntry:k,remoteDialogActiveConv:d,setRemoteDialogActiveConv:h,openRemoteDialog:p,closeRemoteDialog:x}}function Ih({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l,activeConv:u,sendDaemonCommand:f}){const{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:m,setRemoteDialogActiveConv:v,openRemoteDialog:k,closeRemoteDialog:p}=Ch({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}),[x,w]=o.useState(!1),[b,N]=o.useState(null),I=o.useCallback(async S=>{const j=S||u;!j||!et(j)&&!Je(j)||(N(j),w(!0))},[u]),y=o.useCallback(()=>{w(!1),N(null)},[]),M=o.useCallback(async S=>{const j=b||u;if(!j||!et(j)&&!Je(j)){y();return}w(!1);try{const g=Bt(j),$=j.routeId||j.daemonId||"";await f($,"stop_cli",{cliType:g,targetSessionId:j.sessionId,mode:S})}catch(g){console.error("Stop CLI failed:",g)}finally{N(null)}},[u,y,b,f]);return{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:m,setRemoteDialogActiveConv:v,openRemoteDialog:k,closeRemoteDialog:p,cliStopDialogOpen:x,cliStopTargetConv:b,requestCliStop:I,cancelCliStop:y,confirmCliStop:M}}function rl(){return"select_session"}function Mh(){return"open_panel"}function Ah({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function Th(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function Qo(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function Zo(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Ga(e){return e instanceof Error?e.message:String(e||"")}function ei(e){const t=Ga(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function ti(e,t){const r=Ga(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function an({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,i]=o.useState(!1),[c,l]=o.useState(!1),[u,f]=o.useState(null),d=o.useRef(!1),h=o.useRef(null);o.useEffect(()=>{f(null)},[t==null?void 0:t.tabKey]);const m=o.useCallback(async x=>{if(!t)return!1;const w=x.trim(),b=La(t);if(Ah({hasMessage:!!w,blockedMessage:b,sendInFlight:d.current}))return b&&f(b),!1;const N=Date.now(),I={tabKey:t.tabKey,message:w,timestamp:N};if(Th(h.current,I))return f(null),!0;d.current=!0,l(!0),f(null),h.current=I;try{const y=tr(t);if(!y)return h.current=Qo(h.current,I),f("Unable to send message right now."),!1;const M=await e(y,"send_chat",{message:w,...js(t)}),S=Zo(M);if(S!=null&&S.deduplicated)return f(null),!0;if((S==null?void 0:S.sent)===!1)throw new Error((S==null?void 0:S.error)||"Send failed");if((S==null?void 0:S.success)===!1)throw new Error((S==null?void 0:S.error)||"Send failed");return f(null),!0}catch(y){const M=Ga(y);return M.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",M):console.warn("Send blocked/failed",y),h.current=Qo(h.current,I),f(Km(y)),!1}finally{d.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(x){console.error("Relaunch failed",x)}},[t,e]),k=o.useCallback(async x=>{if(t)try{const b=(t.modalButtons||[]).indexOf(x),N=x.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),I=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(N),y=tr(t);if(!y)return;const M=await e(y,"resolve_action",{button:x,action:I?"approve":"reject",...b>=0&&{buttonIndex:b},...js(t)}),S=Zo(M);S.success||r(j=>[...j,{routeId:t.tabKey,text:ti(x,S==null?void 0:S.error),timestamp:Date.now()}])}catch(w){ei(w)||console.error("[ModalButton] Error:",w),r(b=>[...b,{routeId:t.tabKey,text:ei(w)?ti(x,w):`❌ **${x}** error`,timestamp:Date.now()}])}},[t,e,r]),p=o.useCallback(async()=>{if(!(!t||a)){i(!0);try{await e(t.routeId,Mh(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(x){console.error("Focus agent failed",x)}finally{i(!1)}}},[t,a,e]);return{isSendingChat:c,sendFeedbackMessage:u,isFocusingAgent:a,handleSendChat:m,handleRelaunch:v,handleModalButton:k,handleFocusAgent:p}}function Mn(e,t=!0){return(e??!0)&&t}const qa=o.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d=null,handleFocusAgent:h,isFocusingAgent:m,actionLogs:v,userName:k,scrollToBottomRequestNonce:p,isInputActive:x=!0,isVisible:w=!0}){const[b,N]=o.useState(n),I=o.useRef(n);o.useEffect(()=>{const L=I.current;if(I.current=n,!n){N(!1);return}if(L){N(!0);return}N(!1);let O=0,W=0;return O=window.requestAnimationFrame(()=>{W=window.requestAnimationFrame(()=>{N(!0)})}),()=>{window.cancelAnimationFrame(O),window.cancelAnimationFrame(W)}},[n]);const y=n&&b,M=!n||!b,S=Mn(w,n),j=Mn(w,M),g=Mn(w),$=zc(t),A=$.status||$.modalMessage||$.modalButtons?{...t,...$.status?{status:$.status}:{},...$.modalMessage!==void 0?{modalMessage:$.modalMessage}:{},...$.modalButtons!==void 0?{modalButtons:$.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(Yi,{activeConv:A,onModalButton:c}),A.transport!=="pty"&&A.transport!=="acp"&&A.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(Qs,{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,A.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(gf,{activeConv:A,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,isVisible:S,isInputActive:x&&S})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:M?"visible":"hidden",pointerEvents:M?"auto":"none"},children:s.jsx(aa,{activeConv:A,ideEntry:a,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:m,actionLogs:v,userName:k,scrollToBottomRequestNonce:p,isInputActive:x&&j,isVisible:j})})]}):s.jsx(aa,{activeConv:A,ideEntry:a,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:m,actionLogs:v,userName:k,scrollToBottomRequestNonce:p,isInputActive:x&&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 Lh({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:u,onBack:f,onOpenNativeConversation:d,onOpenMachine:h,onOpenHistory:m,onOpenRemote:v,onHideConversation:k,onStopCli:p,cliViewMode:x,onSetCliViewMode:w,handleSendChat:b,handleFocusAgent:N,handleModalButton:I,handleRelaunch:y}){const M=o.useRef(null),S=et(e)&&!t,j=S&&x==="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(ga,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:at(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(hc,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>h(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[S&&x&&s.jsx(Pa,{mode:x,onChange:w,compact:!0}),S&&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(yt,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>m(e),type:"button",children:s.jsx(ya,{size:14})}),!t&&!S&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>v(e),type:"button",children:s.jsx(St,{size:14})}),k&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>k(e),type:"button",title:"Close chat",children:s.jsx(yt,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(qa,{activeConv:e,clearToken:0,isCliTerminal:j,ideEntry:n,terminalRef:M,handleModalButton:I,handleRelaunch:y,handleSendChat:b,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:N,isFocusingAgent:u,actionLogs:a,userName:i})})]})}const An={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 Rh(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function nl(){const[e,t]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{t(Rh())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(An[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:An[c].prompt}),s.jsx("span",{className:"flex-1 break-all",children:An[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 al({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:St},{key:"chats",label:"Chats",icon:Ft}];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 jr({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 Os({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 kr({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:u,isConnecting:f}=Ls(e.conversation),d=at(e.conversation),h=ds(e.conversation),m=kc(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",k=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",x=c?"text-text-muted":"text-text-secondary",w=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 ${k}`,style:a?{color:"var(--accent-on-primary)"}:void 0,children:r(d)}),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:d}),!i&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${b}`,children:qi(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${x}`,children:[h,u?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] ${w}`,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 si({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 _h({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:u,onShowConversation:f,onShowAllHidden:d,onOpenNewSession:h,onOpenMachine:m,onOpenSettings:v,onSectionChange:k,wsStatus:p="connected",isStandalone:x=!1}){const w=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,I=e==="machines"?"Machines":"Chats",y=x?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",M=x?"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:I}),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(Jr,{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(Xr,{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] ${M}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:w?s.jsx(Os,{icon:s.jsx(si,{label:"Reconnecting…"}),title:p==="offline"?"Network offline":p==="auth_failed"?"Session expired":"Reconnecting",subtitle:p==="offline"?"Waiting for network…":p==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):c.length===0?s.jsx(Os,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:x?"Waiting for your daemon":"Connect your machines",subtitle:x?"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:!x&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(nl,{})})}):s.jsx(hs,{children:c.map((S,j)=>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] ${j>0?"border-t border-border-subtle/70":""}`,onClick:()=>m(S.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(S.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:S.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:S.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[S.unread," new"]}):S.total>0?`${S.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:S.subtitle}),S.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[S.total," chat",S.total!==1?"s":"",S.unread>0?` · ${S.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},S.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(jr,{title:"Needs attention",className:"mb-0"}),s.jsx(hs,{children:t.map((S,j)=>s.jsx("div",{className:j>0?"border-t border-border-subtle/70":"",children:s.jsx(kr,{item:S,type:"needs_attention",getAvatarText:l,onOpenConversation:u})},S.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(jr,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(hs,{children:r.map((S,j)=>s.jsx("div",{className:j>0?"border-t border-border-subtle/70":"",children:s.jsx(kr,{item:S,type:"task_complete",getAvatarText:l,onOpenConversation:u})},S.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(jr,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(hs,{children:n.map((S,j)=>s.jsx("div",{className:j>0?"border-t border-border-subtle/70":"",children:s.jsx(kr,{item:S,type:"working",getAvatarText:l,onOpenConversation:u})},S.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(jr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(hs,{children:a.map((S,j)=>s.jsx("div",{className:j>0?"border-t border-border-subtle/70":"",children:s.jsx(kr,{item:S,type:"earlier",getAvatarText:l,onOpenConversation:u})},S.conversation.tabKey))}):N?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):w?s.jsx(Os,{icon:s.jsx(si,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):b?s.jsx(Os,{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(Ft,{size:20})}),title:"No conversations yet",subtitle:Cc,children:h&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:h,"aria-label":Et,title:Et,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:Et})]})}):s.jsx(Os,{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:d,children:"Restore all"})]}),s.jsx(hs,{className:"bg-bg-secondary/25",children:i.map((S,j)=>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 ${j>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(S),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(at(S))}),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:at(S)}),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:ds(S)}),s.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},S.tabKey))})]})]}),e==="chats"&&h&&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:h,"aria-label":Et,title:Et,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(al,{section:e,onSectionChange:k})]})}function Ph(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 ol(e){const t=[e.workspace||"Workspace unknown"],r=ls(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=Ph(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function on({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:u,onConfirm:f}){const[d,h]=o.useState(r);o.useEffect(()=>{h(r)},[r]);const m=xh(r),v=d.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(yt,{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||u(m)},disabled:!m||a,children:[s.jsx(ga,{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:d,onChange:k=>h(k.target.value),onKeyDown:k=>{k.key!=="Enter"||!v||a||(k.preventDefault(),u(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||u(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(k=>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:()=>u(k.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:k.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:k.path})]})]},k.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 Ya({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:u=!1,showArgsInput:f,argsValue:d,onArgsChange:h,showModelInput:m,modelValue:v,onModelChange:k,historyProviderNode:p,onConfirm:x,onCancel:w}){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:w,"aria-label":"Close launch confirmation",children:s.jsx(yt,{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:u,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&&k&&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=>k(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:u})]}),f&&h&&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:d||"",onChange:N=>h(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:u})]})]}),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:w,disabled:u,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:x,disabled:u,children:[s.jsx(wa,{size:14}),u?l:c]})]})]})})}function ri(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function as(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 u of t.workspaces||[])i.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${ri(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const c=(r==null?void 0:r.trim())||"",l=c?(t.workspaces||[]).find(u=>u.path===c):null;if(c&&!l&&i.push({key:`custom:${c}`,label:ri(c),description:c,workspaceId:null,workspacePath:c}),n){const u=`saved:${n}`;if(i.some(f=>f.key===u))return{options:i,selectedKey:u}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function Dh(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Eh(e){return[Dh(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function $h(e){return e.lastLaunchedAt?Qr(e.lastLaunchedAt):""}function il(e){return{metaText:Eh(e),updatedLabel:$h(e)}}function Tn(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function Bh({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var ct,mt,lt,ut;const c=or(),[l,u]=o.useState(!1),f=(((ct=e.detectedIdes)==null?void 0:ct.length)||0)>0,d=o.useMemo(()=>(e.workspaces||[]).map(Ie=>({id:Ie.id,path:Ie.path,label:Ie.label})),[e]),h=e.defaultWorkspaceId||null,[m,v]=o.useState(h||((mt=d[0])==null?void 0:mt.id)||""),[k,p]=o.useState(""),[x,w]=o.useState(""),[b,N]=o.useState([]),[I,y]=o.useState(!1),[M,S]=o.useState(""),[j,g]=o.useState(!1),[$,A]=o.useState(Tn(f,t.length,r.length)),L=o.useRef(null),[O,W]=o.useState(null),P=o.useRef("__home__"),[C,T]=o.useState("__home__"),[V,E]=o.useState(""),[_,F]=o.useState(""),[J,xe]=o.useState(""),[ce,te]=o.useState([]),[be,ge]=o.useState(()=>pt().textQuery),[ve,H]=o.useState(()=>pt().workspaceQuery),[U,Q]=o.useState(()=>pt().modelQuery),[de,ne]=o.useState(()=>pt().resumableOnly),[fe,ae]=o.useState(()=>pt().sortMode),[pe,le]=o.useState(!1),[ue,oe]=o.useState(!1),ye=o.useRef(null),he=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const ke=m==="__custom__"?k.trim():((lt=d.find(Ie=>Ie.id===m))==null?void 0:lt.path)||"",D=m==="__custom__"&&!!ke&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),Y=m!=="__custom__"&&((ut=d.find(Ie=>Ie.id===m))==null?void 0:ut.path)||"",G=o.useMemo(()=>(e.recentLaunches||[]).map(Ie=>Ie.workspace),[e]),X=o.useCallback(async Ie=>{y(!0),S("");try{const Ee=await a(Ie);w(Ee.path),p(Ee.path),N(Ee.directories)}catch(Ee){S(Ee instanceof Error?Ee.message:"Could not load folder")}finally{y(!1)}},[a]),re=o.useCallback(()=>{var Ee;v("__custom__"),g(!0);const Ie=rn(e.platform,sn(k.trim(),Y,G,e.defaultWorkspacePath,(Ee=d.find(Qe=>Qe.id===h))==null?void 0:Ee.path,d.map(Qe=>Qe.path)));X(Ie)},[k,h,X,G,Y,e.platform,d]),Se=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("")},[]),Ae=o.useCallback(Ie=>{if(v(Ie),Ie==="__custom__"){re();return}p("")},[re]),$e=o.useCallback(Ie=>{v("__custom__"),p(Ie)},[]),Be=o.useCallback((Ie,Ee)=>{L.current=Ee,P.current=Ie.selectedWorkspaceKey||"__home__",T(Ie.selectedWorkspaceKey||"__home__"),E(Ie.initialArgs||""),F(Ie.initialModel||""),xe(""),te([]);const Qe=Ie.providerType?`${e.id}:${Ie.providerType}`:null;if(Nf(he.current,Qe)){const Ve=pt();ge(Ve.textQuery),H(Ve.workspaceQuery),Q(Ve.modelQuery),ne(Ve.resumableOnly),ae(Ve.sortMode)}he.current=Qe,W(Ie),Ie.providerType&&i&&(le(!0),i(Ie.providerType).then(Ve=>te(Ve||[])).catch(Ve=>console.warn("Failed to load saved sessions",Ve)).finally(()=>le(!1)))},[i,e.id]),Ke=o.useMemo(()=>Ic(ce,{textQuery:be,workspaceQuery:ve,modelQuery:U,resumableOnly:de,sortMode:fe}),[U,de,ce,fe,be,ve]);o.useEffect(()=>{J&&(Ke.some(Ie=>Ie.providerSessionId===J)||xe(""))},[Ke,J]);const qe=o.useCallback(()=>{L.current&&(oe(!0),L.current().finally(()=>{L.current=null,oe(!1),W(null)}))},[]),ze=o.useCallback(()=>{L.current=null,W(null)},[]),rt=o.useCallback(Ie=>{P.current=Ie,T(Ie)},[]);return o.useEffect(()=>{var Ie;ye.current!==e.id&&(ye.current=e.id,v(h||((Ie=d[0])==null?void 0:Ie.id)||"__custom__"),p(""),w(""),N([]),S(""),g(!1),ge(pt().textQuery),H(pt().workspaceQuery),Q(pt().modelQuery),ne(pt().resumableOnly),ae(pt().sortMode),he.current=null,A(Tn(f,t.length,r.length)))},[r.length,t.length,h,f,e.id,d]),o.useEffect(()=>{var Ie;m!=="__custom__"&&(m&&d.some(Ee=>Ee.id===m)||v(h||((Ie=d[0])==null?void 0:Ie.id)||"__custom__"))},[h,m,d]),o.useEffect(()=>{$==="ide"&&f||$==="cli"&&t.length>0||$==="acp"&&r.length>0||A(Tn(f,t.length,r.length))},[$,r.length,t.length,f]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:f,workspaceRows:d,defaultWorkspaceId:h,workspaceChoice:m,customWorkspacePath:k,browseCurrentPath:x,browseDirectories:b,browseBusy:I,browseError:M,browseDialogOpen:j,activeLauncherKind:$,launchConfirm:O,launchConfirmWorkspaceKeyRef:P,launchConfirmWorkspaceKey:C,launchConfirmArgs:V,launchConfirmModel:_,launchConfirmResumeId:J,launchConfirmSavedSessions:ce,launchConfirmTextFilter:be,launchConfirmWorkspaceFilter:ve,launchConfirmModelFilter:U,launchConfirmResumableOnly:de,launchConfirmSortMode:fe,filteredLaunchConfirmSavedSessions:Ke,launchConfirmSessionsLoading:pe,launchConfirmBusy:ue,resolvedWorkspacePath:ke,canCreateMissingWorkspace:D,openBrowseDialog:re,loadBrowsePath:X,handleWorkspaceChoiceChange:Ae,chooseCustomWorkspacePath:$e,setCustomWorkspacePath:p,setBrowseDialogOpen:g,setActiveLauncherKind:A,openLaunchConfirm:Be,handleConfirmLaunch:qe,closeLaunchConfirm:ze,setWorkspaceSelectionFromOption:Se,setLaunchConfirmWorkspaceKeyAndSync:rt,setLaunchConfirmArgs:E,setLaunchConfirmModel:F,setLaunchConfirmResumeId:xe,setLaunchConfirmTextFilter:ge,setLaunchConfirmWorkspaceFilter:H,setLaunchConfirmModelFilter:Q,setLaunchConfirmResumableOnly:ne,setLaunchConfirmSortMode:ae}}function Kh({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:u,section:f,showBottomNav:d,onBack:h,onSectionChange:m,onOpenConversation:v,onOpenRecent:k,onOpenMachineDetails:p,onMachineUpgrade:x,onLaunchDetectedIde:w,onAddWorkspace:b,onBrowseDirectory:N,onLaunchWorkspaceProvider:I,onListSavedSessions:y}){const M=C=>C==="ide"?"IDE":C==="cli"?"CLI":"ACP",S=r.slice(0,4),j=t.slice(0,3),g=Bh({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:N,onListSavedSessions:y}),$=o.useMemo(()=>S.map(C=>{const{metaText:T,updatedLabel:V}=il(C);return{key:`recent-launch:${C.id}`,primary:C.label,secondary:T,updatedLabel:V,onClick:()=>{const{options:E,selectedKey:_}=as({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspacePath:C.workspace});g.openLaunchConfirm({title:C.kind==="ide"?ts("restart-ide",C.label):C.providerSessionId?$a(C.label):ts("start-fresh",C.label),description:C.kind==="ide"?ss("restart-ide"):C.providerSessionId?Ba():ss("start-fresh"),confirmLabel:C.kind==="ide"?Is("restart-ide"):C.providerSessionId?zr(!0):Is("start-fresh"),busyLabel:C.kind==="ide"?Ms("restart-ide"):C.providerSessionId?Da(!0):Ms("start-fresh"),workspaceOptions:E,selectedWorkspaceKey:_,details:[{label:"Mode",value:M(C.kind)},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]},async()=>{const F=E.find(J=>J.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(F),await k({...C,workspace:(F==null?void 0:F.workspacePath)??null})})}}}),[g,k,S]),A=o.useMemo(()=>j.map(C=>({key:`recent-chat:${C.conversation.tabKey}`,primary:at(C.conversation),secondary:pf(C.conversation,{timestampLabel:C.timestamp?qi(C.timestamp):null}),unread:C.unread,onClick:()=>v(C.conversation)})),[v,j]),L=g.showAllRecent?$:$.slice(0,4),O=$.length>0,W=A.length>0,P=u?"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 ${P} 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:h,type:"button","aria-label":"Back",children:s.jsx(ga,{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:Mt(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:[W&&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:A.map(C=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${C.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:C.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))})]}),O&&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:L.map(C=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:C.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:C.primary}),C.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:C.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))}),$.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(C=>!C),children:g.showAllRecent?"Show fewer":`Show ${$.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:C=>g.handleWorkspaceChoiceChange(C.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:g.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[g.workspaceRows.map(C=>s.jsxs("option",{value:C.id,children:[C.id===g.defaultWorkspaceId?"⭐ ":"",en(C.path,C.label)||C.path]},C.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(C=>s.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const{options:T,selectedKey:V}=as({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspaceId:g.workspaceChoice!=="__custom__"?g.workspaceChoice:null,currentWorkspacePath:g.resolvedWorkspacePath});g.openLaunchConfirm({title:`Launch ${C.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:T,selectedWorkspaceKey:V,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:C.name}]},async()=>{const E=T.find(_=>_.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(E),w(C.type,{workspacePath:(E==null?void 0:E.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:C.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:g.resolvedWorkspacePath||"Use selected workspace"})]},C.type)):(g.activeLauncherKind==="cli"?n:a).map(C=>s.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const T=g.activeLauncherKind==="cli"?"cli":"acp",{options:V,selectedKey:E}=as({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspaceId:g.workspaceChoice!=="__custom__"?g.workspaceChoice:null,currentWorkspacePath:g.resolvedWorkspacePath});g.openLaunchConfirm({title:`Launch ${C.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${T.toUpperCase()}`,workspaceOptions:V,selectedWorkspaceKey:E,details:[{label:"Mode",value:T.toUpperCase()},{label:"Provider",value:C.displayName}],showArgsInput:!0,showModelInput:T==="acp",initialArgs:"",initialModel:"",providerType:C.type},async()=>{const _=V.find(F=>F.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(_),I(T,C.type,{workspaceId:(_==null?void 0:_.workspaceId)??null,workspacePath:(_==null?void 0:_.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:[C.icon?`${C.icon} `:"",C.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:g.resolvedWorkspacePath||"Use selected workspace"})]},C.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:x,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(on,{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:C=>{g.loadBrowsePath(C)},onConfirm:C=>{g.chooseCustomWorkspacePath(C),g.setBrowseDialogOpen(!1)}}),g.launchConfirm&&s.jsx(Ya,{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?zr(!!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:Ea()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:g.launchConfirmTextFilter,onChange:C=>g.setLaunchConfirmTextFilter(C.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:g.launchConfirmWorkspaceFilter,onChange:C=>g.setLaunchConfirmWorkspaceFilter(C.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:g.launchConfirmModelFilter,onChange:C=>g.setLaunchConfirmModelFilter(C.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),s.jsxs("select",{value:g.launchConfirmSortMode,onChange:C=>g.setLaunchConfirmSortMode(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled: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:C=>g.setLaunchConfirmResumableOnly(C.target.checked),disabled:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:g.launchConfirmResumeId,onChange:C=>g.setLaunchConfirmResumeId(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:g.launchConfirmBusy||g.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Mf()}),g.filteredLaunchConfirmSavedSessions.map(C=>s.jsxs("option",{value:C.providerSessionId,disabled:!C.canResume,children:[C.title||C.providerSessionId," ",C.canResume?"":"(workspace missing)"]},C.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 C=g.filteredLaunchConfirmSavedSessions.find(V=>V.providerSessionId===g.launchConfirmResumeId);if(!C)return null;const T=ol(C);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:T.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:T.providerSessionId}),s.jsx("div",{className:"mt-1",children:T.metaLine}),T.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:T.updatedLabel}),T.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:T.preview})]})})()]}),onConfirm:g.handleConfirmLaunch,onCancel:g.closeLaunchConfirm}),d&&s.jsx(al,{section:f,onSectionChange:m})]})}function Oh(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 Wh(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:ls(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,u,f,d;const a=er(n)?"cli":ys(n)?"acp":"ide",i=ls(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(er(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:((d=(f=(u=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:u.at)==null?void 0:f.call(u,-1))==null?void 0:d.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function Fh(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((h,m)=>m.timestamp-h.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=Qn(n),u=a.filter(h=>h.unread||h.requiresAction).length,f=Oh(n),d=[n.platform||"machine",f].filter(Boolean);return{id:n.id,label:Mt(n,{fallbackId:n.id}),subtitle:d.join(" · "),unread:u,total:a.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?hf(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 Hh(e){return e==="chat"}function Sr(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 Uh({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:f,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:m,onRequestedMobileSectionConsumed:v,setSelectedTabKey:k,setScreen:p,setSelectedMachineId:x,setSection:w,setMachineBackTarget:b,resetMachineAction:N}){const I=o.useRef(null),y=o.useCallback(M=>{if(!(M!=null&&M.sessionId))return;const S=Wr(M,c),j=Math.max(Date.now(),Zt(M),S.lastUpdated||0);Sr("mark_read:start",{tabKey:M.tabKey,sessionId:M.sessionId,displayPrimary:at(M),inboxBucket:S.inboxBucket,unread:S.unread,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,activityAt:Zt(M),readAt:j}),l(fs(M)||M.routeId,"mark_session_seen",{sessionId:M.sessionId,providerSessionId:M.providerSessionId,seenAt:j,completionMarker:S.completionMarker}).then(g=>{Sr("mark_read:result",{tabKey:M.tabKey,sessionId:M.sessionId,result:g})}).catch(g=>{Sr("mark_read:error",{tabKey:M.tabKey,sessionId:M.sessionId,error:g instanceof Error?g.message:String(g)})})},[c,l]);return o.useEffect(()=>{var S;if(!n){Hh(i)&&p("inbox"),k(((S=e[0])==null?void 0:S.tabKey)||null),I.current=null;return}if(i!=="chat"){I.current=null;return}const M=`${n.tabKey}:${n.sessionId||""}`;I.current!==M&&(I.current=M,y(n))},[e,y,i,n,p,k]),o.useEffect(()=>{if(!u)return;const M=e.find(S=>S.tabKey===u);M&&(k(M.tabKey),p("chat"),f==null||f())},[e,f,u,p,k]),o.useEffect(()=>{if(!d)return;const M=t.find(S=>S.id===d);M&&(x(M.id),N(),w("machines"),b("inbox"),p("machine"),h==null||h())},[t,h,d,N,b,p,w,x]),o.useEffect(()=>{m&&(w(m),p("inbox"),v==null||v())},[v,m,p,w]),o.useEffect(()=>{const M=r.filter(S=>S.inboxBucket==="task_complete"||S.unread);M.length!==0&&Sr("inbox_state",{screen:i,selectedTabKey:a,items:M.map(S=>{const j=Wr(S.conversation,c);return{liveState:j,tabKey:S.conversation.tabKey,sessionId:S.conversation.sessionId,displayPrimary:at(S.conversation),serverBucket:j.inboxBucket,computedBucket:S.inboxBucket,serverUnread:j.unread,computedUnread:S.unread,lastSeenAt:j.lastSeenAt,lastUpdated:j.lastUpdated,activityAt:Zt(S.conversation)}})})},[r,c,i,a]),{markConversationRead:y}}function zh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function ni(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Vh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Gh({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[u,f]=o.useState(null),d=o.useCallback(()=>{i("idle"),l(""),f(null)},[]),h=o.useCallback(async(b,N,I)=>{var y;try{i("loading"),l(`Launching ${N}…`);const M={ideType:N,enableCdp:!0};(y=I==null?void 0:I.workspacePath)!=null&&y.trim()&&(M.workspace=I.workspacePath.trim()),await e(b,"launch_ide",M),i("done"),l(`${N} launch requested`)}catch(M){i("error"),l(M instanceof Error?M.message:"Launch IDE failed"),console.error("Launch IDE failed",M)}},[e]),m=o.useCallback(async(b,N,I)=>{if(N.trim())try{i("loading"),l(I!=null&&I.createIfMissing?"Creating folder…":"Saving workspace…");const y=await e(b,"workspace_add",{path:N.trim(),createIfMissing:(I==null?void 0:I.createIfMissing)===!0});if(y!=null&&y.success){i("done"),l(I!=null&&I.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,I,y,M,S,j;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${((I=g==null?void 0:g.result)==null?void 0:I.version)||"latest"}.`);return}if((y=g==null?void 0:g.result)!=null&&y.upgraded||(M=g==null?void 0:g.result)!=null&&M.success){i("done"),l(`Upgrade to v${((S=g==null?void 0:g.result)==null?void 0:S.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((j=g==null?void 0:g.result)==null?void 0:j.error)||"Upgrade failed")}catch(g){i("error"),l(g instanceof Error?g.message:"Upgrade failed")}},[e]),k=o.useCallback(async(b,N,I,y)=>{var j,g,$;const M=Date.now(),S={machineId:b,kind:N,providerType:I,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:M};try{i("loading"),l(`Launching ${I}…`),f(S);const A={cliType:I};(j=y==null?void 0:y.workspacePath)!=null&&j.trim()?A.dir=y.workspacePath.trim():y!=null&&y.workspaceId&&(A.workspaceId=y.workspaceId),y!=null&&y.resumeSessionId&&(A.resumeSessionId=y.resumeSessionId),(g=y==null?void 0:y.args)!=null&&g.trim()&&(A.cliArgs=y.args.trim().split(/\s+/).filter(Boolean)),($=y==null?void 0:y.model)!=null&&$.trim()&&(A.initialModel=y.model.trim());const L=await e(b,"launch_cli",A),O=(L==null?void 0:L.result)||L,W=(O==null?void 0:O.sessionId)||(O==null?void 0:O.id);if(L!=null&&L.success&&W){f(null),i("done"),l(`${I} launched`),t(Vt(W));return}if(L!=null&&L.success){i("loading"),l(`${I} launch requested — waiting for session…`);return}f(null),i("error"),l((L==null?void 0:L.error)||(O==null?void 0:O.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(A){if(Vh(A)){i("loading"),l(`${I} launch requested — waiting for session…`);return}f(null),i("error"),l(A instanceof Error?A.message:`Could not launch ${N.toUpperCase()} workspace`)}},[t,e]),p=o.useCallback(async(b,N)=>{try{const I=await e(b,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),y=(I==null?void 0:I.result)??I;return Array.isArray(y==null?void 0:y.sessions)?y.sessions:[]}catch(I){return console.error("Failed to list saved sessions on mobile:",I),[]}},[e]),x=o.useCallback(async(b,N)=>nn(e,b,N),[e]);o.useEffect(()=>{if(!u)return;const b=ni(u.workspacePath),N=r.find(y=>{var A,L,O,W;if(!y||y.type==="adhdev-daemon"||zh(y.daemonId||y.id)!==u.machineId||(y.transport==="acp"?"acp":y.transport==="pty"?"cli":null)!==u.kind||String(y.agentType||y.type||"")!==u.providerType)return!1;const g=String(y.providerSessionId||"");if(u.resumeSessionId&&g)return g===u.resumeSessionId;if(b){const P=ni(y.workspace||y.runtimeWorkspaceLabel);return P?P===b:!1}return Number(y.lastUpdated||y._lastUpdate||y.timestamp||((W=(O=(L=(A=y.activeChat)==null?void 0:A.messages)==null?void 0:L.at)==null?void 0:O.call(L,-1))==null?void 0:W.timestamp)||0)>=u.startedAt-5e3});if(!N)return;const I=pc({entrySessionId:N.sessionId,entryInstanceId:N.instanceId,entryRouteId:N.id,conversations:n});I&&(f(null),i("done"),l(`${u.providerType} launched`),t(Vt(I)))},[n,r,t,u]),o.useEffect(()=>{if(!u)return;const b=window.setTimeout(()=>{f(N=>!N||N.startedAt!==u.startedAt?N:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(b)},[u]);const w=o.useCallback(async(b,N)=>{if(N.kind==="ide"&&N.providerType){await h(b,N.providerType,{workspacePath:N.workspace||null});return}(N.kind==="cli"||N.kind==="acp")&&N.providerType&&await k(b,N.kind,N.providerType,{workspacePath:N.workspace||null,resumeSessionId:N.providerSessionId||null})},[h,k]);return{machineAction:{state:a,message:c},resetMachineAction:d,handleLaunchDetectedIde:h,handleAddWorkspace:m,handleMachineUpgrade:v,handleLaunchWorkspaceProvider:k,handleListSavedSessions:p,handleBrowseDirectory:x,handleOpenRecent:w}}function qh({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:f}){const d=o.useCallback(w=>{i(w.tabKey),c("chat"),n(w)},[n,c,i]),h=o.useCallback(w=>{const b=e.find(N=>N.routeId===w.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((w,b="inbox")=>{l(w),a(),u("machines"),f(b),c("machine")},[a,f,c,u,l]),k=o.useCallback(w=>{const b=fs(w);b&&v(b,"chat")},[v]),p=o.useCallback(()=>{a(),c(r)},[r,a,c]),x=o.useCallback(w=>{u(w),c("inbox")},[c,u]);return{openConversation:d,openNativeConversation:h,backFromConversation:m,openMachine:v,openConversationMachine:k,backFromMachine:p,changeMachineSection:x}}function ms(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function Yh(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function Nr(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Xh({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,userName:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:f,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:m,onRequestedMobileSectionConsumed:v,onOpenHistory:k,onOpenRemote:p,onStopCli:x,wsStatus:w,isConnected:b,onShowHiddenConversation:N,onShowAllHiddenConversations:I,onHideConversation:y,onOpenNewSession:M,liveSessionInboxState:S,setCliViewModeOverrides:j}){const[g,$]=o.useState(()=>{var Y;return((Y=e[0])==null?void 0:Y.tabKey)||null}),[A,L]=o.useState(()=>e[0]?"chat":"inbox"),[O,W]=o.useState("chats"),[P,C]=o.useState(null),[T,V]=o.useState("inbox"),E=Ts(),_="0.9.33",F=o.useMemo(()=>e.find(Y=>Y.tabKey===g)||e[0]||null,[e,g]),J=o.useMemo(()=>F?r.find(Y=>Y.id===F.routeId):void 0,[r,F]),xe=o.useMemo(()=>!F||Je(F)||!et(F)?null:Rs(F),[F]),ce=o.useMemo(()=>r.filter(Y=>Y.type==="adhdev-daemon").sort(ka),[r]),te=o.useMemo(()=>ce.find(Y=>Y.id===P)||null,[ce,P]),be=an({sendDaemonCommand:a,activeConv:F||void 0,setActionLogs:i,isStandalone:c}),ge=Gh({sendDaemonCommand:a,navigate:E,ides:r,conversations:e}),ve=o.useMemo(()=>e.map(Y=>{const G=A==="chat"&&(F==null?void 0:F.tabKey)===Y.tabKey,X=Zr(Y,S,{hideOpenTaskCompleteUnread:!0,isOpenConversation:G}),re=Zt(Y),Se=jc(Y);return{conversation:Y,timestamp:re,preview:Se,unread:X.unread,requiresAction:X.requiresAction,isWorking:X.isWorking,inboxBucket:X.inboxBucket}}),[e,S,A,F]),{markConversationRead:H}=Uh({conversations:e,machineEntries:ce,items:ve,selectedConversation:F,selectedTabKey:g,screen:A,liveSessionInboxState:S,sendDaemonCommand:a,requestedActiveTabKey:u,onRequestedActiveTabConsumed:f,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:m,onRequestedMobileSectionConsumed:v,setSelectedTabKey:$,setScreen:L,setSelectedMachineId:C,setSection:W,setMachineBackTarget:V,resetMachineAction:ge.resetMachineAction}),U=qh({conversations:e,selectedConversation:F,machineBackTarget:T,markConversationRead:H,resetMachineAction:ge.resetMachineAction,setSelectedTabKey:$,setScreen:L,setSelectedMachineId:C,setSection:W,setMachineBackTarget:V}),Q=o.useMemo(()=>Nr(ve.filter(Y=>Y.requiresAction)),[ve]),de=o.useMemo(()=>Nr(ve.filter(Y=>Y.unread&&!Y.requiresAction)),[ve]),ne=o.useMemo(()=>Nr(ve.filter(Y=>!Y.unread&&!Y.requiresAction&&Y.isWorking)),[ve]),fe=o.useMemo(()=>Nr(ve.filter(Y=>!Y.unread&&!Y.requiresAction&&!Y.isWorking)),[ve]),ae=o.useMemo(()=>te?ve.filter(Y=>fs(Y.conversation)===te.id):[],[ve,te]),pe=o.useMemo(()=>Wh(te,r),[r,te]),le=(te==null?void 0:te.version)||null,ue=!!te&&!!le&&!0&&le!==_,oe=o.useMemo(()=>(te==null?void 0:te.availableProviders)||[],[te]),ye=o.useMemo(()=>oe.filter(Y=>ms(Y,"cli")).map(Y=>({type:Y.type,displayName:Y.displayName||Y.type,icon:Y.icon})),[oe]),he=o.useMemo(()=>oe.filter(Y=>ms(Y,"acp")).map(Y=>({type:Y.type,displayName:Y.displayName||Y.type,icon:Y.icon})),[oe]),ke=o.useMemo(()=>Fh(ce,ve),[ve,ce]),D=o.useCallback(async Y=>{te&&await ge.handleOpenRecent(te.id,Y)},[ge,te]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:A==="chat"&&F?s.jsx(Lh,{selectedConversation:F,isAcp:Je(F),isStandalone:c,selectedIdeEntry:J,actionLogs:n,userName:l,isSendingChat:be.isSendingChat,sendFeedbackMessage:be.sendFeedbackMessage,isFocusingAgent:be.isFocusingAgent,handleModalButton:be.handleModalButton,handleRelaunch:be.handleRelaunch,onBack:U.backFromConversation,onOpenNativeConversation:U.openNativeConversation,onOpenMachine:U.openConversationMachine,onHideConversation:y,onOpenHistory:k,onOpenRemote:p,onStopCli:x,cliViewMode:xe,onSetCliViewMode:async Y=>{await Xc({conversation:F,mode:Y,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:j})},handleSendChat:be.handleSendChat,handleFocusAgent:be.handleFocusAgent}):A==="machine"&&te?s.jsx(Kh,{selectedMachineEntry:te,selectedMachineConversations:ae,selectedMachineRecentLaunches:pe,cliProviders:ye,acpProviders:he,selectedMachineNeedsUpgrade:ue,appVersion:_,machineAction:ge.machineAction,isStandalone:c,section:O,showBottomNav:T==="inbox",onBack:U.backFromMachine,onSectionChange:U.changeMachineSection,onOpenConversation:U.openConversation,onOpenRecent:D,onOpenMachineDetails:()=>E(`/machines/${te.id}`),onMachineUpgrade:()=>ge.handleMachineUpgrade(te.id),onLaunchDetectedIde:(Y,G)=>ge.handleLaunchDetectedIde(te.id,Y,G),onAddWorkspace:(Y,G)=>ge.handleAddWorkspace(te.id,Y,G),onBrowseDirectory:Y=>ge.handleBrowseDirectory(te.id,Y),onLaunchWorkspaceProvider:(Y,G,X)=>ge.handleLaunchWorkspaceProvider(te.id,Y,G,X),onListSavedSessions:Y=>ge.handleListSavedSessions(te.id,Y)}):s.jsx(_h,{section:O,attentionItems:Q,unreadItems:de,workingItems:ne,completedItems:fe,hiddenConversations:t,machineCards:ke,getAvatarText:Yh,onOpenConversation:U.openConversation,onShowConversation:N,onShowAllHidden:I,onOpenNewSession:M,onOpenMachine:U.openMachine,onOpenSettings:()=>E("/settings"),onSectionChange:W,wsStatus:w,isConnected:b,isStandalone:c})})}function Ln(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function Jh({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,u]=o.useState(!1),[f,d]=o.useState(null),h=o.useCallback(()=>{c.current=0,u(!1),d(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const m=o.useCallback(x=>{x.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),v=o.useCallback(x=>{if(!x.dataTransfer.types.includes("text/tab-key"))return;if(x.preventDefault(),!Ln(t,r)){d("merge");return}const w=x.currentTarget.getBoundingClientRect(),b=x.clientX-w.left,N=w.width/3;b<N?d("split-left"):b>N*2?d("split-right"):d("merge")},[t,r]),k=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,u(!1),d(null))},[]),p=o.useCallback(x=>{c.current=0,u(!1);const w=x.dataTransfer.getData("text/tab-key"),b=w?e.some(I=>I.tabKey===w):!1,N=f;if(d(null),i(),!!w){if(x.preventDefault(),N==="split-left"&&Ln(t,r)){r==null||r(w,"split-left");return}if(N==="split-right"&&Ln(t,r)){r==null||r(w,"split-right");return}if(b){a(w);return}n==null||n(w)}},[e,f,t,r,n,a,i]);return{dragOver:l,dropAction:f,resetDragState:h,handleDragEnter:m,handleDragOver:v,handleDragLeave:k,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 Zh({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(t??null),[l,u]=o.useState(r??[]),[f,d]=o.useState(null),h=o.useRef(null),m=o.useRef(null),v=o.useRef(n),k=o.useRef(a);o.useEffect(()=>{v.current=n},[n]),o.useEffect(()=>{k.current=a},[a]),o.useEffect(()=>{t&&t!==i&&c(t)},[t,i]),o.useEffect(()=>{u(S=>{const j=Qh(S,e);return j.length===S.length&&j.every((g,$)=>g===S[$])?S:j})},[e]);const p=o.useMemo(()=>{const S=f??l;if(S.length===0)return e;const j=new Map(S.map((g,$)=>[g,$]));return[...e].sort((g,$)=>{const A=j.get(g.tabKey)??999,L=j.get($.tabKey)??999;return A-L})},[e,f,l]);o.useEffect(()=>{var j,g;if(p.length===0){i!==null&&(c(null),(j=v.current)==null||j.call(v,null));return}if(i&&p.some($=>$.tabKey===i))return;const S=p[0].tabKey;S!==i&&(c(S),(g=v.current)==null||g.call(v,S))},[p,i]);const x=o.useMemo(()=>p.find(S=>S.tabKey===i),[p,i]),w=o.useCallback(S=>{var j;c(S),(j=v.current)==null||j.call(v,S)},[]),b=o.useCallback((S,j,g)=>{u($=>{var W;const A=$.filter(P=>P!==S),L=A.indexOf(j);if(L<0)return $;const O=g==="left"?L:L+1;return A.splice(O,0,S),(W=k.current)==null||W.call(k,A),A}),d(null)},[]),N=o.useCallback((S,j,g)=>{const A=(l.length>0?l:e.map(W=>W.tabKey)).filter(W=>W!==S),L=A.indexOf(j);if(L<0)return;const O=g==="left"?L:L+1;A.splice(O,0,S),h.current=A,d(A)},[l,e]),I=o.useCallback(()=>{var j;const S=h.current;S&&(u(S),(j=k.current)==null||j.call(k,S))},[]),y=o.useCallback(()=>{h.current=null,d(null)},[]),M=o.useCallback(S=>{u(j=>{var $;const g=j.filter(A=>A!==S);return g.push(S),($=k.current)==null||$.call(k,g),g})},[]);return{activeTabId:i,activeConv:x,sortedConversations:p,previewOrderRef:h,draggingTabRef:m,selectTab:w,handleTabReorder:b,updatePreviewOrder:N,commitPreviewOrder:I,clearPreviewOrder:y,moveTabToEnd:M,setDraggingTabKey:S=>{m.current=S}}}function ex({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 Xa({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,u=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",f=n?Cc: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:u}),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:Et,"aria-label":Et,children:[s.jsx(Fi,{size:14}),s.jsx("span",{children:Et})]})}),c&&s.jsx(nl,{}),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 cl="adhdev-tab-shortcuts";function ll(){try{return JSON.parse(localStorage.getItem(cl)||"{}")}catch{return{}}}function dl({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>ll()),[l,u]=o.useState(null),f=o.useCallback(h=>{const m=[];return h.metaKey&&m.push(a?"⌘":"Meta"),h.ctrlKey&&m.push("Ctrl"),h.altKey&&m.push(a?"⌥":"Alt"),h.shiftKey&&m.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(m.push(h.key.length===1?h.key.toUpperCase():h.key),m.join("+"))},[a]),d=o.useCallback(h=>{c(h);try{localStorage.setItem(cl,JSON.stringify(h))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const h=m=>{if(m.preventDefault(),m.stopPropagation(),m.key==="Escape"){u(null);return}const v=f(m);if(!v)return;const k={...i};for(const[p,x]of Object.entries(k))x===v&&delete k[p];k[l]=v,d(k),u(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,l,i,d,f]),o.useEffect(()=>{if(!e)return;const h=m=>{if(!(!m.ctrlKey&&!m.metaKey&&!m.altKey)){for(const[v,k]of Object.entries(i))if(t.includes(v)&&f(m)===k){m.preventDefault(),r(),n(v);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,i,t,r,n,f]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:u,saveShortcuts:d}}const tx=o.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:u,onSelectTab:f,onConversationActivated:d,onPreviewReorder:h,onReorderTab:m,onCommitPreviewOrder:v,onClearPreviewOrder:k,onDragStateReset:p,onDragTabKeyChange:x,onReceiveTab:w,onOpenContextMenu:b,longPressTimer:N,isGroupActive:I}){const y=Ls(t),M=y.isGenerating?"agent-tab-generating":y.isWaiting?"agent-tab-waiting":"",S=y.isReconnecting,j=o.useCallback(T=>{l.current=t.tabKey,x(t.tabKey),T.dataTransfer.setData("text/tab-key",t.tabKey),T.dataTransfer.effectAllowed="move"},[t.tabKey,l,x]),g=o.useCallback(()=>{l.current=null,x(null),v(),k(),p()},[l,x,v,k,p]),$=o.useCallback(T=>{const V=l.current;if(!(!V||V===t.tabKey)&&T.dataTransfer.types.includes("text/tab-key")){T.preventDefault(),T.stopPropagation();const E=T.currentTarget.getBoundingClientRect(),_=T.clientX<E.left+E.width/2?"left":"right";h(V,t.tabKey,_)}},[t.tabKey,l,h]),A=o.useCallback(T=>{T.preventDefault(),T.stopPropagation();const V=T.dataTransfer.getData("text/tab-key");if(V&&V!==t.tabKey){const E=T.currentTarget.getBoundingClientRect(),_=T.clientX<E.left+E.width/2?"left":"right";c.includes(V)?m(V,t.tabKey,_):w&&w(V)}k()},[t.tabKey,c,m,w,k]),L=o.useCallback(T=>{T.stopPropagation(),u(),f(t.tabKey),d(t)},[t,d,u,f]),O=o.useCallback(T=>{T.preventDefault(),b(T.clientX,T.clientY,t.tabKey)},[t.tabKey,b]),W=o.useCallback(T=>{const V=T.touches[0];N.current=setTimeout(()=>{b(V.clientX,V.clientY,t.tabKey)},600)},[t.tabKey,N,b]),P=o.useCallback(()=>{N.current&&clearTimeout(N.current)},[N]),C=["adhdev-dockview-tab",M,r&&"is-active",I&&"is-group-active",S&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:C,draggable:!0,onDragStart:j,onDragEnd:g,onDragOver:$,onDrop:A,onClick:L,onContextMenu:O,onTouchStart:W,onTouchEnd:P,onTouchMove:P,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:"▲"}):S?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:at(t),children:at(t)}),s.jsx("span",{className:"adhdev-dockview-tab-meta",children:S?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:es(t)}):y.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[es(t),s.jsx("span",{className:"connecting-dots"})]}):es(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 sx({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:f,onCommitPreviewOrder:d,onClearPreviewOrder:h,onDragStateReset:m,onDragTabKeyChange:v,onReceiveTab:k,onHideTab:p,isGroupActive:x,allowTabShortcuts:w=!0}){const[b,N]=o.useState(null),I=o.useRef(null),y=o.useRef(null),M=o.useMemo(()=>e.map(O=>O.tabKey),[e]);nr("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(b==null?void 0:b.tabKey)||null});const{isMac:S,tabShortcuts:j,shortcutListening:g,setShortcutListening:$,saveShortcuts:A}=dl({enabled:w,sortedTabKeys:e.map(O=>O.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!b)return;const O=W=>{const P=document.querySelector("[data-pane-context-menu]");P&&P.contains(W.target)||N(null)};return window.addEventListener("mousedown",O,!0),()=>window.removeEventListener("mousedown",O,!0)},[b]),o.useEffect(()=>{const O=y.current;if(!O)return;const W=P=>{Math.abs(P.deltaY)<=Math.abs(P.deltaX)||(P.preventDefault(),O.scrollLeft+=P.deltaY)};return O.addEventListener("wheel",W,{passive:!1}),()=>O.removeEventListener("wheel",W)},[]);const L=o.useCallback((O,W,P)=>{N({x:O,y:W,tabKey:P})},[]);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(O=>s.jsx(tx,{conv:O,isActive:t===O.tabKey,isDraggedTab:a.current===O.tabKey,isTaskCompleteUnread:n.has(O.tabKey),shortcut:w?j[O.tabKey]:void 0,conversationKeys:M,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:f,onCommitPreviewOrder:d,onClearPreviewOrder:h,onDragStateReset:m,onDragTabKeyChange:v,onReceiveTab:k,onOpenContextMenu:L,longPressTimer:I,isGroupActive:x},O.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:[w&&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:O=>{O.stopPropagation(),$(b.tabKey),N(null)},children:["⌨ ",j[b.tabKey]?`Change shortcut (${j[b.tabKey]})`:"Set shortcut"]}),j[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 O={...j};delete O[b.tabKey],A(O),N(null)},children:"✕ Remove shortcut"})]}),p&&s.jsxs(s.Fragment,{children:[w&&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"})]})]}),w&&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:()=>$(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:O=>O.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. ",S?"⌘+1":"Ctrl+1",", ",S?"⌥+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 rx({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,userName:u,groupIndex:f,onFocus:d,isSplitMode:h,numGroups:m,onMoveTab:v,onReceiveTab:k,style:p,onActiveTabChange:x,initialActiveTabId:w,initialTabOrder:b,onTabOrderChange:N,onHideTab:I,isFocused:y,allowTabShortcuts:M=!0,onOpenNewSession:S,liveSessionInboxState:j}){const{sendCommand:g}=vt(),$=o.useRef(null),{activeTabId:A,activeConv:L,sortedConversations:O,draggingTabRef:W,selectTab:P,handleTabReorder:C,updatePreviewOrder:T,commitPreviewOrder:V,clearPreviewOrder:E,moveTabToEnd:_,setDraggingTabKey:F}=Zh({conversations:e,initialActiveTabId:w,initialTabOrder:b,onActiveTabChange:x,onTabOrderChange:N}),J=an({sendDaemonCommand:a,activeConv:L,setActionLogs:i,isStandalone:c}),{dragOver:xe,dropAction:ce,resetDragState:te,handleDragEnter:be,handleDragOver:ge,handleDragLeave:ve,handleDrop:H}=Jh({conversations:e,numGroups:m,onMoveTab:v,onReceiveTab:k,onOwnTabDrop:_,onClearPreviewOrder:E}),U=L&&!Je(L)&&Rs(L)==="terminal",Q=o.useMemo(()=>L?t.find(ae=>ae.id===L.routeId):void 0,[t,L]),de=o.useMemo(()=>L?n.filter(ae=>ae.routeId===L.tabKey):[],[n,L]),ne=o.useMemo(()=>new Set(O.filter(ae=>Cu(ae,j,{isOpenConversation:ae.tabKey===A})).map(ae=>ae.tabKey)),[A,j,O]);nr("PaneGroup",{groupIndex:f,conversationCount:e.length,activeTabId:A,dragOver:xe});const fe=o.useCallback(ae=>{ae.streamSource==="agent-stream"&&ae.agentType&&g(ae.routeId,rl(),{agentType:ae.agentType,...ae.sessionId&&{targetSessionId:ae.sessionId}}).catch(()=>{})},[g]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:d,style:{...p,outline:xe?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(sx,{conversations:O,activeTabId:A,groupIndex:f,numGroups:m,unreadTabKeys:ne,draggingTabRef:W,onFocus:d,onSelectTab:P,onConversationActivated:fe,onPreviewReorder:T,onReorderTab:C,onCommitPreviewOrder:V,onClearPreviewOrder:E,onDragStateReset:te,onDragTabKeyChange:F,onMoveTab:v,onReceiveTab:k,onHideTab:I,isGroupActive:y??!1,allowTabShortcuts:M}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:be,onDragOver:ge,onDragLeave:ve,onDrop:H,children:[xe&&s.jsx(ex,{dropAction:ce,canSplit:!!(m<4&&v)}),L?s.jsx(qa,{activeConv:L,clearToken:r[L.tabKey]||0,isCliTerminal:!!U,ideEntry:Q,terminalRef:$,handleModalButton:J.handleModalButton,handleRelaunch:J.handleRelaunch,handleSendChat:J.handleSendChat,isSendingChat:J.isSendingChat,sendFeedbackMessage:J.sendFeedbackMessage,handleFocusAgent:J.handleFocusAgent,isFocusingAgent:J.isFocusingAgent,actionLogs:de,userName:u,isInputActive:!h||!!y}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(Xa,{conversationsCount:e.length,isSplitMode:h,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:S})})]})]})}function nx({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setActionLogs:f,isStandalone:d,hasRegisteredMachines:h,userName:m,focusedGroup:v,focusGroup:k,moveTabToGroup:p,splitTabRelative:x,closeGroup:w,handleResizeStart:b,groupActiveTabIds:N,setGroupActiveTab:I,groupTabOrders:y,setGroupTabOrder:M,toggleHiddenTab:S,onOpenNewSession:j,allowTabShortcuts:g=!0,liveSessionInboxState:$}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((A,L)=>{const O=t&&n.length===r?`${n[L]}%`:void 0;return s.jsxs(jt.Fragment,{children:[t&&L>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:W=>b(L-1,W),onDoubleClick:()=>w(L),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(rx,{style:t?{flexBasis:O??`${100/r}%`,flexGrow:O?0:1,flexShrink:O?0:1}:void 0,conversations:A,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setActionLogs:f,isStandalone:d,hasRegisteredMachines:h,userName:m,groupIndex:L,isFocused:t&&v===L,onFocus:()=>k(L),isSplitMode:t,numGroups:r,onMoveTab:(W,P)=>{P==="left"&&L>0?p(W,L-1):P==="right"&&L<r-1?p(W,L+1):P==="split-left"&&r<4?x(W,L,"left"):P==="split-right"&&r<4&&x(W,L,"right")},onReceiveTab:W=>p(W,L),onActiveTabChange:W=>I(L,W),initialActiveTabId:N[L],initialTabOrder:y[L],onTabOrderChange:W=>M(L,W),onHideTab:S,onOpenNewSession:j,allowTabShortcuts:g,liveSessionInboxState:$})]},L)})})}function ul({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?dt.onScreenshot("ide-page",(d,h)=>{if(d!==e)return;const m=new FileReader;m.onload=()=>i(m.result),m.readAsDataURL(h)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var d;return e?((d=dt.onStatus)==null?void 0:d.call(dt,(h,m)=>{h===e&&m!=null&&m.screenshotUsage&&l(m.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,t]),o.useEffect(()=>{const f=e?dt.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 u=o.useCallback(async(f,d)=>{const h=e?dt.get(e):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(f,d,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:u}}const ml="adhdev-dashboard-action-shortcuts",ax=1200,ox={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function ix(){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 fl(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 da(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function qr(e){const t=Object.fromEntries(fl(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(ml)||"{}"),n={...t,...r};for(const[a,i]of Object.entries(ox))n[a]===i&&(n[a]=t[a]);return n}catch{return t}}function pl(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function cx({enabled:e=!0,onTrigger:t}){const r=ix(),[n,a]=o.useState(()=>qr(r)),[i,c]=o.useState(null),[l,u]=o.useState([]),f=o.useRef({parts:[],timer:null}),d=o.useCallback(p=>{const x=[];return p.metaKey&&x.push(r?"⌘":"Meta"),p.ctrlKey&&x.push("Ctrl"),p.altKey&&x.push(r?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&x.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(x.push(pl(p.key)),x.join("+"))},[r]),h=o.useCallback(p=>{a(p);try{localStorage.setItem(ml,JSON.stringify(p))}catch{}},[]);o.useEffect(()=>{const p=qr(r),x=Object.entries(n),w=Object.entries(p);x.length===w.length&&x.every(([b,N])=>p[b]===N)||h(p)},[n,r,h]);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}},ax))},[]);o.useEffect(()=>{if(!i)return;const p=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){c(null),u([]);return}const w=d(x);if(!w)return;const N=!(x.metaKey||x.ctrlKey||x.altKey)&&/^[A-Z0-9]$/.test(w);if(l.length===0&&N){u([w]);return}const y=[...l,w].slice(0,2).join(" "),M={...n};for(const[S,j]of Object.entries(M))j===y&&delete M[S];M[i]=y,h(M),c(null),u([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,d,h,i,l]),o.useEffect(()=>{if(!e||i)return;const p=x=>{if(x.defaultPrevented)return;const w=d(x);if(!w)return;const b=x.metaKey||x.ctrlKey||x.altKey;if(da(x.target)&&!b)return;const N=f.current.parts,I=b?[w]:[...N.slice(-1),w].slice(-2),y=I.join(" "),M=I[I.length-1],S=Object.entries(n).filter(([,L])=>!!L),j=S.find(([,L])=>L===y);if(j){x.preventDefault(),m(),t(j[0]);return}if(S.some(([,L])=>L.startsWith(`${y} `))){x.preventDefault(),f.current.parts=I,v();return}const $=S.find(([,L])=>L===M);if($){x.preventDefault(),m(),t($[0]);return}if(S.some(([,L])=>L.startsWith(`${M} `))){x.preventDefault(),f.current.parts=[M],v();return}m()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,v,e,d,t,m,i]),o.useEffect(()=>()=>m(),[m]);const k=o.useMemo(()=>fl(r),[r]);return{isMac:r,actionDefinitions:k,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:h}}function lx({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 hl(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function ai({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!hl(n):!0}function dx({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:hl(r)}const xl=o.createContext(null);function cn(){const e=o.useContext(xl);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Dr(e){return at(e)||e.tabKey}function ux(e){return`remote:${e}`}function Lt(e){return e.startsWith("remote:")}function oi(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Rn(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,u;try{t.focus(),(u=(l=e==null?void 0:e.body)==null?void 0:l.focus)==null||u.call(l)}catch{}})}catch{}}function Cr(e,t){e.classList.remove(zn.className,Vn.className),e.classList.add(t==="light"?zn.className:Vn.className)}function ii(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 mx(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 fx(e,t,r){var c;const n=[t];let a;for(const l of n){let u;for(const f of l){const d=e.addPanel({id:f.tabKey,component:"conversation",title:Dr(f),params:{kind:"conversation",tabKey:f.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});u||(u=d.id)}a=u??a}return r??((c=t[0])==null?void 0:c.tabKey)??null}function ci(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!==Dr(n)&&a.api.setTitle(Dr(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:Dr(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 li(e,t,r){var u,f;const n=r?ux(r):null;for(const d of[...e.panels])Lt(d.id)&&(!n||d.id!==n)&&e.removePanel(d);if(!r||!n)return;const a=Pt(t,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=Nc(a);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((f=e.panels.find(d=>!Lt(d.id)))==null?void 0:f.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function px({params:e,api:t}){var h;const r=cn(),n=o.useRef(null),[a,i]=o.useState(t.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=an({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 u=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(Xa,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const d=!Je(c)&&Rs(c)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(qa,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:d,ideEntry:u,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:f,userName:r.userName,scrollToBottomRequestNonce:((h=r.scrollToBottomRequest)==null?void 0:h.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:a})})}function hx({params:e}){var u;const t=cn(),r=o.useMemo(()=>Pt([...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)||((u=r==null?void 0:r.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:l}=ul({doId:a,targetSessionId:r?dc(r):(n==null?void 0:n.sessionId)||(n==null?void 0:n.instanceId),connState:(r==null?void 0:r.connectionState)||"new",viewMode:"remote"});return r?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(Gi,{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 xx(){const e=cn();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(Xa,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function bx(e){var v,k;mx(e);const t=cn(),r=o.useCallback(p=>{"button"in p&&p.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const p=Pt([...t.conversationsByTabKey.values()],e.params.routeId),x=((v=e.api.group.activePanel)==null?void 0:v.id)===e.api.id,w=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${x?" is-active":""}${w?" 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=((k=e.api.group.activePanel)==null?void 0:k.id)===e.api.id,i=e.api.isGroupActive,c=Zr(n,t.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,u=c.isConnecting,f=c.isGenerating,d=c.isWaiting,h=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:at(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:p=>{var x;p.preventDefault(),r(p),t.openTabContextMenu({x:p.clientX,y:p.clientY,tabKey:n.tabKey,sourceDocument:((x=p.target)==null?void 0:x.ownerDocument)??document})},children:[h&&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"}):d?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:"○"}):u?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:at(n)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:es(n)}):u?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:es(n)}):s.jsx("span",{children:es(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 gx({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:u,userName:f,toggleHiddenTab:d,actionShortcuts:h,registerActionHandlers:m,onActiveTabChange:v,onOpenNewSession:k,onRequestScrollToBottom:p,requestedActiveTabKey:x,requestedRemoteIdeId:w,onRequestedActiveTabConsumed:b,scrollToBottomRequest:N,liveSessionInboxState:I,layoutProfile:y}){var ft,At,gt;const{theme:M}=Wa(),{sendCommand:S}=vt(),j=o.useRef(null),g=o.useRef(null),$=o.useRef(!1),A=o.useRef(!1),L=o.useRef(!1),O=o.useRef(null),W=o.useRef([]),[P,C]=o.useState(null),[T,V]=o.useState(!1),[E,_]=o.useState(!1),[F,J]=o.useState(0),xe=o.useRef(null),ce=o.useRef(typeof window>"u"?{}:qp(y)),te=o.useMemo(()=>new Map(e.map(K=>[K.tabKey,K])),[e]),be=o.useMemo(()=>{const K=j.current;return K?K.groups.some(B=>{try{const z=B.model.location.type;return z!=="floating"&&z!=="popout"?!1:B.panels.some(q=>te.has(q.id))}catch{return!1}}):!1},[te,F,e]),ge=o.useCallback(()=>{var K;(K=j.current)==null||K.focus()},[]),ve=o.useCallback((K,B)=>{p==null||p(K,B)},[p]),H=o.useCallback(K=>{const B=document,z=K.document;for(const Ne of B.querySelectorAll('link[rel="stylesheet"]')){const se=z.createElement("link");se.rel="stylesheet",se.href=Ne.href,Ne.crossOrigin&&(se.crossOrigin=Ne.crossOrigin),z.head.appendChild(se)}for(const Ne of B.querySelectorAll("style")){const se=z.createElement("style");se.textContent=Ne.textContent,z.head.appendChild(se)}const q=[];for(const Ne of B.styleSheets)try{for(const se of Ne.cssRules)se instanceof CSSStyleRule&&(se.selectorText===":root"||se.selectorText==="html")&&q.push(se.cssText)}catch{}if(q.length>0){const Ne=z.createElement("style");Ne.textContent=q.join(`
43
43
  `),z.head.appendChild(Ne)}const ie=B.documentElement.getAttribute("data-theme");ie&&z.documentElement.setAttribute("data-theme",ie),z.documentElement.style.colorScheme=ie==="light"?"light":"dark",z.body.className=B.body.className;const je=B.documentElement.getAttribute("style");je&&z.documentElement.setAttribute("style",je);const Me=z.getElementById("dv-popout-window");Me instanceof HTMLElement&&(Me.classList.add("adhdev-dockview"),Cr(Me,M))},[M]),U=o.useCallback(()=>{var B;const K=j.current;if(K)for(const z of K.groups)try{const q=(B=z.element)==null?void 0:B.ownerDocument;if(!q||q===document)continue;const ie=q.getElementById("dv-popout-window");ie instanceof HTMLElement&&(ie.classList.add("adhdev-dockview"),Cr(ie,M));const je=document.documentElement.getAttribute("data-theme");je&&q.documentElement.setAttribute("data-theme",je),q.documentElement.style.colorScheme=je==="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{}},[M]),Q=o.useCallback(()=>{var B;const K=j.current;if(K)for(const z of K.groups)try{const q=(B=z.element)==null?void 0:B.ownerDocument;if(!q||q===document)continue;const ie=q.getElementById("dv-popout-window");if(!(ie instanceof HTMLElement))continue;ie.classList.add("adhdev-dockview"),Cr(ie,M),ie.classList.toggle("is-showing-dockview-overlay",E),ie.classList.toggle("is-dragging-dockview",T)}catch{}},[T,E,M]),de=o.useCallback(K=>{const B=j.current;if(!B)return;const z=B.getPanel(K);z&&B.addPopoutGroup(z,{popoutUrl:"/popout.html",onDidOpen:({window:q})=>{H(q),he();const ie=te.get(K);q.document.title=ie?`${at(ie)} — ADHDev`:"ADHDev — Popout"}})},[te,H]),ne=o.useCallback(K=>{const B=j.current,z=B==null?void 0:B.getPanel(K);if(!B||!z)return;const q=B.groups.filter(ie=>{var je;try{return((je=ie.element)==null?void 0:je.ownerDocument)===document}catch{return!0}});q.length>0?z.api.moveTo({group:q[0],position:"center"}):z.api.moveTo({position:"center"}),z.api.setActive()},[]),fe=o.useCallback(K=>{var q;const B=j.current;if(!B)return!1;const z=B.getPanel(K);if(!z)return!1;try{return((q=z.group.element)==null?void 0:q.ownerDocument)!==document}catch{return!1}},[]),ae=o.useCallback(K=>{fe(K)&&ne(K),d(K)},[fe,ne,d]),pe=o.useCallback(K=>{const B=j.current,z=B==null?void 0:B.getPanel(K);!B||!z||B.addFloatingGroup(z,{width:600,height:500})},[]),le=o.useCallback(K=>{var z;const B=(z=j.current)==null?void 0:z.getPanel(K);if(!B)return!1;try{return B.group.model.location.type==="floating"}catch{return!1}},[]),ue=o.useCallback(()=>{var B,z;const K=(z=(B=j.current)==null?void 0:B.activePanel)==null?void 0:z.id;return!K||Lt(K)?null:te.has(K)?K:null},[te]),oe=o.useCallback(K=>{const B=j.current,z=B==null?void 0:B.getPanel(K);if(!B||!z)return;const q=B.groups.filter(ie=>{try{return ie.model.location.type==="grid"}catch{return!0}});q.length>0?z.api.moveTo({group:q[0],position:"center"}):z.api.moveTo({position:"center"}),z.api.setActive()},[]),ye=o.useCallback(()=>{var je;const K=j.current;if(!K)return;const z=K.groups.filter(Me=>{var Ne;try{return((Ne=Me.element)==null?void 0:Ne.ownerDocument)===document&&Me.model.location.type==="grid"}catch{return!1}})[0]||null,q=[...K.panels];for(const Me of q){const Ne=(je=Me.group.element)==null?void 0:je.ownerDocument,se=Me.group.model.location.type;Ne===document&&se==="grid"||(z&&z.id!==Me.group.id?Me.api.moveTo({group:z,position:"center"}):Me.api.moveTo({position:"center"}))}const ie=K.activePanel;ie&&(ie.group.model.openPanel(ie),ie.api.setActive()),Rn(document)},[]),he=o.useCallback(()=>{var B,z;const K=j.current;if(K)for(const q of K.groups){const ie=(B=q.element)==null?void 0:B.ownerDocument;if(!ie||ie===document)continue;const je=ie.getElementById("dv-popout-window");if(!(je instanceof HTMLElement))continue;let Me=null,Ne=ie.title||"ADHDev",se="Popout workspace";const we=q.activePanel;if(we)if(Me=we.id,Lt(we.id)){const R=((z=we.params)==null?void 0:z.routeId)||we.id.slice(7),ee=Pt([...te.values()],R);Ne=Nc(ee),se=ee!=null&&ee.machineName?`Remote view · ${ee.machineName}`:"Remote view"}else{const R=te.get(we.id);Ne=R?at(R):we.title||we.id,se=R?es(R):"Dockview panel"}ie.title=`${Ne} — ADHDev`;const Oe=Array.from(ie.querySelectorAll("#adhdev-popout-header"));for(const R of Oe)R.remove();const Fe=ie.createElement("div");Fe.id="adhdev-popout-header",ie.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>
@@ -75,9 +75,9 @@ This will disconnect CDP and optionally kill the process.`))try{const _=await r(
75
75
 
76
76
  `)}function jb(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function kb(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Sb({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:i,quickFilter:c,searchQuery:l,daemonLoading:u,traceLoading:f,daemonFetchError:d,traceFetchError:h}){const m=eb(n,i),v=rb(e,l),k=ob(t,l),p=ib(m,l),x=cb(a,l),w=jb(v,c),b=c==="all"?k:[],N=kb(p,c),I=c==="issues"?[]:x,y=lb({daemonLogs:v,daemonRawLines:k,trace:p,webEvents:x}),M=bb({daemonLogs:w,daemonRawLines:b,trace:N,webEvents:I}),S=yb(M),j=mb({daemonLoading:u,traceLoading:f,daemonFetchError:d,traceFetchError:h,daemonLogKind:r,daemonLogsCount:v.length,daemonRawLineCount:k.length,traceCount:p.length,webEventCount:x.length});return{filteredDaemonLogs:v,filteredDaemonRawLines:k,filteredTraceEntries:p,filteredWebEvents:x,visibleDaemonLogs:w,visibleDaemonRawLines:b,visibleTraceEntries:N,visibleWebEvents:I,quickFilterCounts:y,diagnosticEvents:M,diagnosticsSummary:S,sourceStates:j}}function Nb(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Sl(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function ua(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 En(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 Qa(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function Cb({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${ua(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:Sl(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:Qa(e.source)}),e.category&&e.stage&&s.jsxs("span",{children:[e.category,".",e.stage]}),e.topic&&s.jsxs("span",{children:["topic=",e.topic]}),e.interactionId&&s.jsxs("span",{children:["ix=",e.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:e.message})]})}function Ib({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:i,onCopyDiagnostics:c,onCopyVisible:l,onToggleAutoRefresh:u,onRefresh:f,onClear:d}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(h=>s.jsx("button",{type:"button",onClick:()=>a(h.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===h.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:h.label},h.id))}),s.jsx("input",{value:r,onChange:h=>i(h.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:l,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:u,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:f,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:d,className:"machine-btn",children:"Clear"})]})]})}function Mb({logLevel:e,traceCategory:t,onLogLevelChange:r,onTraceCategoryChange:n}){return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary p-3",children:s.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wider text-text-muted font-semibold",children:"Advanced source scope"}),["debug","info","warn","error"].map(a=>s.jsxs("button",{onClick:()=>r(a),className:`machine-btn text-[10px] px-2 py-0.5 ${e===a?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:["Daemon ",a.toUpperCase(),"+"]},a))]}),s.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:Qx.map(a=>s.jsx("button",{onClick:()=>n(a.value),className:`machine-btn text-[10px] px-2 py-0.5 ${t===a.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:a.label},a.value))})]})})}function Ab({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:i,daemonFetchError:c,traceFetchError:l}){var d,h;const u=((d=e.latestIssue)==null?void 0:d.severity)==="error"?"danger":((h=e.latestIssue)==null?void 0:h.severity)==="warn"?"warning":"good",f=c||l?"danger":i?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${En(e.issueCount>0?"warning":"good")}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Diagnostics timeline"}),s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[t," visible event(s) · ",e.issueCount," issue signal(s)"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:n.trim()?`Filtered by “${n.trim()}”`:"Daemon, trace, and browser signals merged by time"})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${En(u)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[Qa(e.latestIssue.source)," · ",e.latestIssue.severity.toUpperCase()]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:e.latestIssue.message}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2",children:Sl(e.latestIssue.ts)})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No visible warn/error signal"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use Issues or All if you need a narrower or rawer view."})]})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${En(f)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Source status"}),s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:c||l?"Needs attention":i?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",Nb(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(m=>s.jsxs("div",{children:[m.label,": ",m.status]},m.id))})]})]})}function Tb({patterns:e}){return e.length===0?null:s.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/[0.04] p-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Repeated issue patterns"}),s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:e.map(t=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary px-3 py-2",children:[s.jsxs("div",{className:"text-[12px] text-text-primary font-medium",children:[t.count,"× ",t.severity.toUpperCase()," · ",Qa(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function Lb({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:i,visibleTraceEntries:c,visibleWebEvents:l,quickFilter:u,searchQuery:f}){return s.jsxs("div",{className:"grid gap-3",children:[s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(d=>({...d,timeline:!d.timeline})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[n.length," visible diagnostic event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.timeline?"Hide":"Show"})]}),t.timeline&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&n.length===0&&s.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&s.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&s.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),n.map(d=>s.jsx(Cb,{event:d},d.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(d=>({...d,daemon:!d.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${i.length} visible raw line(s) from file fallback`:`${a.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.daemon?"Hide":"Show"})]}),t.daemon&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.daemonLoading&&a.length===0&&i.length===0&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&i.length===0&&e.daemonRawText&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:u==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&a.length===0&&e.daemonLogs.length>0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&i.map((d,h)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:d},`raw-${h}`)),e.daemonLogKind!=="text"&&a.map((d,h)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${ua(d.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(d.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:d.level==="error"?"ERR":d.level==="warn"?"WRN":d.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:d.message})]},`log-${h}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(d=>({...d,trace:!d.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.trace?"Hide":"Show"})]}),t.trace&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.traceLoading&&c.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&c.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&c.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:f.trim()?"No trace entries match the current search.":e.traceCategory==="session_host"?"No session_host trace entries yet. This filter uses get_debug_trace(category=session_host).":"No trace entries yet. Run daemon with --dev or --trace."}),c.map(d=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${ua(d.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(d.ts).toLocaleTimeString()}),s.jsx("span",{children:d.level.toUpperCase()}),s.jsxs("span",{children:[d.category,".",d.stage]}),d.interactionId&&s.jsxs("span",{children:["ix=",d.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:As(d.payload,360)||"No payload"})]},d.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(d=>({...d,web:!d.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[l.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.web?"Hide":"Show"})]}),t.web&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[l.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:f.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),l.map(d=>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(d.ts).toLocaleTimeString()}),s.jsx("span",{children:d.kind}),d.topic&&s.jsxs("span",{children:["topic=",d.topic]}),d.interactionId&&s.jsxs("span",{children:["ix=",d.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:As(d.payload,360)||"No payload"})]},d.id))]})]})]})}function Rb({machineId:e,sendDaemonCommand:t}){const r=ub({machineId:e,sendDaemonCommand:t}),[n,a]=o.useState("info"),[i,c]=o.useState(""),[l,u]=o.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),f=o.useRef(null),d=o.useRef(!1),h=o.useMemo(()=>Sb({daemonLogs:r.daemonLogs,daemonRawText:r.daemonRawText,daemonLogKind:r.daemonLogKind,debugTrace:r.debugTrace,webEvents:r.webEvents,traceCategory:r.traceCategory,quickFilter:n,searchQuery:i,daemonLoading:r.daemonLoading,traceLoading:r.traceLoading,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),[n,i,r.daemonFetchError,r.daemonLoading,r.daemonLogKind,r.daemonLogs,r.daemonRawText,r.debugTrace,r.traceCategory,r.traceFetchError,r.traceLoading,r.webEvents]);o.useEffect(()=>{if(r.autoRefresh&&h.diagnosticEvents.length>0){const k=d.current?"smooth":"instant";setTimeout(()=>{var p;(p=f.current)==null||p.scrollIntoView({behavior:k}),d.current=!0},50)}},[h.diagnosticEvents.length,r.autoRefresh]);const m=o.useCallback(async()=>{var p;const k=db({daemonLogs:h.visibleDaemonLogs,daemonRawLines:h.visibleDaemonRawLines,trace:h.visibleTraceEntries,webEvents:h.visibleWebEvents});if(!k.trim()){it.showToast("No visible logs to copy.","info");return}try{await((p=navigator.clipboard)==null?void 0:p.writeText(k)),it.showToast("Copied visible logs to clipboard.","success")}catch(x){it.showToast(x instanceof Error?x.message:"Could not copy visible logs","warning")}},[h.visibleDaemonLogs,h.visibleDaemonRawLines,h.visibleTraceEntries,h.visibleWebEvents]),v=o.useCallback(async()=>{var p;const k=wb({events:h.diagnosticEvents,summary:h.diagnosticsSummary,sources:h.sourceStates});try{await((p=navigator.clipboard)==null?void 0:p.writeText(k)),it.showToast("Copied diagnostic bundle to clipboard.","success")}catch(x){it.showToast(x instanceof Error?x.message:"Could not copy diagnostic bundle","warning")}},[h.diagnosticEvents,h.diagnosticsSummary,h.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(Ib,{quickFilter:n,quickFilterCounts:h.quickFilterCounts,searchQuery:i,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:c,onCopyDiagnostics:()=>{v()},onCopyVisible:()=>{m()},onToggleAutoRefresh:()=>r.setAutoRefresh(k=>!k),onRefresh:r.refresh,onClear:r.clear}),s.jsx(Mb,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(Ab,{diagnosticsSummary:h.diagnosticsSummary,diagnosticEventsCount:h.diagnosticEvents.length,sourceStates:h.sourceStates,searchQuery:i,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(Tb,{patterns:h.diagnosticsSummary.repeatedPatterns}),s.jsx(Lb,{streams:r,sectionsOpen:l,setSectionsOpen:u,diagnosticEvents:h.diagnosticEvents,visibleDaemonLogs:h.visibleDaemonLogs,visibleDaemonRawLines:h.visibleDaemonRawLines,visibleTraceEntries:h.visibleTraceEntries,visibleWebEvents:h.visibleWebEvents,quickFilter:n,searchQuery:i}),s.jsx("div",{ref:f})]})}function _b(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 Nl(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 Pb(e){var a;const t=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=Nl((i==null?void 0:i.meta)||void 0),u=((a=i==null?void 0:i.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(c)?t.push(i):(c==="stopped"||c==="failed")&&(u||l)?r.push(i):n.push(i)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function Db(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function $n(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 Bn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Kn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function yi(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 Eb(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function $b(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 Bb(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 Kb({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,u]=o.useState(!1),f=kp(e,{enabled:!!e,includeSessions:!0,limit:Lo,intervalMs:Dm}),d=f.diagnostics,h=f.loading,m=f.applyDiagnostics,v=o.useMemo(()=>_b({diagnostics:d,loading:h,refreshing:l,error:n}),[d,h,l,n]),k=o.useMemo(()=>new Map(t.map(A=>[A.sessionId||A.id,A])),[t]),p=o.useCallback(async()=>{if(e){u(!0);try{const A=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Lo}),L=Bn(A);if(!(L!=null&&L.success))throw new Error((L==null?void 0:L.error)||"Could not load hosted runtime diagnostics");m(L.diagnostics||L.result||null),a("")}catch(A){const L=A instanceof Error?A.message:"Could not load hosted runtime diagnostics";a(L)}finally{u(!1)}}},[m,e,r]);o.useEffect(()=>{!e||d||h||l||p()},[d,h,e,p,l]);const x=o.useCallback(async(A,L)=>{const O=`${A}:${L.sessionId}`;if(!(A==="session_host_stop_session"&&!window.confirm(`Stop ${L.displayName}?
77
77
  This will terminate the hosted runtime.`))){c(O);try{const W=await r(e,A,{sessionId:L.sessionId}),P=Bn(W);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Session host action failed");const C=A==="session_host_resume_session"?"resumed":A==="session_host_restart_session"?"restarted":"stopped";it.showToast(`Session host ${C}: ${L.displayName}`,"success"),await p()}catch(W){const P=W instanceof Error?W.message:"Session host action failed";it.showToast(P,"warning"),a(P)}finally{c(W=>W===O?null:W)}}},[e,p,r]),w=o.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
78
- 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 L=await r(e,"session_host_prune_duplicate_sessions",{}),O=Bn(L);if(!(O!=null&&O.success))throw new Error((O==null?void 0:O.error)||"Duplicate prune failed");const W=O.result||{},P=Array.isArray(W.prunedSessionIds)?W.prunedSessionIds.length:0,C=typeof W.duplicateGroupCount=="number"?W.duplicateGroupCount:0;it.showToast(`Pruned ${P} duplicate runtime(s) across ${C} group(s)`,"success"),await p()}catch(L){const O=L instanceof Error?L.message:"Duplicate prune failed";it.showToast(O,"warning"),a(O)}finally{c(L=>L==="session_host_prune_duplicate_sessions"?null:L)}}},[e,p,r]),b=o.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((A,L)=>(L.lastActivityAt||0)-(A.lastActivityAt||0)),[d==null?void 0:d.sessions]),N=o.useMemo(()=>d!=null&&d.liveRuntimes||d!=null&&d.recoverySnapshots||d!=null&&d.inactiveRecords?{liveRuntimes:(d==null?void 0:d.liveRuntimes)||[],recoverySnapshots:(d==null?void 0:d.recoverySnapshots)||[],inactiveRecords:(d==null?void 0:d.inactiveRecords)||[]}:Pb(b),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,b]),I=N.liveRuntimes,y=N.recoverySnapshots,M=N.inactiveRecords,S=o.useMemo(()=>Bb(I),[I]),j=o.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-6).reverse(),[d==null?void 0:d.recentTransitions]),g=o.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(A=>A.level==="warn"||A.level==="error")||null,[d==null?void 0:d.recentLogs]),$=(A,L)=>{var F;const O=i===`session_host_resume_session:${A.sessionId}`,W=i===`session_host_restart_session:${A.sessionId}`,P=i===`session_host_stop_session:${A.sessionId}`,C=Nl(A.meta),T=k.get(A.sessionId),V=A.attachedClients.length===1?"1 client":`${A.attachedClients.length} clients`,E=L==="recovery"?"Recover":"Resume",_=Db(L);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:A.displayName||(T==null?void 0:T.cliName)||A.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${$b(A.lifecycle)}`,children:A.lifecycle}),C&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:C})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:A.workspaceLabel||(T==null?void 0:T.runtimeWorkspaceLabel)||A.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:A.runtimeKey}),A.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",A.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((F=A.writeOwner)==null?void 0:F.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Eb(A.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(Ei,{size:11})," ",V]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",yi(A.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",_]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[L==="recovery"&&(A.lifecycle==="interrupted"||A.lifecycle==="failed"||A.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{x("session_host_resume_session",A)},children:O?`${E}ing…`:E}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{x("session_host_restart_session",A)},children:W?"Restarting…":"Restart"}),L==="live"&&(A.lifecycle==="running"||A.lifecycle==="starting"||A.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:()=>{x("session_host_stop_session",A)},children:P?"Stopping…":"Stop"})]})]})},A.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(cs,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Af()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[S>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{w()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${S})`}),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:h||l,children:[s.jsx(rr,{size:13}),h||l?"Refreshing…":"Refresh"]})]})]}),n&&!d&&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(Qs,{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})]})]})}),d&&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:d.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:d.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:yi(d.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Kn(d.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(Qs,{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:[Kn(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(va,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:$n("live")}),I.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:I.map(A=>$(A,"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(cs,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:$n("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(A=>$(A,"recovery"))})]}),M.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:$n("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:M.map(A=>$(A,"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"}),j.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:j.map(A=>{var O;const L=b.find(W=>W.sessionId===A.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:(L==null?void 0:L.displayName)||((O=k.get(A.sessionId))==null?void 0:O.cliName)||A.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[A.action,A.lifecycle?` · ${A.lifecycle}`:"",A.detail?` · ${A.detail}`:"",A.error?` · ${A.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${A.success===!1?"text-red-300":"text-text-secondary"}`,children:Kn(A.timestamp)})]},`${A.sessionId}:${A.timestamp}:${A.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:d.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function Ob({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 On({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 Wn({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 Wb({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),u=r.slice(0,4),d=Gs(e,"0.9.31");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(On,{icon:s.jsx(Ft,{size:13}),children:"Current Chats"}),s.jsx(Wn,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(h=>{const m=ta(h);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(h),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:at(h)}),m>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Qr(m)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ds(h)})]},h.tabKey)})})})]}),u.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(On,{icon:s.jsx(Wi,{size:13}),children:"Recent Launches"}),s.jsx(Wn,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(h=>{const{metaText:m,updatedLabel:v}=il(h);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(h),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:h.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})]},h.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(On,{icon:s.jsx(Qs,{size:13}),children:"Daemon Update"}),s.jsx(Wn,{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:d?"Daemon update required":"Version mismatch detected"}),s.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:d?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),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(rr,{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"}function Hb({machine:e,selectedWorkspace:t,resolvedWorkspacePath:r,customPath:n,canBrowse:a,onWorkspaceChange:i,onCustomPathChange:c,onOpenBrowseDialog:l}){return s.jsxs("div",{className:"mb-3",children:[s.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[s.jsx("select",{value:t,onChange:u=>{const f=u.target.value;if(i(f),f==="__custom__"&&a){l();return}f!=="__custom__"&&c("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(e.workspaces||[]).length>0?s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(e.workspaces||[]).map(u=>s.jsxs("option",{value:u.id,children:[u.id===e.defaultWorkspaceId?"⭐ ":"",en(u.path,u.label)]},u.id)),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]})}),t==="__custom__"&&(a?s.jsx("button",{type:"button",className:"px-3 py-1.5 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] hover:border-accent-primary text-text-secondary hover:text-text-primary transition-colors",onClick:l,children:"Select workspace…"}):s.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:n,onChange:u=>c(u.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:t==="__custom__"?r?s.jsx("span",{className:"font-mono truncate block",title:r,children:r}):a?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":r?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:t===e.defaultWorkspaceId?"Default workspace":"Selected workspace"}),s.jsx("span",{className:"font-mono truncate block",title:r,children:r})]}):"No workspace selected. This launches in the home directory."})]})}const Ub={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 Mr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Fn({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:f}){const d=Ts(),{handleLaunchIde:h,handleStopCli:m,handleRestartIde:v,handleStopIde:k,handleDetectIdes:p,launchingIde:x,launchingAgentType:w,addLog:b}=c,[N,I]=o.useState(null),y=o.useCallback(R=>{R&&d(Vt(R))},[d]),M=Ub[e],S=e==="ide",j=e==="acp",g=o.useMemo(()=>n.filter(R=>ms(R,e)),[e,n]),$=o.useMemo(()=>new Map(g.map(R=>[R.type,R.displayName||R.type])),[g]),[A,L]=o.useState(""),[O,W]=o.useState(""),[P,C]=o.useState([]),[T,V]=o.useState(""),[E,_]=o.useState(""),[F,J]=o.useState([]),[xe,ce]=o.useState(!1),[te,be]=o.useState(!1),[ge,ve]=o.useState(""),[H,U]=o.useState(!1),[Q,de]=o.useState(()=>pt()),[ne,fe]=o.useState(null),[ae,pe]=o.useState(f?"__custom__":u||t.defaultWorkspaceId||""),[le,ue]=o.useState(f||""),[oe,ye]=o.useState([]),[he,ke]=o.useState(!1),[D,Y]=o.useState(""),[G,X]=o.useState([]),[re,Se]=o.useState(!1),[Ae,$e]=o.useState(""),Be=o.useRef(null),[Ke,qe]=o.useState(null),ze=o.useRef("__home__"),[rt,ct]=o.useState("__home__"),[mt,lt]=o.useState(!1),ut=o.useRef(0),Ie=oe.filter(R=>!a.some(ee=>ee.type===R&&xt(ee.status)!=="stopped")),Ee=o.useRef({});o.useEffect(()=>{t.defaultWorkspaceId&&!ae&&pe(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),o.useEffect(()=>{if(f){pe("__custom__"),ue(f);return}u&&(pe(u),ue(""))},[u,f]),o.useEffect(()=>{S||A&&(g.some(R=>R.type===A)||(L(""),_("")))},[g,S,A]);const Qe=(()=>{if(ae==="__custom__")return le.trim();if(!ae)return"";const R=(t.workspaces||[]).find(ee=>ee.id===ae);return(R==null?void 0:R.path)||""})(),Ve=o.useCallback(R=>{const ee=Ee.current[R];ee&&(clearTimeout(ee),delete Ee.current[R]),ye(me=>me.includes(R)?me.filter(Le=>Le!==R):me)},[]),Ye=o.useRef(new Set),Ze=o.useCallback(async R=>{if(l){Se(!0),$e("");try{const ee=await nn(l,r,R);Y(ee.path),ue(ee.path),X(ee.directories)}catch(ee){$e(ee instanceof Error?ee.message:"Could not load folder")}finally{Se(!1)}}},[r,l]),Z=o.useCallback(()=>{if(!l)return;pe("__custom__"),ke(!0);const R=a.map(me=>me.workspace),ee=rn(t.platform,sn(le.trim(),Qe,f,R,t.defaultWorkspacePath,(t.workspaces||[]).map(me=>me.path)));Ze(ee)},[le,f,Ze,t.defaultWorkspacePath,t.platform,t.workspaces,a,Qe,l]),Re=o.useCallback(R=>{const ee=String(R.workspace||"").trim();if(!ee)return;const me=(t.workspaces||[]).find(Le=>Mr(Le.path)===Mr(ee));if(me){pe(me.id),ue("");return}pe("__custom__"),ue(ee)},[t.workspaces]),_e=o.useCallback(R=>{const ee=String(R.workspace||"").trim();if(!ee)return{workspaceId:null,workspacePath:"",useHome:!0};const me=(t.workspaces||[]).find(Le=>Mr(Le.path)===Mr(ee));return me?{workspaceId:me.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:ee,useHome:!1}},[t.workspaces]),nt=o.useCallback(async R=>{if(!l||!R||e!=="cli"){J([]),ce(!1),be(!1),ve("");return}const ee=ut.current+1;ut.current=ee,ce(!0),ve("");try{const me=await l(r,"list_saved_sessions",{providerType:R,kind:"cli",limit:30});if(ut.current!==ee)return;const Le=(me==null?void 0:me.result)??me;J(Array.isArray(Le==null?void 0:Le.sessions)?Le.sessions:[])}catch(me){if(ut.current!==ee)return;J([]),ve(me instanceof Error?me.message:"Could not load saved sessions")}finally{ut.current===ee&&(ce(!1),be(!0))}},[e,r,l]),Nt=o.useMemo(()=>{if(e!=="cli"||!A)return null;const R=$.get(A)||A;return{routeId:r,daemonId:r,providerSessionId:E||void 0,transport:"pty",mode:"chat",agentName:R,agentType:A,status:"idle",title:R,messages:[],ideType:A,workspaceName:Qe,displayPrimary:R,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${A}`}},[e,r,$,Qe,E,A]),ft=o.useCallback(R=>{if(e==="ide"||!R){C([]);return}C(vl(r,R))},[e,r]);o.useEffect(()=>{ut.current+=1,_(""),ft(A),be(!1),J([]),ve(""),ce(!1)},[e,ft,nt,A]);const At=o.useMemo(()=>F.find(R=>R.providerSessionId===E)||null,[F,E]);o.useEffect(()=>{if(!E)return;const R=F.find(ee=>ee.providerSessionId===E);R!=null&&R.canResume||_("")},[F,E]);const gt=o.useCallback((R,ee)=>{Be.current=ee,ze.current=R.selectedWorkspaceKey||"__home__",ct(R.selectedWorkspaceKey||"__home__"),qe(R)},[]),K=o.useCallback(()=>{Be.current&&(lt(!0),Be.current().finally(()=>{Be.current=null,lt(!1),qe(null)}))},[]),B=o.useCallback(R=>{if(!R)return;ye(me=>me.includes(R)?me:[...me,R]);const ee=Ee.current[R];ee&&clearTimeout(ee),Ee.current[R]=setTimeout(()=>{ye(me=>me.includes(R)?me.filter(Le=>Le!==R):me),delete Ee.current[R]},2e4)},[]);o.useEffect(()=>{for(const ee of a)xt(ee.status)!=="stopped"&&(oe.includes(ee.type)&&!Ye.current.has(ee.type)&&(Ye.current.add(ee.type),b("info",`${$.get(ee.type)||ee.type} launched`,!0)),Ve(ee.type));const R=new Set(a.filter(ee=>xt(ee.status)!=="stopped").map(ee=>ee.type));Ye.current.forEach(ee=>{!oe.includes(ee)&&!R.has(ee)&&Ye.current.delete(ee)})},[b,Ve,a,oe,$]),o.useEffect(()=>()=>{Object.values(Ee.current).forEach(clearTimeout),Ee.current={}},[]);const[z,q]=o.useState({}),[ie,je]=o.useState(null);o.useEffect(()=>{if(!S||!r||!l)return;(async()=>{try{const ee=await l(r,"get_ide_extensions",{}),me=(ee==null?void 0:ee.result)||ee;me!=null&&me.success&&(me!=null&&me.ideExtensions)&&q(me.ideExtensions)}catch{}})()},[S,r,l]);const Me=R=>S?st(R.type):e==="cli"?R.cliName:R.acpName,Ne=S?t.detectedIdes||[]:[],se=o.useCallback(async R=>{const ee=(R==null?void 0:R.type)||A,me=(R==null?void 0:R.workspacePath)??Qe;if(S){await h(ee,me?{workspace:me}:void 0)&&B(ee);return}const Le=await c.runLaunchCliCore({cliType:ee,dir:R!=null&&R.workspaceId?void 0:me||void 0,workspaceId:(R==null?void 0:R.workspaceId)||void 0,useHome:(R==null?void 0:R.useHome)||!(R!=null&&R.workspaceId)&&!me,argsStr:(R==null?void 0:R.argsStr)??(O||void 0),model:(R==null?void 0:R.model)??(j&&T||void 0),resumeSessionId:(R==null?void 0:R.resumeSessionId)||!j&&e==="cli"&&ee===A&&E||void 0});if(Le.success||Le.pending){const Ce=(R==null?void 0:R.argsStr)??O;!S&&(Ce!=null&&Ce.trim())&&(wl(r,ee,Ce),ft(ee)),B(ee),Le.success&&Le.sessionId&&y(Le.sessionId)}},[c,h,j,S,O,T,ft,B,r,y,Qe,E,A]),we=Mc(S?"ide":j?"acp":"cli",!S&&!j&&!!E),Oe=Ac(S?"ide":j?"acp":"cli",!S&&!j&&!!E),Fe=()=>{var Ce;const R=S?st(A):$.get(A)||A,ee=!S&&!j&&!!E,{options:me,selectedKey:Le}=as({machine:t,currentWorkspaceId:ae&&ae!=="__custom__"?ae:null,currentWorkspacePath:Qe});gt({title:ee?$a(R):ts("start-fresh",R),description:ee?Ba():ss("start-fresh"),confirmLabel:we,busyLabel:Oe,workspaceOptions:me,selectedWorkspaceKey:Le,details:[{label:"Mode",value:M.label},{label:"Provider",value:R},...!S&&e==="cli"&&E?[{label:"Resume",value:((Ce=F.find(Te=>Te.providerSessionId===E))==null?void 0:Ce.title)||E}]:[],...!S&&O.trim()?[{label:"Arguments",value:O.trim()}]:[],...j&&T.trim()?[{label:"Model",value:T.trim()}]:[]]},async()=>{const Te=me.find(Ue=>Ue.key===ze.current);Te!=null&&Te.workspaceId?(pe(Te.workspaceId),ue("")):Te!=null&&Te.workspacePath?(pe("__custom__"),ue(Te.workspacePath)):(pe(""),ue("")),await se({workspaceId:(Te==null?void 0:Te.workspaceId)??null,workspacePath:(Te==null?void 0:Te.workspacePath)??"",useHome:!(Te!=null&&Te.workspaceId)&&!(Te!=null&&Te.workspacePath)})})},Xe=R=>{S?k(R):m(R.type,R.workspace,R.id)},He=o.useCallback(async(R,ee,me=!1)=>{if(R.mode===ee){me&&R.sessionId&&y(R.sessionId);return}if(!l||!R.sessionId){me&&R.sessionId&&y(R.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:R.sessionId,cliType:R.type,mode:ee}),me&&y(R.sessionId)}catch(Le){const Ce=Yc(Le);qc(Le)?console.warn(Ce?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Le instanceof Error?Le.message:String(Le)):console.error("Failed to switch CLI view mode:",Le)}},[r,y,l]);return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${M.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 ",M.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:S?Ne.length>0?Ne.map(R=>{const ee=a.find(Ue=>(Ue.type||"").toLowerCase()===(R.type||"").toLowerCase()&&xt(Ue.status)!=="stopped"),me=R.running||!!ee,Le=!!ee&&ee.cdpConnected,Ce=oe.includes(R.type||R.id||""),Te=A===(R.type||"");return s.jsxs("button",{onClick:()=>{if(Le&&ee){const Ue=ee.sessionId;Ue?d(Vt(Ue),{state:{openRemoteForTabKey:Ue}}):d("/dashboard",{state:{openRemoteForTabKey:ee.id}});return}Ce||L(Ue=>Ue===(R.type||"")?"":R.type||"")},disabled:!!x||Ce,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Le?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Te?"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:x&&x!==R.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(R.type)}),me&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Le?"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:R.name||st(R.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Le?"text-green-400":Ce?"text-orange-400":Te?"text-accent-primary":"text-text-muted"}`,children:Le?"Open Session":Ce?"Starting...":Te?"Configure":"Select"})]})]},R.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(Wd,{size:14})," Scan System"]})]}):g.length>0?g.map(R=>{const ee=A===R.type,me=oe.includes(R.type),Ce=!!a.find(Te=>Te.type===R.type&&xt(Te.status)!=="stopped");return s.jsxs("button",{onClick:()=>L(Te=>Te===R.type?"":R.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${ee?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:R.icon}),Ce&&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:R.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${me?"text-orange-400":ee?"text-accent-primary":"text-text-muted"}`,children:me?"Starting...":ee?"Configure":"Select"})]})]},R.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."})]})}),A&&(S?Ne.find(R=>R.type===A):g.find(R=>R.type===A))&&s.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[s.jsx("span",{children:"Launch Settings"}),s.jsx("span",{className:"text-accent-primary font-bold",children:S?st(A):$.get(A)||A})]}),s.jsx(Hb,{machine:t,selectedWorkspace:ae,resolvedWorkspacePath:Qe,customPath:le,canBrowse:!!l,onWorkspaceChange:pe,onCustomPathChange:ue,onOpenBrowseDialog:Z}),!S&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!j&&e==="cli"&&s.jsx(kl,{busy:!!w||!!x||oe.includes(A),savedSessionsLoading:xe,savedSessionsError:ge,selectedSession:At,onRefresh:()=>void nt(A),onOpenHistory:()=>{A&&(U(!0),jl({hasLoadedInitialResults:te,isLoading:xe})&&nt(A))},onClearSelection:()=>_("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[j&&s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),s.jsx("input",{type:"text",placeholder:"Leave empty for default",value:T,onChange:R=>V(R.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"})]}),s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),s.jsx("input",{type:"text",placeholder:"Optional flags...",value:O,onChange:R=>W(R.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),P.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:P.map(R=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>W(R),title:R,children:R},R))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:Fe,disabled:!!w||!!x||oe.includes(A),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:w===A||x===A?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+oe.filter(R=>!a.some(ee=>ee.type===R&&xt(ee.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 ",M.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Ie.map(R=>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(R)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:S?st(R):$.get(R)||R}),s.jsx("div",{className:"text-[11px] text-text-muted",children:w===R?"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:${R}`)),a.map(R=>{const ee=S?R:null,me=!S&&!j?R:null,Le=xt(R.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(R.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Me(R),(ee==null?void 0:ee.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",ee.version]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[s.jsx("span",{children:R.workspace||"—"}),(me==null?void 0:me.mode)&&s.jsx("span",{className:me.mode==="chat"?"text-violet-400":"text-text-secondary",children:me.mode==="chat"?"Chat view":"Terminal view"})]}),me&&(me.runtimeKey||me.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[me.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 ",me.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 Ce;(Ce=navigator.clipboard)==null||Ce.writeText(`adhdev attach ${me.runtimeKey}`),I(me.runtimeKey||null),window.setTimeout(()=>{I(Te=>Te===me.runtimeKey?null:Te)},1200)},children:N===me.runtimeKey?"Copied":"Copy"})]}),me.runtimeWriteOwner&&s.jsx("span",{style:{color:me.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:me.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Fb(me.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 ${Le==="stopped"?"bg-red-500/[0.08] text-red-500":Le==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Le}),S&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const Ce=R.sessionId;if(Ce){d(Vt(Ce),{state:{openRemoteForTabKey:Ce}});return}d("/dashboard",{state:{openRemoteForTabKey:R.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(St,{size:13})}),s.jsx("button",{onClick:()=>{const Ce=R.workspace||"",{options:Te,selectedKey:Ue}=as({machine:t,currentWorkspacePath:Ce});gt({title:ts("restart-ide",st(R.type)),description:ss("restart-ide"),confirmLabel:Is("restart-ide"),busyLabel:Ms("restart-ide"),workspaceOptions:Te,selectedWorkspaceKey:Ue,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:st(R.type)}]},async()=>{const De=Te.find(Ht=>Ht.key===ze.current),ot=(De==null?void 0:De.workspacePath)??"";if(ot&&ot!==Ce){await se({type:R.type,workspacePath:ot});return}await v(R)})},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(rr,{size:14})})]}),j&&s.jsx("button",{onClick:()=>{const Ce=R.sessionId;Ce&&y(Ce)},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:!R.sessionId,children:s.jsx(Ft,{size:14})}),me&&Le!=="stopped"&&s.jsxs(s.Fragment,{children:[me.mode&&s.jsx(Pa,{mode:me.mode,onChange:Ce=>void He(me,Ce,!1),compact:!0}),s.jsx("button",{onClick:()=>{const Ce=R.sessionId;Ce&&y(Ce)},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:!R.sessionId,children:me.mode==="chat"?s.jsx(Ft,{size:14}):s.jsx(St,{size:13})})]}),Le==="stopped"?s.jsx("button",{onClick:()=>{const Ce=R.workspace||"",Te=S?st(R.type):Me(R),{options:Ue,selectedKey:De}=as({machine:t,currentWorkspacePath:Ce});gt({title:ts("restart-stopped",Te),description:ss("restart-stopped"),confirmLabel:Is("restart-stopped"),busyLabel:Ms("restart-stopped"),workspaceOptions:Ue,selectedWorkspaceKey:De,details:[{label:"Mode",value:M.label},{label:"Provider",value:Te}]},async()=>{const ot=Ue.find(Ht=>Ht.key===ze.current);await se({type:R.type,workspaceId:(ot==null?void 0:ot.workspaceId)??null,workspacePath:(ot==null?void 0:ot.workspacePath)??"",useHome:!(ot!=null&&ot.workspaceId)&&!(ot!=null&&ot.workspacePath)})})},disabled:oe.includes(R.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:oe.includes(R.type)?"⏳":s.jsx(wa,{size:14})}):s.jsx("button",{onClick:()=>Xe(R),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(yt,{size:14})})]})]}),ee&&ee.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:ee.aiAgents.map(Ce=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Ji(Ce.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Ce.name," · ",xt(Ce.status)]},Ce.id))}),ee&&(z[ee.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:(z[ee.type]||[]).map(Ce=>s.jsxs("button",{disabled:ie===`${ee.type}.${Ce.type}`,onClick:async()=>{const Te=`${ee.type}.${Ce.type}`;je(Te);try{await l(r,"set_ide_extension",{ideType:ee.type,extensionType:Ce.type,enabled:!Ce.enabled}),q(Ue=>({...Ue,[ee.type]:(Ue[ee.type]||[]).map(De=>De.type===Ce.type?{...De,enabled:!De.enabled}:De)}))}catch(Ue){console.error("Extension toggle failed:",Ue)}finally{je(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 ${Ce.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 ${Ce.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Ce.name,s.jsx("span",{className:"text-[9px] font-normal",children:Ce.enabled?"ON":"OFF"})]},Ce.type))})]})]},R.id)})]}),he&&l&&s.jsx(on,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:D,directories:G,busy:re,error:Ae,confirmLabel:"Use this folder",onClose:()=>ke(!1),onNavigate:R=>{Ze(R)},onConfirm:R=>{ue(R),pe("__custom__"),ke(!1)}}),Ke&&s.jsx(Ya,{title:Ke.title,description:Ke.description,details:Ke.details,workspaceOptions:Ke.workspaceOptions,selectedWorkspaceKey:rt,onWorkspaceChange:R=>{ze.current=R,ct(R)},confirmLabel:Ke.confirmLabel,busyLabel:Ke.busyLabel,busy:mt,onConfirm:K,onCancel:()=>{Be.current=null,qe(null)}}),H&&Nt&&s.jsx(Ka,{activeConv:Nt,ides:[],isCreatingChat:!1,isRefreshingHistory:xe,savedSessions:F,isSavedSessionsLoading:xe,isResumingSavedSessionId:ne,savedHistoryFilters:Q,onSavedHistoryFiltersChange:de,onClose:()=>U(!1),onNewChat:()=>{_(""),U(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{nt(A)},onResumeSavedSession:R=>{if(!R.canResume||ne)return;const ee=_e(R);_(R.providerSessionId),Re(R),fe(R.providerSessionId),U(!1),se({type:R.providerType,workspaceId:ee.workspaceId,workspacePath:ee.workspacePath,useHome:ee.useHome,resumeSessionId:R.providerSessionId}).finally(()=>{fe(me=>me===R.providerSessionId?null:me)})}})]})}const vi=[{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 zb({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:u="ide",initialWorkspaceId:f,initialWorkspacePath:d,sendDaemonCommand:h}){var p;const[m,v]=o.useState(u);o.useEffect(()=>{v(u)},[u]);const k=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:vi.map(x=>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===x.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>v(x.id),children:[s.jsx("span",{children:x.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${m===x.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:k[x.id]})]},x.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(p=vi.find(x=>x.id===m))==null?void 0:p.helper})]}),m==="ide"&&s.jsx(Fn,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:d}),m==="cli"&&s.jsx(Fn,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:d}),m==="acp"&&s.jsx(Fn,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:d})]})}function Vb({onNicknameSynced:e}={}){var fe,ae,pe,le,ue,oe,ye,he,ke;const{id:t}=ud(),r=Ts(),n=xa(),{sendCommand:a}=vt(),i=or(),c=Uc(),l=vc(),u=l.ides||[],f=l.initialLoaded??!0,d=u.find(D=>D.id===t&&D.type==="adhdev-daemon"),h=u.some(D=>D.type==="adhdev-daemon"),[m,v]=o.useState("workspace"),[k,p]=o.useState("ide"),x=o.useRef(null),[w,b]=o.useState(null),N=o.useRef("__home__"),[I,y]=o.useState("__home__"),[M,S]=o.useState(!1),j=o.useRef(null);o.useEffect(()=>{!t||!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||i(t,{minFreshMs:3e4}).catch(()=>{})},[i,d,t]),o.useEffect(()=>{if(!t||!d||m!=="overview")return;const D=d.machine;(typeof(D==null?void 0:D.cpus)!="number"||typeof(D==null?void 0:D.totalMem)!="number"||typeof(D==null?void 0:D.arch)!="string"||typeof(D==null?void 0:D.release)!="string")&&c(t,{minFreshMs:3e4}).catch(()=>{})},[m,c,d,t]),jp(t&&m==="overview"?[t]:[],{enabled:m==="overview",intervalMs:Lm});const g=()=>{if(h){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},$=Wx({machineId:t,registeredMachineId:(d==null?void 0:d.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:j});o.useEffect(()=>it.onToast(Y=>{l.setToasts(X=>{if(X.some(Ae=>Ae.message===Y.message&&Y.timestamp-Ae.timestamp<3e3))return X;const Se={id:Y.id,message:Y.message,type:Y.type,timestamp:Y.timestamp,targetKey:Y.targetKey,actions:Y.actions};return[...X.slice(-4),Se]});const G=Y.duration||5e3;setTimeout(()=>l.setToasts(X=>X.filter(re=>re.id!==Y.id)),G)}),[l]);const A=(d==null?void 0:d.availableProviders)||[],L={};for(const D of A)L[D.type]=D.icon;const O=D=>L[D]||"",W=d?{id:d.id,hostname:Qi(d,{fallbackId:d.id}),platform:((fe=d.machine)==null?void 0:fe.platform)||"unknown",arch:((ae=d.machine)==null?void 0:ae.arch)||"",cpus:((pe=d.machine)==null?void 0:pe.cpus)||0,totalMem:((le=d.machine)==null?void 0:le.totalMem)||0,freeMem:(ue=d.machine)==null?void 0:ue.freeMem,availableMem:(oe=d.machine)==null?void 0:oe.availableMem,loadavg:(ye=d.machine)==null?void 0:ye.loadavg,uptime:(he=d.machine)==null?void 0:he.uptime,release:((ke=d.machine)==null?void 0:ke.release)||"",cdpConnected:!!d.cdpConnected,machineNickname:d.machineNickname||null,p2p:d.p2p?{screenshotActive:!1,...d.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:d.detectedIdes||[],workspaces:d.workspaces||[],defaultWorkspaceId:d.defaultWorkspaceId??d.activeWorkspaceId??null,defaultWorkspacePath:d.defaultWorkspacePath??d.activeWorkspacePath??null}:null,P=u.filter(D=>D.daemonId===t&&D.type!=="adhdev-daemon").filter(D=>!er(D)&&!ys(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,version:D.version||"",instanceId:D.instanceId||"",status:D.status,workspace:D.workspace||null,terminals:D.terminals||0,aiAgents:Eu(D.aiAgents||(D.agents||[]).map(Y=>({id:Y.name,name:Y.name,status:Y.status,version:Y.version}))),activeChat:D.activeChat||null,chats:D.chats||[],childSessions:D.childSessions||[],cdpConnected:D.cdpConnected||!1,daemonId:t})),C=u.filter(D=>D.daemonId===t&&er(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,cliName:D.cliName||D.type,status:D.status,workspace:D.workspace||"",activeChat:D.activeChat||null,providerSessionId:D.providerSessionId,mode:D.mode,runtimeKey:D.runtimeKey,runtimeDisplayName:D.runtimeDisplayName,runtimeWorkspaceLabel:D.runtimeWorkspaceLabel,runtimeWriteOwner:D.runtimeWriteOwner||null,runtimeAttachedClients:D.runtimeAttachedClients||[],daemonId:t})),T=u.filter(D=>D.daemonId===t&&ys(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,acpName:D.cliName||D.type,status:D.status,workspace:D.workspace||"",activeChat:D.activeChat||null,providerSessionId:D.providerSessionId,daemonId:t})),V=d?Mt(d,{fallbackId:t}):"",E="workspace",_=n.state,F=_==null?void 0:_.initialMachineTab,J=_==null?void 0:_.initialWorkspaceCategory,xe=_==null?void 0:_.initialWorkspaceId,ce=_==null?void 0:_.initialWorkspacePath,te=F==="ides"||F==="clis"||F==="acps"?"workspace":F||E,be=F==="ides"?"ide":F==="clis"?"cli":F==="acps"?"acp":J,ge=[...P.map(D=>{var Y,G,X,re,Se;return{id:`ide:${D.type}:${D.workspace||""}`,label:((Y=D.activeChat)==null?void 0:Y.title)||D.type,kind:"ide",providerType:D.type,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((Se=(re=(X=(G=D.activeChat)==null?void 0:G.messages)==null?void 0:X.at)==null?void 0:re.call(X,-1))==null?void 0:Se.timestamp)||0}}),...C.map(D=>{var Y,G,X,re,Se;return{id:`cli:${D.type}:${D.workspace||""}`,label:((Y=D.activeChat)==null?void 0:Y.title)||D.cliName,kind:"cli",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((Se=(re=(X=(G=D.activeChat)==null?void 0:G.messages)==null?void 0:X.at)==null?void 0:re.call(X,-1))==null?void 0:Se.timestamp)||0}}),...T.map(D=>{var Y,G,X,re,Se;return{id:`acp:${D.type}:${D.workspace||""}`,label:((Y=D.activeChat)==null?void 0:Y.title)||D.acpName,kind:"acp",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:ls(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((Se=(re=(X=(G=D.activeChat)==null?void 0:G.messages)==null?void 0:X.at)==null?void 0:re.call(X,-1))==null?void 0:Se.timestamp)||0}})].sort((D,Y)=>(Y.lastLaunchedAt||0)-(D.lastLaunchedAt||0)),ve=((d==null?void 0:d.recentLaunches)||[]).length>0?((d==null?void 0:d.recentLaunches)||[]).map(D=>({id:D.id,label:D.title||D.providerName||D.providerType,kind:D.kind,providerType:D.providerType,providerSessionId:D.providerSessionId,subtitle:ls(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace,summaryMetadata:D.summaryMetadata,lastLaunchedAt:D.lastLaunchedAt})):ge,H=o.useMemo(()=>{var Y;const D=((Y=l.connectionStates)==null?void 0:Y[t||""])||void 0;return u.filter(G=>G.daemonId===t&&G.type!=="adhdev-daemon").flatMap(G=>Oa(G,{connectionStates:t&&D?{[t]:D}:void 0,defaultConnectionState:D})).filter(G=>!(G.transport==="pty"&&G.mode==="terminal")).sort((G,X)=>ta(X)-ta(G))},[u,l.connectionStates,t]),U=o.useCallback(D=>{const Y=Aa(D);Y&&r(Vt(Y))},[r]),Q=o.useCallback(()=>{x.current&&(S(!0),x.current().finally(()=>{x.current=null,S(!1),b(null)}))},[]),de=o.useCallback(D=>{if(!W)return;const{options:Y,selectedKey:G}=as({machine:W,currentWorkspacePath:D.workspace}),X=async()=>{p(D.kind),v("workspace")};x.current=async()=>{const re=Y.find($e=>$e.key===N.current),Se=(re==null?void 0:re.workspacePath)??null,Ae=(re==null?void 0:re.workspaceId)??null;if(D.kind==="ide"&&D.providerType){await $.handleLaunchIde(D.providerType,Se?{workspace:Se}:void 0);return}if((D.kind==="cli"||D.kind==="acp")&&D.providerType){await $.runLaunchCliCore({cliType:D.providerType,dir:Ae?void 0:Se||"",workspaceId:Ae||void 0,model:D.kind==="acp"&&ec(D.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:D.providerSessionId});return}await X()},N.current=G,y(G),b({title:D.kind==="ide"?ts("restart-ide",D.label):D.providerSessionId?$a(D.label):ts("start-fresh",D.label),description:D.kind==="ide"?ss("restart-ide"):D.providerSessionId?Ba():ss("start-fresh"),confirmLabel:D.kind==="ide"?Is("restart-ide"):D.providerSessionId?zr(!0):Is("start-fresh"),busyLabel:D.kind==="ide"?Ms("restart-ide"):D.providerSessionId?Da(!0):Ms("start-fresh"),workspaceOptions:Y,details:[{label:"Mode",value:D.kind.toUpperCase()},...D.providerType?[{label:"Provider",value:D.providerType}]:[]]})},[$,W]);if(o.useEffect(()=>{v(te)},[E,te,t]),o.useEffect(()=>{be&&p(be)},[be,t]),!W)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(St,{size:14})," Workspace"]}),count:P.length+C.length+T.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(cs,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Xr,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Fd,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Kd,{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:[$.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:$.nicknameInput,onChange:D=>$.setNicknameInput(D.target.value),onKeyDown:D=>{D.key==="Enter"&&$.handleSaveNickname(),D.key==="Escape"&&$.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:$.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:()=>$.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:()=>{$.setEditingNickname(!0),$.setNicknameInput(W.machineNickname||"")},title:"Click to set nickname",children:V}),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:[W.platform," · ",W.arch]}),s.jsxs("span",{children:[W.cpus," cores"]}),(d==null?void 0:d.version)&&s.jsxs("span",{children:["v",d.version]}),W.p2p.available&&s.jsxs("span",{children:["P2P ",W.p2p.state==="connected"?"connected":W.p2p.state]}),W.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:W.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(D=>s.jsxs("button",{onClick:()=>v(D.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${m===D.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[D.label,D.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${m===D.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:D.count})]},D.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(Wb,{machineEntry:d,providers:A,recentLaunches:ve,currentConversations:H,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",{})}catch{}},onOpenRecent:de,onOpenConversation:U}),s.jsx(zb,{machine:W,machineId:t,providers:A,ideSessions:P,cliSessions:C,acpSessions:T,actions:$,getIcon:O,initialCategory:k,initialWorkspaceId:xe,initialWorkspacePath:ce,sendDaemonCommand:a})]}),m==="providers"&&s.jsx(Jx,{machineId:t,providers:A,sendDaemonCommand:a}),m==="overview"&&s.jsx(Fx,{machineId:t,machine:W,ideSessions:P,cliSessions:C,acpSessions:T,actions:$,sendDaemonCommand:a}),m==="session-host"&&s.jsx(Kb,{machineId:t,cliSessions:C,sendDaemonCommand:a}),m==="logs"&&s.jsx(Rb,{machineId:t,sendDaemonCommand:a})]})})}),$.launchPick&&W&&s.jsx(Ob,{machine:W,launchPick:$.launchPick,actions:$}),w&&s.jsx(Ya,{title:w.title,description:w.description,details:w.details,workspaceOptions:w.workspaceOptions,selectedWorkspaceKey:I,onWorkspaceChange:D=>{N.current=D,y(D)},confirmLabel:w.confirmLabel,busyLabel:w.busyLabel,busy:M,onConfirm:Q,onCancel:()=>{x.current=null,b(null)}}),s.jsx(Tc,{toasts:l.toasts||[],onDismiss:D=>l.setToasts(Y=>Y.filter(G=>G.id!==D)),onClickToast:D=>{D.targetKey&&r(Vt(D.targetKey))}}),s.jsx("style",{children:`
78
+ 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 L=await r(e,"session_host_prune_duplicate_sessions",{}),O=Bn(L);if(!(O!=null&&O.success))throw new Error((O==null?void 0:O.error)||"Duplicate prune failed");const W=O.result||{},P=Array.isArray(W.prunedSessionIds)?W.prunedSessionIds.length:0,C=typeof W.duplicateGroupCount=="number"?W.duplicateGroupCount:0;it.showToast(`Pruned ${P} duplicate runtime(s) across ${C} group(s)`,"success"),await p()}catch(L){const O=L instanceof Error?L.message:"Duplicate prune failed";it.showToast(O,"warning"),a(O)}finally{c(L=>L==="session_host_prune_duplicate_sessions"?null:L)}}},[e,p,r]),b=o.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((A,L)=>(L.lastActivityAt||0)-(A.lastActivityAt||0)),[d==null?void 0:d.sessions]),N=o.useMemo(()=>d!=null&&d.liveRuntimes||d!=null&&d.recoverySnapshots||d!=null&&d.inactiveRecords?{liveRuntimes:(d==null?void 0:d.liveRuntimes)||[],recoverySnapshots:(d==null?void 0:d.recoverySnapshots)||[],inactiveRecords:(d==null?void 0:d.inactiveRecords)||[]}:Pb(b),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,b]),I=N.liveRuntimes,y=N.recoverySnapshots,M=N.inactiveRecords,S=o.useMemo(()=>Bb(I),[I]),j=o.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-6).reverse(),[d==null?void 0:d.recentTransitions]),g=o.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(A=>A.level==="warn"||A.level==="error")||null,[d==null?void 0:d.recentLogs]),$=(A,L)=>{var F;const O=i===`session_host_resume_session:${A.sessionId}`,W=i===`session_host_restart_session:${A.sessionId}`,P=i===`session_host_stop_session:${A.sessionId}`,C=Nl(A.meta),T=k.get(A.sessionId),V=A.attachedClients.length===1?"1 client":`${A.attachedClients.length} clients`,E=L==="recovery"?"Recover":"Resume",_=Db(L);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:A.displayName||(T==null?void 0:T.cliName)||A.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${$b(A.lifecycle)}`,children:A.lifecycle}),C&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:C})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:A.workspaceLabel||(T==null?void 0:T.runtimeWorkspaceLabel)||A.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:A.runtimeKey}),A.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",A.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((F=A.writeOwner)==null?void 0:F.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Eb(A.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(Ei,{size:11})," ",V]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",yi(A.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",_]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[L==="recovery"&&(A.lifecycle==="interrupted"||A.lifecycle==="failed"||A.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{x("session_host_resume_session",A)},children:O?`${E}ing…`:E}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{x("session_host_restart_session",A)},children:W?"Restarting…":"Restart"}),L==="live"&&(A.lifecycle==="running"||A.lifecycle==="starting"||A.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:()=>{x("session_host_stop_session",A)},children:P?"Stopping…":"Stop"})]})]})},A.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(cs,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Af()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[S>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{w()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${S})`}),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:h||l,children:[s.jsx(rr,{size:13}),h||l?"Refreshing…":"Refresh"]})]})]}),n&&!d&&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(Qs,{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})]})]})}),d&&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:d.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:d.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:yi(d.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Kn(d.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(Qs,{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:[Kn(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(va,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:$n("live")}),I.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:I.map(A=>$(A,"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(cs,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:$n("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(A=>$(A,"recovery"))})]}),M.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:$n("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:M.map(A=>$(A,"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"}),j.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:j.map(A=>{var O;const L=b.find(W=>W.sessionId===A.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:(L==null?void 0:L.displayName)||((O=k.get(A.sessionId))==null?void 0:O.cliName)||A.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[A.action,A.lifecycle?` · ${A.lifecycle}`:"",A.detail?` · ${A.detail}`:"",A.error?` · ${A.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${A.success===!1?"text-red-300":"text-text-secondary"}`,children:Kn(A.timestamp)})]},`${A.sessionId}:${A.timestamp}:${A.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:d.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function Ob({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 On({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 Wn({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 Wb({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),u=r.slice(0,4),d=Gs(e,"0.9.33");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(On,{icon:s.jsx(Ft,{size:13}),children:"Current Chats"}),s.jsx(Wn,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(h=>{const m=ta(h);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(h),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:at(h)}),m>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Qr(m)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ds(h)})]},h.tabKey)})})})]}),u.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(On,{icon:s.jsx(Wi,{size:13}),children:"Recent Launches"}),s.jsx(Wn,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(h=>{const{metaText:m,updatedLabel:v}=il(h);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(h),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:h.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})]},h.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(On,{icon:s.jsx(Qs,{size:13}),children:"Daemon Update"}),s.jsx(Wn,{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:d?"Daemon update required":"Version mismatch detected"}),s.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:d?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),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(rr,{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"}function Hb({machine:e,selectedWorkspace:t,resolvedWorkspacePath:r,customPath:n,canBrowse:a,onWorkspaceChange:i,onCustomPathChange:c,onOpenBrowseDialog:l}){return s.jsxs("div",{className:"mb-3",children:[s.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[s.jsx("select",{value:t,onChange:u=>{const f=u.target.value;if(i(f),f==="__custom__"&&a){l();return}f!=="__custom__"&&c("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(e.workspaces||[]).length>0?s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(e.workspaces||[]).map(u=>s.jsxs("option",{value:u.id,children:[u.id===e.defaultWorkspaceId?"⭐ ":"",en(u.path,u.label)]},u.id)),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]})}),t==="__custom__"&&(a?s.jsx("button",{type:"button",className:"px-3 py-1.5 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] hover:border-accent-primary text-text-secondary hover:text-text-primary transition-colors",onClick:l,children:"Select workspace…"}):s.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:n,onChange:u=>c(u.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:t==="__custom__"?r?s.jsx("span",{className:"font-mono truncate block",title:r,children:r}):a?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":r?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:t===e.defaultWorkspaceId?"Default workspace":"Selected workspace"}),s.jsx("span",{className:"font-mono truncate block",title:r,children:r})]}):"No workspace selected. This launches in the home directory."})]})}const Ub={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 Mr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Fn({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:f}){const d=Ts(),{handleLaunchIde:h,handleStopCli:m,handleRestartIde:v,handleStopIde:k,handleDetectIdes:p,launchingIde:x,launchingAgentType:w,addLog:b}=c,[N,I]=o.useState(null),y=o.useCallback(R=>{R&&d(Vt(R))},[d]),M=Ub[e],S=e==="ide",j=e==="acp",g=o.useMemo(()=>n.filter(R=>ms(R,e)),[e,n]),$=o.useMemo(()=>new Map(g.map(R=>[R.type,R.displayName||R.type])),[g]),[A,L]=o.useState(""),[O,W]=o.useState(""),[P,C]=o.useState([]),[T,V]=o.useState(""),[E,_]=o.useState(""),[F,J]=o.useState([]),[xe,ce]=o.useState(!1),[te,be]=o.useState(!1),[ge,ve]=o.useState(""),[H,U]=o.useState(!1),[Q,de]=o.useState(()=>pt()),[ne,fe]=o.useState(null),[ae,pe]=o.useState(f?"__custom__":u||t.defaultWorkspaceId||""),[le,ue]=o.useState(f||""),[oe,ye]=o.useState([]),[he,ke]=o.useState(!1),[D,Y]=o.useState(""),[G,X]=o.useState([]),[re,Se]=o.useState(!1),[Ae,$e]=o.useState(""),Be=o.useRef(null),[Ke,qe]=o.useState(null),ze=o.useRef("__home__"),[rt,ct]=o.useState("__home__"),[mt,lt]=o.useState(!1),ut=o.useRef(0),Ie=oe.filter(R=>!a.some(ee=>ee.type===R&&xt(ee.status)!=="stopped")),Ee=o.useRef({});o.useEffect(()=>{t.defaultWorkspaceId&&!ae&&pe(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),o.useEffect(()=>{if(f){pe("__custom__"),ue(f);return}u&&(pe(u),ue(""))},[u,f]),o.useEffect(()=>{S||A&&(g.some(R=>R.type===A)||(L(""),_("")))},[g,S,A]);const Qe=(()=>{if(ae==="__custom__")return le.trim();if(!ae)return"";const R=(t.workspaces||[]).find(ee=>ee.id===ae);return(R==null?void 0:R.path)||""})(),Ve=o.useCallback(R=>{const ee=Ee.current[R];ee&&(clearTimeout(ee),delete Ee.current[R]),ye(me=>me.includes(R)?me.filter(Le=>Le!==R):me)},[]),Ye=o.useRef(new Set),Ze=o.useCallback(async R=>{if(l){Se(!0),$e("");try{const ee=await nn(l,r,R);Y(ee.path),ue(ee.path),X(ee.directories)}catch(ee){$e(ee instanceof Error?ee.message:"Could not load folder")}finally{Se(!1)}}},[r,l]),Z=o.useCallback(()=>{if(!l)return;pe("__custom__"),ke(!0);const R=a.map(me=>me.workspace),ee=rn(t.platform,sn(le.trim(),Qe,f,R,t.defaultWorkspacePath,(t.workspaces||[]).map(me=>me.path)));Ze(ee)},[le,f,Ze,t.defaultWorkspacePath,t.platform,t.workspaces,a,Qe,l]),Re=o.useCallback(R=>{const ee=String(R.workspace||"").trim();if(!ee)return;const me=(t.workspaces||[]).find(Le=>Mr(Le.path)===Mr(ee));if(me){pe(me.id),ue("");return}pe("__custom__"),ue(ee)},[t.workspaces]),_e=o.useCallback(R=>{const ee=String(R.workspace||"").trim();if(!ee)return{workspaceId:null,workspacePath:"",useHome:!0};const me=(t.workspaces||[]).find(Le=>Mr(Le.path)===Mr(ee));return me?{workspaceId:me.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:ee,useHome:!1}},[t.workspaces]),nt=o.useCallback(async R=>{if(!l||!R||e!=="cli"){J([]),ce(!1),be(!1),ve("");return}const ee=ut.current+1;ut.current=ee,ce(!0),ve("");try{const me=await l(r,"list_saved_sessions",{providerType:R,kind:"cli",limit:30});if(ut.current!==ee)return;const Le=(me==null?void 0:me.result)??me;J(Array.isArray(Le==null?void 0:Le.sessions)?Le.sessions:[])}catch(me){if(ut.current!==ee)return;J([]),ve(me instanceof Error?me.message:"Could not load saved sessions")}finally{ut.current===ee&&(ce(!1),be(!0))}},[e,r,l]),Nt=o.useMemo(()=>{if(e!=="cli"||!A)return null;const R=$.get(A)||A;return{routeId:r,daemonId:r,providerSessionId:E||void 0,transport:"pty",mode:"chat",agentName:R,agentType:A,status:"idle",title:R,messages:[],ideType:A,workspaceName:Qe,displayPrimary:R,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${A}`}},[e,r,$,Qe,E,A]),ft=o.useCallback(R=>{if(e==="ide"||!R){C([]);return}C(vl(r,R))},[e,r]);o.useEffect(()=>{ut.current+=1,_(""),ft(A),be(!1),J([]),ve(""),ce(!1)},[e,ft,nt,A]);const At=o.useMemo(()=>F.find(R=>R.providerSessionId===E)||null,[F,E]);o.useEffect(()=>{if(!E)return;const R=F.find(ee=>ee.providerSessionId===E);R!=null&&R.canResume||_("")},[F,E]);const gt=o.useCallback((R,ee)=>{Be.current=ee,ze.current=R.selectedWorkspaceKey||"__home__",ct(R.selectedWorkspaceKey||"__home__"),qe(R)},[]),K=o.useCallback(()=>{Be.current&&(lt(!0),Be.current().finally(()=>{Be.current=null,lt(!1),qe(null)}))},[]),B=o.useCallback(R=>{if(!R)return;ye(me=>me.includes(R)?me:[...me,R]);const ee=Ee.current[R];ee&&clearTimeout(ee),Ee.current[R]=setTimeout(()=>{ye(me=>me.includes(R)?me.filter(Le=>Le!==R):me),delete Ee.current[R]},2e4)},[]);o.useEffect(()=>{for(const ee of a)xt(ee.status)!=="stopped"&&(oe.includes(ee.type)&&!Ye.current.has(ee.type)&&(Ye.current.add(ee.type),b("info",`${$.get(ee.type)||ee.type} launched`,!0)),Ve(ee.type));const R=new Set(a.filter(ee=>xt(ee.status)!=="stopped").map(ee=>ee.type));Ye.current.forEach(ee=>{!oe.includes(ee)&&!R.has(ee)&&Ye.current.delete(ee)})},[b,Ve,a,oe,$]),o.useEffect(()=>()=>{Object.values(Ee.current).forEach(clearTimeout),Ee.current={}},[]);const[z,q]=o.useState({}),[ie,je]=o.useState(null);o.useEffect(()=>{if(!S||!r||!l)return;(async()=>{try{const ee=await l(r,"get_ide_extensions",{}),me=(ee==null?void 0:ee.result)||ee;me!=null&&me.success&&(me!=null&&me.ideExtensions)&&q(me.ideExtensions)}catch{}})()},[S,r,l]);const Me=R=>S?st(R.type):e==="cli"?R.cliName:R.acpName,Ne=S?t.detectedIdes||[]:[],se=o.useCallback(async R=>{const ee=(R==null?void 0:R.type)||A,me=(R==null?void 0:R.workspacePath)??Qe;if(S){await h(ee,me?{workspace:me}:void 0)&&B(ee);return}const Le=await c.runLaunchCliCore({cliType:ee,dir:R!=null&&R.workspaceId?void 0:me||void 0,workspaceId:(R==null?void 0:R.workspaceId)||void 0,useHome:(R==null?void 0:R.useHome)||!(R!=null&&R.workspaceId)&&!me,argsStr:(R==null?void 0:R.argsStr)??(O||void 0),model:(R==null?void 0:R.model)??(j&&T||void 0),resumeSessionId:(R==null?void 0:R.resumeSessionId)||!j&&e==="cli"&&ee===A&&E||void 0});if(Le.success||Le.pending){const Ce=(R==null?void 0:R.argsStr)??O;!S&&(Ce!=null&&Ce.trim())&&(wl(r,ee,Ce),ft(ee)),B(ee),Le.success&&Le.sessionId&&y(Le.sessionId)}},[c,h,j,S,O,T,ft,B,r,y,Qe,E,A]),we=Mc(S?"ide":j?"acp":"cli",!S&&!j&&!!E),Oe=Ac(S?"ide":j?"acp":"cli",!S&&!j&&!!E),Fe=()=>{var Ce;const R=S?st(A):$.get(A)||A,ee=!S&&!j&&!!E,{options:me,selectedKey:Le}=as({machine:t,currentWorkspaceId:ae&&ae!=="__custom__"?ae:null,currentWorkspacePath:Qe});gt({title:ee?$a(R):ts("start-fresh",R),description:ee?Ba():ss("start-fresh"),confirmLabel:we,busyLabel:Oe,workspaceOptions:me,selectedWorkspaceKey:Le,details:[{label:"Mode",value:M.label},{label:"Provider",value:R},...!S&&e==="cli"&&E?[{label:"Resume",value:((Ce=F.find(Te=>Te.providerSessionId===E))==null?void 0:Ce.title)||E}]:[],...!S&&O.trim()?[{label:"Arguments",value:O.trim()}]:[],...j&&T.trim()?[{label:"Model",value:T.trim()}]:[]]},async()=>{const Te=me.find(Ue=>Ue.key===ze.current);Te!=null&&Te.workspaceId?(pe(Te.workspaceId),ue("")):Te!=null&&Te.workspacePath?(pe("__custom__"),ue(Te.workspacePath)):(pe(""),ue("")),await se({workspaceId:(Te==null?void 0:Te.workspaceId)??null,workspacePath:(Te==null?void 0:Te.workspacePath)??"",useHome:!(Te!=null&&Te.workspaceId)&&!(Te!=null&&Te.workspacePath)})})},Xe=R=>{S?k(R):m(R.type,R.workspace,R.id)},He=o.useCallback(async(R,ee,me=!1)=>{if(R.mode===ee){me&&R.sessionId&&y(R.sessionId);return}if(!l||!R.sessionId){me&&R.sessionId&&y(R.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:R.sessionId,cliType:R.type,mode:ee}),me&&y(R.sessionId)}catch(Le){const Ce=Yc(Le);qc(Le)?console.warn(Ce?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Le instanceof Error?Le.message:String(Le)):console.error("Failed to switch CLI view mode:",Le)}},[r,y,l]);return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${M.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 ",M.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:S?Ne.length>0?Ne.map(R=>{const ee=a.find(Ue=>(Ue.type||"").toLowerCase()===(R.type||"").toLowerCase()&&xt(Ue.status)!=="stopped"),me=R.running||!!ee,Le=!!ee&&ee.cdpConnected,Ce=oe.includes(R.type||R.id||""),Te=A===(R.type||"");return s.jsxs("button",{onClick:()=>{if(Le&&ee){const Ue=ee.sessionId;Ue?d(Vt(Ue),{state:{openRemoteForTabKey:Ue}}):d("/dashboard",{state:{openRemoteForTabKey:ee.id}});return}Ce||L(Ue=>Ue===(R.type||"")?"":R.type||"")},disabled:!!x||Ce,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Le?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Te?"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:x&&x!==R.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(R.type)}),me&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Le?"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:R.name||st(R.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Le?"text-green-400":Ce?"text-orange-400":Te?"text-accent-primary":"text-text-muted"}`,children:Le?"Open Session":Ce?"Starting...":Te?"Configure":"Select"})]})]},R.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(Wd,{size:14})," Scan System"]})]}):g.length>0?g.map(R=>{const ee=A===R.type,me=oe.includes(R.type),Ce=!!a.find(Te=>Te.type===R.type&&xt(Te.status)!=="stopped");return s.jsxs("button",{onClick:()=>L(Te=>Te===R.type?"":R.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${ee?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:R.icon}),Ce&&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:R.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${me?"text-orange-400":ee?"text-accent-primary":"text-text-muted"}`,children:me?"Starting...":ee?"Configure":"Select"})]})]},R.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."})]})}),A&&(S?Ne.find(R=>R.type===A):g.find(R=>R.type===A))&&s.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[s.jsx("span",{children:"Launch Settings"}),s.jsx("span",{className:"text-accent-primary font-bold",children:S?st(A):$.get(A)||A})]}),s.jsx(Hb,{machine:t,selectedWorkspace:ae,resolvedWorkspacePath:Qe,customPath:le,canBrowse:!!l,onWorkspaceChange:pe,onCustomPathChange:ue,onOpenBrowseDialog:Z}),!S&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!j&&e==="cli"&&s.jsx(kl,{busy:!!w||!!x||oe.includes(A),savedSessionsLoading:xe,savedSessionsError:ge,selectedSession:At,onRefresh:()=>void nt(A),onOpenHistory:()=>{A&&(U(!0),jl({hasLoadedInitialResults:te,isLoading:xe})&&nt(A))},onClearSelection:()=>_("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[j&&s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),s.jsx("input",{type:"text",placeholder:"Leave empty for default",value:T,onChange:R=>V(R.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"})]}),s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),s.jsx("input",{type:"text",placeholder:"Optional flags...",value:O,onChange:R=>W(R.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),P.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:P.map(R=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>W(R),title:R,children:R},R))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:Fe,disabled:!!w||!!x||oe.includes(A),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:w===A||x===A?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+oe.filter(R=>!a.some(ee=>ee.type===R&&xt(ee.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 ",M.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Ie.map(R=>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(R)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:S?st(R):$.get(R)||R}),s.jsx("div",{className:"text-[11px] text-text-muted",children:w===R?"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:${R}`)),a.map(R=>{const ee=S?R:null,me=!S&&!j?R:null,Le=xt(R.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(R.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Me(R),(ee==null?void 0:ee.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",ee.version]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[s.jsx("span",{children:R.workspace||"—"}),(me==null?void 0:me.mode)&&s.jsx("span",{className:me.mode==="chat"?"text-violet-400":"text-text-secondary",children:me.mode==="chat"?"Chat view":"Terminal view"})]}),me&&(me.runtimeKey||me.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[me.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 ",me.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 Ce;(Ce=navigator.clipboard)==null||Ce.writeText(`adhdev attach ${me.runtimeKey}`),I(me.runtimeKey||null),window.setTimeout(()=>{I(Te=>Te===me.runtimeKey?null:Te)},1200)},children:N===me.runtimeKey?"Copied":"Copy"})]}),me.runtimeWriteOwner&&s.jsx("span",{style:{color:me.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:me.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Fb(me.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 ${Le==="stopped"?"bg-red-500/[0.08] text-red-500":Le==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Le}),S&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const Ce=R.sessionId;if(Ce){d(Vt(Ce),{state:{openRemoteForTabKey:Ce}});return}d("/dashboard",{state:{openRemoteForTabKey:R.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(St,{size:13})}),s.jsx("button",{onClick:()=>{const Ce=R.workspace||"",{options:Te,selectedKey:Ue}=as({machine:t,currentWorkspacePath:Ce});gt({title:ts("restart-ide",st(R.type)),description:ss("restart-ide"),confirmLabel:Is("restart-ide"),busyLabel:Ms("restart-ide"),workspaceOptions:Te,selectedWorkspaceKey:Ue,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:st(R.type)}]},async()=>{const De=Te.find(Ht=>Ht.key===ze.current),ot=(De==null?void 0:De.workspacePath)??"";if(ot&&ot!==Ce){await se({type:R.type,workspacePath:ot});return}await v(R)})},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(rr,{size:14})})]}),j&&s.jsx("button",{onClick:()=>{const Ce=R.sessionId;Ce&&y(Ce)},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:!R.sessionId,children:s.jsx(Ft,{size:14})}),me&&Le!=="stopped"&&s.jsxs(s.Fragment,{children:[me.mode&&s.jsx(Pa,{mode:me.mode,onChange:Ce=>void He(me,Ce,!1),compact:!0}),s.jsx("button",{onClick:()=>{const Ce=R.sessionId;Ce&&y(Ce)},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:!R.sessionId,children:me.mode==="chat"?s.jsx(Ft,{size:14}):s.jsx(St,{size:13})})]}),Le==="stopped"?s.jsx("button",{onClick:()=>{const Ce=R.workspace||"",Te=S?st(R.type):Me(R),{options:Ue,selectedKey:De}=as({machine:t,currentWorkspacePath:Ce});gt({title:ts("restart-stopped",Te),description:ss("restart-stopped"),confirmLabel:Is("restart-stopped"),busyLabel:Ms("restart-stopped"),workspaceOptions:Ue,selectedWorkspaceKey:De,details:[{label:"Mode",value:M.label},{label:"Provider",value:Te}]},async()=>{const ot=Ue.find(Ht=>Ht.key===ze.current);await se({type:R.type,workspaceId:(ot==null?void 0:ot.workspaceId)??null,workspacePath:(ot==null?void 0:ot.workspacePath)??"",useHome:!(ot!=null&&ot.workspaceId)&&!(ot!=null&&ot.workspacePath)})})},disabled:oe.includes(R.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:oe.includes(R.type)?"⏳":s.jsx(wa,{size:14})}):s.jsx("button",{onClick:()=>Xe(R),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(yt,{size:14})})]})]}),ee&&ee.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:ee.aiAgents.map(Ce=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Ji(Ce.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Ce.name," · ",xt(Ce.status)]},Ce.id))}),ee&&(z[ee.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:(z[ee.type]||[]).map(Ce=>s.jsxs("button",{disabled:ie===`${ee.type}.${Ce.type}`,onClick:async()=>{const Te=`${ee.type}.${Ce.type}`;je(Te);try{await l(r,"set_ide_extension",{ideType:ee.type,extensionType:Ce.type,enabled:!Ce.enabled}),q(Ue=>({...Ue,[ee.type]:(Ue[ee.type]||[]).map(De=>De.type===Ce.type?{...De,enabled:!De.enabled}:De)}))}catch(Ue){console.error("Extension toggle failed:",Ue)}finally{je(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 ${Ce.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 ${Ce.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Ce.name,s.jsx("span",{className:"text-[9px] font-normal",children:Ce.enabled?"ON":"OFF"})]},Ce.type))})]})]},R.id)})]}),he&&l&&s.jsx(on,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:D,directories:G,busy:re,error:Ae,confirmLabel:"Use this folder",onClose:()=>ke(!1),onNavigate:R=>{Ze(R)},onConfirm:R=>{ue(R),pe("__custom__"),ke(!1)}}),Ke&&s.jsx(Ya,{title:Ke.title,description:Ke.description,details:Ke.details,workspaceOptions:Ke.workspaceOptions,selectedWorkspaceKey:rt,onWorkspaceChange:R=>{ze.current=R,ct(R)},confirmLabel:Ke.confirmLabel,busyLabel:Ke.busyLabel,busy:mt,onConfirm:K,onCancel:()=>{Be.current=null,qe(null)}}),H&&Nt&&s.jsx(Ka,{activeConv:Nt,ides:[],isCreatingChat:!1,isRefreshingHistory:xe,savedSessions:F,isSavedSessionsLoading:xe,isResumingSavedSessionId:ne,savedHistoryFilters:Q,onSavedHistoryFiltersChange:de,onClose:()=>U(!1),onNewChat:()=>{_(""),U(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{nt(A)},onResumeSavedSession:R=>{if(!R.canResume||ne)return;const ee=_e(R);_(R.providerSessionId),Re(R),fe(R.providerSessionId),U(!1),se({type:R.providerType,workspaceId:ee.workspaceId,workspacePath:ee.workspacePath,useHome:ee.useHome,resumeSessionId:R.providerSessionId}).finally(()=>{fe(me=>me===R.providerSessionId?null:me)})}})]})}const vi=[{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 zb({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:u="ide",initialWorkspaceId:f,initialWorkspacePath:d,sendDaemonCommand:h}){var p;const[m,v]=o.useState(u);o.useEffect(()=>{v(u)},[u]);const k=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:vi.map(x=>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===x.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>v(x.id),children:[s.jsx("span",{children:x.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${m===x.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:k[x.id]})]},x.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(p=vi.find(x=>x.id===m))==null?void 0:p.helper})]}),m==="ide"&&s.jsx(Fn,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:d}),m==="cli"&&s.jsx(Fn,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:d}),m==="acp"&&s.jsx(Fn,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:d})]})}function Vb({onNicknameSynced:e}={}){var fe,ae,pe,le,ue,oe,ye,he,ke;const{id:t}=ud(),r=Ts(),n=xa(),{sendCommand:a}=vt(),i=or(),c=Uc(),l=vc(),u=l.ides||[],f=l.initialLoaded??!0,d=u.find(D=>D.id===t&&D.type==="adhdev-daemon"),h=u.some(D=>D.type==="adhdev-daemon"),[m,v]=o.useState("workspace"),[k,p]=o.useState("ide"),x=o.useRef(null),[w,b]=o.useState(null),N=o.useRef("__home__"),[I,y]=o.useState("__home__"),[M,S]=o.useState(!1),j=o.useRef(null);o.useEffect(()=>{!t||!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||i(t,{minFreshMs:3e4}).catch(()=>{})},[i,d,t]),o.useEffect(()=>{if(!t||!d||m!=="overview")return;const D=d.machine;(typeof(D==null?void 0:D.cpus)!="number"||typeof(D==null?void 0:D.totalMem)!="number"||typeof(D==null?void 0:D.arch)!="string"||typeof(D==null?void 0:D.release)!="string")&&c(t,{minFreshMs:3e4}).catch(()=>{})},[m,c,d,t]),jp(t&&m==="overview"?[t]:[],{enabled:m==="overview",intervalMs:Lm});const g=()=>{if(h){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},$=Wx({machineId:t,registeredMachineId:(d==null?void 0:d.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:j});o.useEffect(()=>it.onToast(Y=>{l.setToasts(X=>{if(X.some(Ae=>Ae.message===Y.message&&Y.timestamp-Ae.timestamp<3e3))return X;const Se={id:Y.id,message:Y.message,type:Y.type,timestamp:Y.timestamp,targetKey:Y.targetKey,actions:Y.actions};return[...X.slice(-4),Se]});const G=Y.duration||5e3;setTimeout(()=>l.setToasts(X=>X.filter(re=>re.id!==Y.id)),G)}),[l]);const A=(d==null?void 0:d.availableProviders)||[],L={};for(const D of A)L[D.type]=D.icon;const O=D=>L[D]||"",W=d?{id:d.id,hostname:Qi(d,{fallbackId:d.id}),platform:((fe=d.machine)==null?void 0:fe.platform)||"unknown",arch:((ae=d.machine)==null?void 0:ae.arch)||"",cpus:((pe=d.machine)==null?void 0:pe.cpus)||0,totalMem:((le=d.machine)==null?void 0:le.totalMem)||0,freeMem:(ue=d.machine)==null?void 0:ue.freeMem,availableMem:(oe=d.machine)==null?void 0:oe.availableMem,loadavg:(ye=d.machine)==null?void 0:ye.loadavg,uptime:(he=d.machine)==null?void 0:he.uptime,release:((ke=d.machine)==null?void 0:ke.release)||"",cdpConnected:!!d.cdpConnected,machineNickname:d.machineNickname||null,p2p:d.p2p?{screenshotActive:!1,...d.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:d.detectedIdes||[],workspaces:d.workspaces||[],defaultWorkspaceId:d.defaultWorkspaceId??d.activeWorkspaceId??null,defaultWorkspacePath:d.defaultWorkspacePath??d.activeWorkspacePath??null}:null,P=u.filter(D=>D.daemonId===t&&D.type!=="adhdev-daemon").filter(D=>!er(D)&&!ys(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,version:D.version||"",instanceId:D.instanceId||"",status:D.status,workspace:D.workspace||null,terminals:D.terminals||0,aiAgents:Eu(D.aiAgents||(D.agents||[]).map(Y=>({id:Y.name,name:Y.name,status:Y.status,version:Y.version}))),activeChat:D.activeChat||null,chats:D.chats||[],childSessions:D.childSessions||[],cdpConnected:D.cdpConnected||!1,daemonId:t})),C=u.filter(D=>D.daemonId===t&&er(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,cliName:D.cliName||D.type,status:D.status,workspace:D.workspace||"",activeChat:D.activeChat||null,providerSessionId:D.providerSessionId,mode:D.mode,runtimeKey:D.runtimeKey,runtimeDisplayName:D.runtimeDisplayName,runtimeWorkspaceLabel:D.runtimeWorkspaceLabel,runtimeWriteOwner:D.runtimeWriteOwner||null,runtimeAttachedClients:D.runtimeAttachedClients||[],daemonId:t})),T=u.filter(D=>D.daemonId===t&&ys(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,acpName:D.cliName||D.type,status:D.status,workspace:D.workspace||"",activeChat:D.activeChat||null,providerSessionId:D.providerSessionId,daemonId:t})),V=d?Mt(d,{fallbackId:t}):"",E="workspace",_=n.state,F=_==null?void 0:_.initialMachineTab,J=_==null?void 0:_.initialWorkspaceCategory,xe=_==null?void 0:_.initialWorkspaceId,ce=_==null?void 0:_.initialWorkspacePath,te=F==="ides"||F==="clis"||F==="acps"?"workspace":F||E,be=F==="ides"?"ide":F==="clis"?"cli":F==="acps"?"acp":J,ge=[...P.map(D=>{var Y,G,X,re,Se;return{id:`ide:${D.type}:${D.workspace||""}`,label:((Y=D.activeChat)==null?void 0:Y.title)||D.type,kind:"ide",providerType:D.type,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((Se=(re=(X=(G=D.activeChat)==null?void 0:G.messages)==null?void 0:X.at)==null?void 0:re.call(X,-1))==null?void 0:Se.timestamp)||0}}),...C.map(D=>{var Y,G,X,re,Se;return{id:`cli:${D.type}:${D.workspace||""}`,label:((Y=D.activeChat)==null?void 0:Y.title)||D.cliName,kind:"cli",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((Se=(re=(X=(G=D.activeChat)==null?void 0:G.messages)==null?void 0:X.at)==null?void 0:re.call(X,-1))==null?void 0:Se.timestamp)||0}}),...T.map(D=>{var Y,G,X,re,Se;return{id:`acp:${D.type}:${D.workspace||""}`,label:((Y=D.activeChat)==null?void 0:Y.title)||D.acpName,kind:"acp",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:ls(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((Se=(re=(X=(G=D.activeChat)==null?void 0:G.messages)==null?void 0:X.at)==null?void 0:re.call(X,-1))==null?void 0:Se.timestamp)||0}})].sort((D,Y)=>(Y.lastLaunchedAt||0)-(D.lastLaunchedAt||0)),ve=((d==null?void 0:d.recentLaunches)||[]).length>0?((d==null?void 0:d.recentLaunches)||[]).map(D=>({id:D.id,label:D.title||D.providerName||D.providerType,kind:D.kind,providerType:D.providerType,providerSessionId:D.providerSessionId,subtitle:ls(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace,summaryMetadata:D.summaryMetadata,lastLaunchedAt:D.lastLaunchedAt})):ge,H=o.useMemo(()=>{var Y;const D=((Y=l.connectionStates)==null?void 0:Y[t||""])||void 0;return u.filter(G=>G.daemonId===t&&G.type!=="adhdev-daemon").flatMap(G=>Oa(G,{connectionStates:t&&D?{[t]:D}:void 0,defaultConnectionState:D})).filter(G=>!(G.transport==="pty"&&G.mode==="terminal")).sort((G,X)=>ta(X)-ta(G))},[u,l.connectionStates,t]),U=o.useCallback(D=>{const Y=Aa(D);Y&&r(Vt(Y))},[r]),Q=o.useCallback(()=>{x.current&&(S(!0),x.current().finally(()=>{x.current=null,S(!1),b(null)}))},[]),de=o.useCallback(D=>{if(!W)return;const{options:Y,selectedKey:G}=as({machine:W,currentWorkspacePath:D.workspace}),X=async()=>{p(D.kind),v("workspace")};x.current=async()=>{const re=Y.find($e=>$e.key===N.current),Se=(re==null?void 0:re.workspacePath)??null,Ae=(re==null?void 0:re.workspaceId)??null;if(D.kind==="ide"&&D.providerType){await $.handleLaunchIde(D.providerType,Se?{workspace:Se}:void 0);return}if((D.kind==="cli"||D.kind==="acp")&&D.providerType){await $.runLaunchCliCore({cliType:D.providerType,dir:Ae?void 0:Se||"",workspaceId:Ae||void 0,model:D.kind==="acp"&&ec(D.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:D.providerSessionId});return}await X()},N.current=G,y(G),b({title:D.kind==="ide"?ts("restart-ide",D.label):D.providerSessionId?$a(D.label):ts("start-fresh",D.label),description:D.kind==="ide"?ss("restart-ide"):D.providerSessionId?Ba():ss("start-fresh"),confirmLabel:D.kind==="ide"?Is("restart-ide"):D.providerSessionId?zr(!0):Is("start-fresh"),busyLabel:D.kind==="ide"?Ms("restart-ide"):D.providerSessionId?Da(!0):Ms("start-fresh"),workspaceOptions:Y,details:[{label:"Mode",value:D.kind.toUpperCase()},...D.providerType?[{label:"Provider",value:D.providerType}]:[]]})},[$,W]);if(o.useEffect(()=>{v(te)},[E,te,t]),o.useEffect(()=>{be&&p(be)},[be,t]),!W)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(St,{size:14})," Workspace"]}),count:P.length+C.length+T.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(cs,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Xr,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Fd,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Kd,{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:[$.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:$.nicknameInput,onChange:D=>$.setNicknameInput(D.target.value),onKeyDown:D=>{D.key==="Enter"&&$.handleSaveNickname(),D.key==="Escape"&&$.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:$.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:()=>$.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:()=>{$.setEditingNickname(!0),$.setNicknameInput(W.machineNickname||"")},title:"Click to set nickname",children:V}),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:[W.platform," · ",W.arch]}),s.jsxs("span",{children:[W.cpus," cores"]}),(d==null?void 0:d.version)&&s.jsxs("span",{children:["v",d.version]}),W.p2p.available&&s.jsxs("span",{children:["P2P ",W.p2p.state==="connected"?"connected":W.p2p.state]}),W.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:W.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(D=>s.jsxs("button",{onClick:()=>v(D.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${m===D.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[D.label,D.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${m===D.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:D.count})]},D.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(Wb,{machineEntry:d,providers:A,recentLaunches:ve,currentConversations:H,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",{})}catch{}},onOpenRecent:de,onOpenConversation:U}),s.jsx(zb,{machine:W,machineId:t,providers:A,ideSessions:P,cliSessions:C,acpSessions:T,actions:$,getIcon:O,initialCategory:k,initialWorkspaceId:xe,initialWorkspacePath:ce,sendDaemonCommand:a})]}),m==="providers"&&s.jsx(Jx,{machineId:t,providers:A,sendDaemonCommand:a}),m==="overview"&&s.jsx(Fx,{machineId:t,machine:W,ideSessions:P,cliSessions:C,acpSessions:T,actions:$,sendDaemonCommand:a}),m==="session-host"&&s.jsx(Kb,{machineId:t,cliSessions:C,sendDaemonCommand:a}),m==="logs"&&s.jsx(Rb,{machineId:t,sendDaemonCommand:a})]})})}),$.launchPick&&W&&s.jsx(Ob,{machine:W,launchPick:$.launchPick,actions:$}),w&&s.jsx(Ya,{title:w.title,description:w.description,details:w.details,workspaceOptions:w.workspaceOptions,selectedWorkspaceKey:I,onWorkspaceChange:D=>{N.current=D,y(D)},confirmLabel:w.confirmLabel,busyLabel:w.busyLabel,busy:M,onConfirm:Q,onCancel:()=>{x.current=null,b(null)}}),s.jsx(Tc,{toasts:l.toasts||[],onDismiss:D=>l.setToasts(Y=>Y.filter(G=>G.id!==D)),onClickToast:D=>{D.targetKey&&r(Vt(D.targetKey))}}),s.jsx("style",{children:`
79
79
  @keyframes toast-in {
80
80
  from { opacity: 0; transform: translateX(40px); }
81
81
  to { opacity: 1; transform: translateX(0); }
82
82
  }
83
- `})]})}function Za(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function Gb(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=Za();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 Dt(e,t){return await fetch(Gb(e),{credentials:"same-origin",...t})}function Cl(){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 qb{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,n){if(!r)return{success:!1,error:"sessionId is required"};const a=new URL(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`,window.location.origin);typeof(n==null?void 0:n.sinceSeq)=="number"&&a.searchParams.set("sinceSeq",String(n.sinceSeq));const i=await Dt(`${a.pathname}${a.search}`);if(!i.ok){let l=`Runtime snapshot unavailable (${i.status})`;try{const u=await i.json();u!=null&&u.error&&(l=u.error)}catch{}return{success:!1,error:l}}const c=await i.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof c.seq=="number"?c.seq:0,text:typeof c.text=="string"?c.text:"",truncated:!!c.truncated,cols:typeof c.cols=="number"?c.cols:void 0,rows:typeof c.rows=="number"?c.rows:void 0,force:!!(n!=null&&n.force)}),{success:!0}}emitRuntimeEvent(t,r){var n;(n=this.runtimeListeners.get(t))==null||n.forEach(a=>a(r))}}const Kt=new qb;function Yb(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=Za();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Ar=Yb(),wi=3e3,Xb=3e4;let Rt=null,Jb=0;const Yr=new Map;let Xt=null,Ys=null;function ji(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Ws(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function Qb(e){return e==="connected"?"connected":e}async function $r(e,t,r){const n=_c(e,r||{}),a=Rt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++Jb}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{Yr.delete(i),l(new Error(`WS command timeout: ${t}`))},3e4);Yr.set(i,{resolve:f=>{clearTimeout(u),c(f)},reject:f=>{clearTimeout(u),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 ma(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 Zb(e,t,r){const n=Rt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=_c(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 eg{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 $r(this.daemonId,t,r)}async sendInput(t,r){return $r(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Xt&&(clearInterval(Xt),Xt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await $r(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());Kt.emitScreenshot(this.daemonId,a)}}catch{}};r(),Xt=setInterval(r,2e3)}stopScreenshots(t){Xt&&(clearInterval(Xt),Xt=null)}}let It=null;function tg(e){return(!It||It.daemonId!==e)&&(It=new eg(e)),It}function sg({children:e}){const t=o.useRef(Js()),r=Js();t.current=r;const{setUserName:n}=is(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),u=o.useCallback((p,x)=>{l(p),Ys==null||Ys(p,x)},[]),f=o.useRef(null),d=o.useRef(),h=o.useRef(wi),m=o.useRef(!0),v=o.useRef(!1),k=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;u("connecting"),console.log(`[Standalone WS] Connecting to ${Ar}...`),Ws("connect_attempt",{url:Ar,reason:k.current,delayMs:h.current});let w;try{w=new WebSocket(Ar)}catch(I){console.error("[Standalone WS] Failed to create WebSocket:",I),x();return}f.current=w,w.onopen=()=>{if(!m.current){w.close();return}u("connected"),h.current=wi,Ws("open",{url:Ar,reason:k.current}),Gt.resubscribeAll({sendData:ma}),console.log("[Standalone WS] Connected")},Rt=w,w.onmessage=I=>{var y,M;try{const S=JSON.parse(I.data);if((S.type==="command_result"||S.type==="error")&&S.requestId){const j=Yr.get(S.requestId);j&&(Yr.delete(S.requestId),S.type==="error"?j.reject(new Error(((y=S.data)==null?void 0:y.message)||"Command failed")):j.resolve(S.data));return}if(S.type==="session_output"){const j=S.sessionId||S.cliId||S.cliType;j&&Kt.emitSessionOutput(j,typeof S.data=="string"?S.data:"",typeof S.seq=="number"?S.seq:void 0);return}if(S.type==="runtime_snapshot"){Kt.emitRuntimeSnapshot(S.sessionId,typeof S.text=="string"?S.text:"",typeof S.seq=="number"?S.seq:0,!!S.truncated,typeof S.cols=="number"?S.cols:void 0,typeof S.rows=="number"?S.rows:void 0);return}if(S.type==="topic_update"){const j=S.update;j&&Gt.publish(j);return}if(S.type==="status"||S.type==="initial_state"){const j=S.data;if(!j)return;const{injectEntries:g,markLoaded:$,getIdes:A}=t.current,L=j.instanceId||"standalone",O=A().find(C=>C.id===L),W=tg(L);Kt.register(L,W),Kt.setState(L,"connected"),u("connected",L),Kt.emitStatus(L,j);const P=Ur(j,{daemonId:L,existingDaemon:O,existingEntries:A()});ji("ws_status",{type:S.type,daemonId:L,sessions:(j.sessions||[]).map(C=>({id:C.id,parentId:C.parentId,providerType:C.providerType,kind:C.kind,transport:C.transport,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,title:C.title})),recentLaunches:(j.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),ji("entries",{daemonId:L,entries:P.filter(C=>C.type!=="adhdev-daemon").map(C=>({id:C.id,type:C.type,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,sessionId:C.sessionId}))}),P.length>0&&g(P,{authoritativeDaemonIds:[L]}),$(),c.current!==L&&((M=i.current)==null||M.call(i),c.current=L,i.current=Gt.subscribe({sendData:ma},L,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${L}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const T=t.current.getIdes(),V=T.find(_=>_.id===L),E=Ur(C.status,{daemonId:L,existingDaemon:V,existingEntries:T,timestamp:C.timestamp});E.length>0&&t.current.injectEntries(E,{authoritativeDaemonIds:[L]}),C.userName&&a.current&&a.current(C.userName)}))}}catch(S){console.error("[Standalone WS] Parse error:",S)}},w.onclose=I=>{m.current&&(It==null||It.stopScreenshots(),It&&Kt.setState(It.daemonId,"disconnected"),u("disconnected"),f.current=null,k.current=`close:${I.code}${I.wasClean?":clean":":unclean"}`,Ws("close",{code:I.code,reason:I.reason||"",wasClean:I.wasClean}),x())},w.onerror=I=>{v.current||!m.current||(k.current="error",Ws("error",{message:I instanceof Event?"event":String(I),readyState:w.readyState}),console.warn("[Standalone WS] Error, will reconnect:",I))}}function x(){if(!m.current)return;clearTimeout(d.current);const w=h.current;console.log(`[Standalone WS] Reconnecting in ${w}ms...`),Ws("schedule_reconnect",{reason:k.current,delayMs:w}),d.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,Xb),p()},w)}return p(),()=>{var w;m.current=!1,v.current=!0,(w=i.current)==null||w.call(i),i.current=null,c.current=null,clearTimeout(d.current),f.current&&(f.current.onerror=null,f.current.onclose=null,f.current.close(),f.current=null,Rt=null),It&&(It.stopScreenshots(),Kt.unregister(It.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function rg({children:e}){const[t,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(Ys=(c,l)=>{r(c),l&&a(l)},()=>{Ys=null}),[]);const i=o.useMemo(()=>{const c=t==="connected",l=Qb(t),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:t,isConnected:c,connectionStates:u}},[t,n]);return s.jsx(Ad,{connectionOverrides:i,children:s.jsx(sg,{children:e})})}const Il="adhdev_standalone_font_preferences",os={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},dn=[{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"}],sr=[{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"}],ng=new Set(dn.map(e=>e.id)),ag=new Set(sr.map(e=>e.id));function $t(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Br("chat",t.chat),code:Br("code",t.code),terminal:Br("terminal",t.terminal)}}function Br(e,t){const r=os[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"?ng:ag).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:a}:r}function Kr(e,t){var a;const r=Br(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?dn:sr;return((a=n.find(i=>i.id===r.preset))==null?void 0:a.family)||n[0].family}function og(e){const t=$t(e),r=Kr("chat",t.chat),n=Kr("code",t.code),a=Kr("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Qt(e,t=document.documentElement){const r=$t(e),n=og(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))t.style.setProperty(a,i);return r}function fa(e){const t=$t(e);try{localStorage.setItem(Il,JSON.stringify(t))}catch{}return t}function ig(){try{const e=localStorage.getItem(Il);if(e)return $t(JSON.parse(e))}catch{}return os}function cg(){return Qt(ig())}function Fs(e,t){var n;const r=e==="chat"?dn:sr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const lg=[{id:"dashboard",path:"/dashboard",icon:s.jsx(Di,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(cs,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:s.jsx(Xr,{}),label:"Settings"}];function dg({children:e}){const t=Ts(),r=xa(),n=o.useMemo(()=>lg.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($i,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Bi,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(qf,{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.31"]}),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 ug=[{icon:s.jsx(cs,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Ft,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Ki,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(St,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Zs,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx($i,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],mg=[{icon:s.jsx(Ud,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Di,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Jr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Bd,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Ei,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Od,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],fg=[{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 pg(){return s.jsxs($c,{icon:s.jsx(Bi,{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.31"]}),children:[s.jsx(kt,{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(kt,{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:ug.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(kt,{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:Pc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Ec.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Dc.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(kt,{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:mg.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(kt,{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:fg.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(Kc,{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(eu,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Hn(e,t,r){return{...e,[t]:r}}function Un({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:Kr(e,n)})]})]})]})}function hg({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:i,onSave:c,onResetToSaved:l,onResetToDefaults:u}){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(Un,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:dn,onChange:d=>i(Hn(e,"chat",d))}),s.jsx(Un,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:sr,onChange:d=>i(Hn(e,"code",d))}),s.jsx(Un,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:sr,onChange:d=>i(Hn(e,"terminal",d))})]}),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: ",Fs("chat",e.chat.preset)," · Code: ",Fs("code",e.code.preset)," · Terminal: ",Fs("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Fs("chat",os.chat.preset)," / ",Fs("code",os.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:u,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function xg(){const{ides:e}=is(),t=e.find(H=>H.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=vt(),{userName:a}=is(),[i,c]=o.useState(a||""),[l,u]=o.useState(null),[f,d]=o.useState(null),[h,m]=o.useState(os),[v,k]=o.useState(!1),[p,x]=o.useState(""),[w,b]=o.useState(""),[N,I]=o.useState("127.0.0.1"),[y,M]=o.useState(""),[S,j]=o.useState(""),[g,$]=o.useState(""),[A,L]=o.useState(""),[O,W]=o.useState(""),[P,C]=o.useState(!1),T=async()=>{const U=await(await Dt("/auth/session")).json();u(U)},V=async()=>{const U=await(await Dt("/api/v1/standalone/preferences")).json();d(U),I(U.standaloneBindHost);const Q=$t(U.standaloneFontPreferences);m(Q),Qt(Q),fa(Q)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([T(),V()]).catch(H=>{L(H instanceof Error?H.message:String(H))})},[]),o.useEffect(()=>{Qt(h)},[h]);const E=H=>{const U=H.target.value.trim();t!=null&&t.id&&U!==a&&n(t.id,"set_user_name",{userName:U}).catch(console.error)},[_,F]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),J=H=>{F(H);try{localStorage.setItem("adhdev_sound",H?"1":"0")}catch{}},xe=async()=>{x(""),b(""),k(!0);try{const H=$t(h),U=await Dt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:H})}),Q=await U.json();if(!U.ok)throw new Error((Q==null?void 0:Q.error)||"Failed to save standalone font preferences");const de=$t(Q.standaloneFontPreferences);d(Q),m(de),Qt(de),fa(de),b("Standalone chat fonts saved for this self-hosted dashboard.")}catch(H){x(H instanceof Error?H.message:String(H))}finally{k(!1)}},ce=()=>{const H=$t(f==null?void 0:f.standaloneFontPreferences);x(""),b(""),m(H),Qt(H)},te=()=>{x(""),b(""),m(os),Qt(os)},be=async()=>{L(""),W(""),C(!0);try{const H=await Dt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:N})}),U=await H.json();if(!H.ok)throw new Error((U==null?void 0:U.error)||"Failed to save standalone network preference");d(U),I(U.standaloneBindHost),W(U.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(H){L(H instanceof Error?H.message:String(H))}finally{C(!1)}},ge=async()=>{if(L(""),W(""),S.trim().length<4){L("Password must be at least 4 characters.");return}if(S!==g){L("New password and confirmation do not match.");return}C(!0);try{const H=await Dt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,newPassword:S})}),U=await H.json();if(!H.ok)throw new Error((U==null?void 0:U.error)||"Failed to save password");u(U),await V(),M(""),j(""),$(""),W(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Cl()}catch(H){L(H instanceof Error?H.message:String(H))}finally{C(!1)}},ve=async()=>{L(""),W(""),C(!0);try{const H=await Dt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,clear:!0})}),U=await H.json();if(!H.ok)throw new Error((U==null?void 0:U.error)||"Failed to clear password");u(U),await V(),M(""),j(""),$(""),W("Standalone password disabled.")}catch(H){L(H instanceof Error?H.message:String(H))}finally{C(!1)}};return s.jsxs($c,{icon:s.jsx(Xr,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(yr,{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(yr,{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(kt,{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.31"]}),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(kt,{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:()=>I("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:()=>I("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:()=>{be()},disabled:P,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:P?"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(kt,{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."}),A&&s.jsx(yr,{variant:"error",children:A}),O&&s.jsx(yr,{variant:"success",children:O}),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:H=>M(H.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:S,onChange:H=>j(H.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:H=>$(H.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{ge()},disabled:P,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:P?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{ve()},disabled:P,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(kt,{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(H=>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 ${H.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:H.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:H.type})]},H.type))})}),s.jsx(kt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(rp,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(kt,{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(ip,{})]}),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(hp,{})]}),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(hg,{value:h,savedValue:$t(f==null?void 0:f.standaloneFontPreferences),saving:v,error:p,notice:w,onChange:m,onSave:()=>{xe()},onResetToSaved:ce,onResetToDefaults:te})]}),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(gp,{})]})]})}),s.jsx(kt,{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(ep,{}),s.jsx(Jt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Zd,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:_,onChange:J})]})}),s.jsx(kt,{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($d,{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:H=>c(H.target.value),onBlur:E,onKeyDown:H=>{H.key==="Enter"&&H.currentTarget.blur()}})]})})})]})}Vf();fp();cg();const bg=Ri({baseUrl:"",getToken:Za});function gg({children:e}){const[t,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,u]=o.useState(""),[f,d]=o.useState(!1),h=async()=>{a(!0),u("");try{const k=await(await Dt("/auth/session")).json();r(k)}catch(v){u(v instanceof Error?v.message:String(v))}finally{a(!1)}};o.useEffect(()=>{h()},[]),o.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let v=!1;return(async()=>{try{const k=await Dt("/api/v1/standalone/preferences");if(!k.ok)return;const p=await k.json();if(v)return;const x=$t(p.standaloneFontPreferences);Qt(x),fa(x)}catch{}})(),()=>{v=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const m=async v=>{v.preventDefault(),d(!0),u("");try{const k=await Dt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),p=await k.json();if(!k.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),c(""),Cl()}catch(k){u(k instanceof Error?k.message:String(k))}finally{d(!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 ki(){const{ides:e,initialLoaded:t}=is();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(Gn,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Gn,{to:"/dashboard",replace:!0})}function yg(){const e=o.useMemo(()=>({sendCommand:$r,sendData:ma,sendPtyInput:Zb}),[]);return s.jsx(md,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Rd,{client:bg,children:s.jsx(gg,{children:s.jsx(rg,{children:s.jsx(Pd,{value:e,children:s.jsx(dg,{children:s.jsxs(fd,{children:[s.jsx(qt,{path:"/dashboard",element:s.jsx(Ox,{})}),s.jsx(qt,{path:"/machine",element:s.jsx(ki,{})}),s.jsx(qt,{path:"/machines/:id",element:s.jsx(Vb,{})}),s.jsx(qt,{path:"/machines",element:s.jsx(ki,{})}),s.jsx(qt,{path:"/about",element:s.jsx(pg,{})}),s.jsx(qt,{path:"/settings",element:s.jsx(xg,{})}),s.jsx(qt,{path:"*",element:s.jsx(Gn,{to:"/dashboard",replace:!0})})]})})})})})})})}uf({connectionManager:Kt});pd(document.getElementById("root")).render(s.jsx(yg,{}));
83
+ `})]})}function Za(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function Gb(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=Za();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 Dt(e,t){return await fetch(Gb(e),{credentials:"same-origin",...t})}function Cl(){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 qb{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,n){if(!r)return{success:!1,error:"sessionId is required"};const a=new URL(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`,window.location.origin);typeof(n==null?void 0:n.sinceSeq)=="number"&&a.searchParams.set("sinceSeq",String(n.sinceSeq));const i=await Dt(`${a.pathname}${a.search}`);if(!i.ok){let l=`Runtime snapshot unavailable (${i.status})`;try{const u=await i.json();u!=null&&u.error&&(l=u.error)}catch{}return{success:!1,error:l}}const c=await i.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof c.seq=="number"?c.seq:0,text:typeof c.text=="string"?c.text:"",truncated:!!c.truncated,cols:typeof c.cols=="number"?c.cols:void 0,rows:typeof c.rows=="number"?c.rows:void 0,force:!!(n!=null&&n.force)}),{success:!0}}emitRuntimeEvent(t,r){var n;(n=this.runtimeListeners.get(t))==null||n.forEach(a=>a(r))}}const Kt=new qb;function Yb(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=Za();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Ar=Yb(),wi=3e3,Xb=3e4;let Rt=null,Jb=0;const Yr=new Map;let Xt=null,Ys=null;function ji(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Ws(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function Qb(e){return e==="connected"?"connected":e}async function $r(e,t,r){const n=_c(e,r||{}),a=Rt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++Jb}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{Yr.delete(i),l(new Error(`WS command timeout: ${t}`))},3e4);Yr.set(i,{resolve:f=>{clearTimeout(u),c(f)},reject:f=>{clearTimeout(u),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 ma(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 Zb(e,t,r){const n=Rt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=_c(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 eg{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 $r(this.daemonId,t,r)}async sendInput(t,r){return $r(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Xt&&(clearInterval(Xt),Xt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await $r(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());Kt.emitScreenshot(this.daemonId,a)}}catch{}};r(),Xt=setInterval(r,2e3)}stopScreenshots(t){Xt&&(clearInterval(Xt),Xt=null)}}let It=null;function tg(e){return(!It||It.daemonId!==e)&&(It=new eg(e)),It}function sg({children:e}){const t=o.useRef(Js()),r=Js();t.current=r;const{setUserName:n}=is(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),u=o.useCallback((p,x)=>{l(p),Ys==null||Ys(p,x)},[]),f=o.useRef(null),d=o.useRef(),h=o.useRef(wi),m=o.useRef(!0),v=o.useRef(!1),k=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;u("connecting"),console.log(`[Standalone WS] Connecting to ${Ar}...`),Ws("connect_attempt",{url:Ar,reason:k.current,delayMs:h.current});let w;try{w=new WebSocket(Ar)}catch(I){console.error("[Standalone WS] Failed to create WebSocket:",I),x();return}f.current=w,w.onopen=()=>{if(!m.current){w.close();return}u("connected"),h.current=wi,Ws("open",{url:Ar,reason:k.current}),Gt.resubscribeAll({sendData:ma}),console.log("[Standalone WS] Connected")},Rt=w,w.onmessage=I=>{var y,M;try{const S=JSON.parse(I.data);if((S.type==="command_result"||S.type==="error")&&S.requestId){const j=Yr.get(S.requestId);j&&(Yr.delete(S.requestId),S.type==="error"?j.reject(new Error(((y=S.data)==null?void 0:y.message)||"Command failed")):j.resolve(S.data));return}if(S.type==="session_output"){const j=S.sessionId||S.cliId||S.cliType;j&&Kt.emitSessionOutput(j,typeof S.data=="string"?S.data:"",typeof S.seq=="number"?S.seq:void 0);return}if(S.type==="runtime_snapshot"){Kt.emitRuntimeSnapshot(S.sessionId,typeof S.text=="string"?S.text:"",typeof S.seq=="number"?S.seq:0,!!S.truncated,typeof S.cols=="number"?S.cols:void 0,typeof S.rows=="number"?S.rows:void 0);return}if(S.type==="topic_update"){const j=S.update;j&&Gt.publish(j);return}if(S.type==="status"||S.type==="initial_state"){const j=S.data;if(!j)return;const{injectEntries:g,markLoaded:$,getIdes:A}=t.current,L=j.instanceId||"standalone",O=A().find(C=>C.id===L),W=tg(L);Kt.register(L,W),Kt.setState(L,"connected"),u("connected",L),Kt.emitStatus(L,j);const P=Ur(j,{daemonId:L,existingDaemon:O,existingEntries:A()});ji("ws_status",{type:S.type,daemonId:L,sessions:(j.sessions||[]).map(C=>({id:C.id,parentId:C.parentId,providerType:C.providerType,kind:C.kind,transport:C.transport,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,title:C.title})),recentLaunches:(j.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),ji("entries",{daemonId:L,entries:P.filter(C=>C.type!=="adhdev-daemon").map(C=>({id:C.id,type:C.type,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,sessionId:C.sessionId}))}),P.length>0&&g(P,{authoritativeDaemonIds:[L]}),$(),c.current!==L&&((M=i.current)==null||M.call(i),c.current=L,i.current=Gt.subscribe({sendData:ma},L,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${L}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const T=t.current.getIdes(),V=T.find(_=>_.id===L),E=Ur(C.status,{daemonId:L,existingDaemon:V,existingEntries:T,timestamp:C.timestamp});E.length>0&&t.current.injectEntries(E,{authoritativeDaemonIds:[L]}),C.userName&&a.current&&a.current(C.userName)}))}}catch(S){console.error("[Standalone WS] Parse error:",S)}},w.onclose=I=>{m.current&&(It==null||It.stopScreenshots(),It&&Kt.setState(It.daemonId,"disconnected"),u("disconnected"),f.current=null,k.current=`close:${I.code}${I.wasClean?":clean":":unclean"}`,Ws("close",{code:I.code,reason:I.reason||"",wasClean:I.wasClean}),x())},w.onerror=I=>{v.current||!m.current||(k.current="error",Ws("error",{message:I instanceof Event?"event":String(I),readyState:w.readyState}),console.warn("[Standalone WS] Error, will reconnect:",I))}}function x(){if(!m.current)return;clearTimeout(d.current);const w=h.current;console.log(`[Standalone WS] Reconnecting in ${w}ms...`),Ws("schedule_reconnect",{reason:k.current,delayMs:w}),d.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,Xb),p()},w)}return p(),()=>{var w;m.current=!1,v.current=!0,(w=i.current)==null||w.call(i),i.current=null,c.current=null,clearTimeout(d.current),f.current&&(f.current.onerror=null,f.current.onclose=null,f.current.close(),f.current=null,Rt=null),It&&(It.stopScreenshots(),Kt.unregister(It.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function rg({children:e}){const[t,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(Ys=(c,l)=>{r(c),l&&a(l)},()=>{Ys=null}),[]);const i=o.useMemo(()=>{const c=t==="connected",l=Qb(t),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:t,isConnected:c,connectionStates:u}},[t,n]);return s.jsx(Ad,{connectionOverrides:i,children:s.jsx(sg,{children:e})})}const Il="adhdev_standalone_font_preferences",os={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},dn=[{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"}],sr=[{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"}],ng=new Set(dn.map(e=>e.id)),ag=new Set(sr.map(e=>e.id));function $t(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Br("chat",t.chat),code:Br("code",t.code),terminal:Br("terminal",t.terminal)}}function Br(e,t){const r=os[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"?ng:ag).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:a}:r}function Kr(e,t){var a;const r=Br(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?dn:sr;return((a=n.find(i=>i.id===r.preset))==null?void 0:a.family)||n[0].family}function og(e){const t=$t(e),r=Kr("chat",t.chat),n=Kr("code",t.code),a=Kr("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Qt(e,t=document.documentElement){const r=$t(e),n=og(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))t.style.setProperty(a,i);return r}function fa(e){const t=$t(e);try{localStorage.setItem(Il,JSON.stringify(t))}catch{}return t}function ig(){try{const e=localStorage.getItem(Il);if(e)return $t(JSON.parse(e))}catch{}return os}function cg(){return Qt(ig())}function Fs(e,t){var n;const r=e==="chat"?dn:sr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const lg=[{id:"dashboard",path:"/dashboard",icon:s.jsx(Di,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(cs,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:s.jsx(Xr,{}),label:"Settings"}];function dg({children:e}){const t=Ts(),r=xa(),n=o.useMemo(()=>lg.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($i,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Bi,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(qf,{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.33"]}),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 ug=[{icon:s.jsx(cs,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Ft,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Ki,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(St,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Zs,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx($i,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],mg=[{icon:s.jsx(Ud,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Di,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Jr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Bd,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Ei,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Od,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],fg=[{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 pg(){return s.jsxs($c,{icon:s.jsx(Bi,{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.33"]}),children:[s.jsx(kt,{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(kt,{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:ug.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(kt,{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:Pc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Ec.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Dc.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(kt,{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:mg.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(kt,{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:fg.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(Kc,{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(eu,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Hn(e,t,r){return{...e,[t]:r}}function Un({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:Kr(e,n)})]})]})]})}function hg({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:i,onSave:c,onResetToSaved:l,onResetToDefaults:u}){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(Un,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:dn,onChange:d=>i(Hn(e,"chat",d))}),s.jsx(Un,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:sr,onChange:d=>i(Hn(e,"code",d))}),s.jsx(Un,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:sr,onChange:d=>i(Hn(e,"terminal",d))})]}),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: ",Fs("chat",e.chat.preset)," · Code: ",Fs("code",e.code.preset)," · Terminal: ",Fs("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Fs("chat",os.chat.preset)," / ",Fs("code",os.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:u,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function xg(){const{ides:e}=is(),t=e.find(H=>H.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=vt(),{userName:a}=is(),[i,c]=o.useState(a||""),[l,u]=o.useState(null),[f,d]=o.useState(null),[h,m]=o.useState(os),[v,k]=o.useState(!1),[p,x]=o.useState(""),[w,b]=o.useState(""),[N,I]=o.useState("127.0.0.1"),[y,M]=o.useState(""),[S,j]=o.useState(""),[g,$]=o.useState(""),[A,L]=o.useState(""),[O,W]=o.useState(""),[P,C]=o.useState(!1),T=async()=>{const U=await(await Dt("/auth/session")).json();u(U)},V=async()=>{const U=await(await Dt("/api/v1/standalone/preferences")).json();d(U),I(U.standaloneBindHost);const Q=$t(U.standaloneFontPreferences);m(Q),Qt(Q),fa(Q)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([T(),V()]).catch(H=>{L(H instanceof Error?H.message:String(H))})},[]),o.useEffect(()=>{Qt(h)},[h]);const E=H=>{const U=H.target.value.trim();t!=null&&t.id&&U!==a&&n(t.id,"set_user_name",{userName:U}).catch(console.error)},[_,F]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),J=H=>{F(H);try{localStorage.setItem("adhdev_sound",H?"1":"0")}catch{}},xe=async()=>{x(""),b(""),k(!0);try{const H=$t(h),U=await Dt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:H})}),Q=await U.json();if(!U.ok)throw new Error((Q==null?void 0:Q.error)||"Failed to save standalone font preferences");const de=$t(Q.standaloneFontPreferences);d(Q),m(de),Qt(de),fa(de),b("Standalone chat fonts saved for this self-hosted dashboard.")}catch(H){x(H instanceof Error?H.message:String(H))}finally{k(!1)}},ce=()=>{const H=$t(f==null?void 0:f.standaloneFontPreferences);x(""),b(""),m(H),Qt(H)},te=()=>{x(""),b(""),m(os),Qt(os)},be=async()=>{L(""),W(""),C(!0);try{const H=await Dt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:N})}),U=await H.json();if(!H.ok)throw new Error((U==null?void 0:U.error)||"Failed to save standalone network preference");d(U),I(U.standaloneBindHost),W(U.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(H){L(H instanceof Error?H.message:String(H))}finally{C(!1)}},ge=async()=>{if(L(""),W(""),S.trim().length<4){L("Password must be at least 4 characters.");return}if(S!==g){L("New password and confirmation do not match.");return}C(!0);try{const H=await Dt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,newPassword:S})}),U=await H.json();if(!H.ok)throw new Error((U==null?void 0:U.error)||"Failed to save password");u(U),await V(),M(""),j(""),$(""),W(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Cl()}catch(H){L(H instanceof Error?H.message:String(H))}finally{C(!1)}},ve=async()=>{L(""),W(""),C(!0);try{const H=await Dt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,clear:!0})}),U=await H.json();if(!H.ok)throw new Error((U==null?void 0:U.error)||"Failed to clear password");u(U),await V(),M(""),j(""),$(""),W("Standalone password disabled.")}catch(H){L(H instanceof Error?H.message:String(H))}finally{C(!1)}};return s.jsxs($c,{icon:s.jsx(Xr,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(yr,{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(yr,{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(kt,{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.33"]}),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(kt,{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:()=>I("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:()=>I("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:()=>{be()},disabled:P,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:P?"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(kt,{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."}),A&&s.jsx(yr,{variant:"error",children:A}),O&&s.jsx(yr,{variant:"success",children:O}),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:H=>M(H.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:S,onChange:H=>j(H.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:H=>$(H.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{ge()},disabled:P,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:P?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{ve()},disabled:P,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(kt,{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(H=>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 ${H.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:H.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:H.type})]},H.type))})}),s.jsx(kt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(rp,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(kt,{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(ip,{})]}),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(hp,{})]}),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(hg,{value:h,savedValue:$t(f==null?void 0:f.standaloneFontPreferences),saving:v,error:p,notice:w,onChange:m,onSave:()=>{xe()},onResetToSaved:ce,onResetToDefaults:te})]}),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(gp,{})]})]})}),s.jsx(kt,{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(ep,{}),s.jsx(Jt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Zd,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:_,onChange:J})]})}),s.jsx(kt,{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($d,{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:H=>c(H.target.value),onBlur:E,onKeyDown:H=>{H.key==="Enter"&&H.currentTarget.blur()}})]})})})]})}Vf();fp();cg();const bg=Ri({baseUrl:"",getToken:Za});function gg({children:e}){const[t,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,u]=o.useState(""),[f,d]=o.useState(!1),h=async()=>{a(!0),u("");try{const k=await(await Dt("/auth/session")).json();r(k)}catch(v){u(v instanceof Error?v.message:String(v))}finally{a(!1)}};o.useEffect(()=>{h()},[]),o.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let v=!1;return(async()=>{try{const k=await Dt("/api/v1/standalone/preferences");if(!k.ok)return;const p=await k.json();if(v)return;const x=$t(p.standaloneFontPreferences);Qt(x),fa(x)}catch{}})(),()=>{v=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const m=async v=>{v.preventDefault(),d(!0),u("");try{const k=await Dt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),p=await k.json();if(!k.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),c(""),Cl()}catch(k){u(k instanceof Error?k.message:String(k))}finally{d(!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 ki(){const{ides:e,initialLoaded:t}=is();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(Gn,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Gn,{to:"/dashboard",replace:!0})}function yg(){const e=o.useMemo(()=>({sendCommand:$r,sendData:ma,sendPtyInput:Zb}),[]);return s.jsx(md,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Rd,{client:bg,children:s.jsx(gg,{children:s.jsx(rg,{children:s.jsx(Pd,{value:e,children:s.jsx(dg,{children:s.jsxs(fd,{children:[s.jsx(qt,{path:"/dashboard",element:s.jsx(Ox,{})}),s.jsx(qt,{path:"/machine",element:s.jsx(ki,{})}),s.jsx(qt,{path:"/machines/:id",element:s.jsx(Vb,{})}),s.jsx(qt,{path:"/machines",element:s.jsx(ki,{})}),s.jsx(qt,{path:"/about",element:s.jsx(pg,{})}),s.jsx(qt,{path:"/settings",element:s.jsx(xg,{})}),s.jsx(qt,{path:"*",element:s.jsx(Gn,{to:"/dashboard",replace:!0})})]})})})})})})})}uf({connectionManager:Kt});pd(document.getElementById("root")).render(s.jsx(yg,{}));