@adhdev/daemon-standalone 0.9.22 → 0.9.23
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 Gl=Object.defineProperty;var ql=(e,t,r)=>t in e?Gl(e,t,{enumerable:!0,config
|
|
|
28
28
|
|
|
29
29
|
`)))return}const G=(c==null?void 0:c[R.id])??p[R.id];try{const B=await v(R.invokeScript),E=fr(B);if(E&&!E.ok||pr(B))throw new Error((E==null?void 0:E.error)||Ls(B)||`Could not run ${R.label}`);E&&g(R,G??!0,E)}catch(B){D(R,G);const E=B instanceof Error?B.message:`Could not run ${R.label}`;lt.showToast(E,"warning")}};return s.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${f}33`,background:`${f}12`,color:f},children:a}),M.map(R=>{const G=String(x[R.id]||""),B=Zu(R,j,G),E=N===R.id,W=y===R.id,J=Tr(R,j),be="inline-flex h-7 max-w-full items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium transition-colors whitespace-nowrap";switch(R.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${be} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:E?`${f}55`:"var(--border-default)",background:E?`${f}10`:"var(--surface-tertiary)",color:G?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void I(R),title:R.label,children:[R.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:W?"Loading…":B||R.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),E&&J.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>T(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:R.label}),J.map(he=>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:he.value===G?`${f}14`:"transparent",color:he.value===G?"var(--text-primary)":"var(--text-secondary)",borderLeft:he.value===G?`2px solid ${f}`:"2px solid transparent"},title:he.description||he.label,onMouseEnter:de=>{de.currentTarget.style.background=`${f}10`},onMouseLeave:de=>{de.currentTarget.style.background=he.value===G?`${f}14`:"transparent"},onClick:()=>void P(R,he.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:he.label}),he.value===G&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:f},children:"✓"})]},he.value))]})]})]},R.id);case"cycle":return s.jsxs("button",{type:"button",className:`${be} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:G?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void K(R),title:`Click to cycle: ${J.map(he=>he.label).join(" → ")}`,children:[R.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:B||R.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},R.id);case"toggle":return s.jsxs("button",{type:"button",className:`${be} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:G?`${f}44`:"var(--border-default)",background:G?`${f}14`:"var(--surface-tertiary)",color:G?f:"var(--text-muted)"},onClick:()=>void V(R),"aria-pressed":!!G,children:[R.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),R.label]},R.id);case"action":return s.jsxs("button",{type:"button",className:`${be} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void L(R),children:[R.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:R.resultDisplay==="inline"&&G?`${R.label}: ${G}`:R.label})]},R.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:G?"var(--text-primary)":"var(--text-muted)"},children:[R.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:G?`${R.label}: ${G}`:R.label})]},R.id);default:return null}})]})})}function sm({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:u}){const{isVisible:f}=Bi(),d=ka(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(tm,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:d,controlValues:u})})}function rm({hasDraft:e,isBusy:t=!1}){return!e||t}const Vi=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:w,toggleVisibility:S}=Bi();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:S,"aria-label":w?"Hide controls":"Show controls","aria-pressed":w,title:w?"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 j=x.clipboardData.getData("text");j&&m(b=>b+j),x.preventDefault()},onKeyDown:x=>{if(x.key==="Enter"){if(x.nativeEvent.isComposing){x.preventDefault();return}x.preventDefault(),p()}},onBlur:x=>{if(window.innerWidth<768){const j=x.relatedTarget;if((j==null?void 0:j.tagName)==="BUTTON")return;setTimeout(()=>{document.documentElement.scrollTop=0},300)}},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:rm({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})]})}),Je=e=>e.transport==="pty",Ts=(e,t)=>Je(e)?e.mode||"terminal":"chat",Gi=(e,t)=>Je(e)&&Ts(e)==="terminal",qe=e=>e.transport==="acp";function Vt(e){return e.streamSource!=="agent-stream"}function fs(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function qi(e){return e.machineName||""}function sr(e){return fs(e)}function Kt(e){return e.agentType||""}function Hr(e){return e.hostIdeType||""}function Sa(e){return e.displayPrimary||e.agentName||"Agent"}function Yi(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function nm(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function ko(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 am(e){return ko(e==null?void 0:e.receivedAt)||ko(e==null?void 0:e.timestamp)||0}function Xi(e){const t=nm(e),r=Vs(t==null?void 0:t.content),n=am(t),a=Vs(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 om(e){return Xi(e)||e.displaySecondary||""}function Ji(e){return[e.displaySecondary,qi(e)].filter(Boolean)}function Ns(e){return e.agentName||Ze(Kt(e))}function im(e){var t,r;if(!Vt(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return Ze(Hr(e)||Kt(e))}function Qi(e){return Vt(e)?e.sessionId:e.nativeSessionId}function So(e){return Vt(e)?"native":e.tabKey}function cm(e){return e.sessionId}function lm(e,t){if(t)return Vt(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function dm(e,t){const r=Kt(e),n=Vt(e),a=Je(e)||qe(e),i=n?a?Ns(e)||(t==null?void 0:t.cliName)||Ze(Hr(e)||r):t!=null&&t.type?Ze(t.type):Ze(Hr(e)||r):Ns(e);return{isNativeConversation:n,isCli:Je(e),isAcp:qe(e),isCliTerminal:Gi(e),providerType:r,displayLabel:i,targetEntry:lm(e,t)}}function gt(e){return(typeof e=="string"?e.trim():"")||void 0}function Ht(e,t){const r=gt(t);return r?`${e}:${r}`:void 0}function zt(e,t,r){const n=Ht(t,r),a=gt(r);n&&e.push(n),a&&e.push(a)}function gs(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function Zi(e){return gt(e.providerSessionId)||gt(e.sessionId)||gt(e.tabKey)||gt(e.routeId)}function Na(e){return gs([gt(e.providerSessionId),gt(e.sessionId)])}function ws(e){const t=[];return zt(t,"provider",e.providerSessionId),zt(t,"session",e.sessionId),zt(t,"tab",e.tabKey),zt(t,"route",e.routeId),gs(t)}function um(e){const t=[];return gt(e.providerSessionId)?(zt(t,"provider",e.providerSessionId),gs(t)):gt(e.sessionId)?(zt(t,"session",e.sessionId),gs(t)):gt(e.tabKey)?(zt(t,"tab",e.tabKey),gs(t)):gt(e.routeId)?(zt(t,"route",e.routeId),gs(t)):[]}function Ca(e){return Ht("provider",e.providerSessionId)||Ht("session",e.sessionId)||Ht("tab",e.tabKey)||Ht("route",e.routeId)||"unknown:"}function rr(e){return Na(e)[0]}function mm(e){const t=gt(e.providerSessionId),r=gt(e.sessionId),n=gt(e.tabKey),a=gt(e.routeId),i=[Ht("provider",t),Ht("session",r),Ht("tab",n),Ht("route",a)].filter(u=>typeof u=="string"),c=ws({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),l=Ca({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:Zi({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:rr({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function Zn(e,t){const r=mm(e);return um(t).some(n=>r.lookupKeys.includes(n))}function No(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function es(e){const t=[...e.messages].reverse().find(a=>!(a!=null&&a._localId))||e.messages[e.messages.length-1],r=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,n=No(t==null?void 0:t.receivedAt)||No(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function ea(e,t=0){return es(e)||e.lastUpdated||t||0}function ec(e){return es(e)||e.lastUpdated||0}function tc(e,t,r=ec){const n=r(t)-r(e);if(n!==0)return n;const a=(e.machineName||"").localeCompare(t.machineName||"");if(a!==0)return a;const i=e.displayPrimary.localeCompare(t.displayPrimary);if(i!==0)return i;const c=e.displaySecondary.localeCompare(t.displaySecondary);return c!==0?c:e.tabKey.localeCompare(t.tabKey)}function ta(e){var r;const t=bt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function fm(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!ta(e)&&!e.title.trim()}function pm(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(ta(r))-Number(ta(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:tc(t,r)})[0]||null}function _t(e,t){const r=e.filter(c=>c.routeId===t);if(r.length===0)return null;const n=r.find(c=>c.streamSource==="native")||null,a=r.filter(c=>c.streamSource==="agent-stream"),i=pm(a);return n?i&&fm(n)?i:n:i||r[0]||null}function Gt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Ia(e){return rr(e)||e.tabKey||e.routeId||null}function sc(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"";if(t)return t;const r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"";if(r)return r;const n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"";if(!n)return null;const a=_t(e.conversations,n)||e.conversations.find(i=>i.routeId===n);return a?Ia(a):null}function rc({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=As(),c=fs(e),l=qi(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=Ns(e),m=im(e),w=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),S=o.useCallback(()=>{if(r){r();return}const p=Ia(e);p&&i(Gt(p))},[e,i,r]);return s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[u&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:S,title:m,children:[s.jsx(Ct,{size:12}),s.jsx("span",{children:m})]}):s.jsxs("span",{className:"conversation-meta-chip",title:m,children:[s.jsx(Ct,{size:12}),s.jsx("span",{children:m})]})),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(Ys,{size:12}),s.jsx("span",{children:h})]}),d&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(Ys,{size:12}),s.jsx("span",{children:h})]}),l&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:w,title:l,children:[s.jsx(ls,{size:12}),s.jsx("span",{children:l})]}):s.jsxs("span",{className:"conversation-meta-chip",title:l,children:[s.jsx(ls,{size:12}),s.jsx("span",{children:l})]}))]})}function xn(e,t){return`${e}:${t}`}function hm(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function hr(e,t){hm()&&console.debug(`[subscription-manager] ${e}`,t)}class xm{constructor(){Ge(this,"active",new Map)}subscribe(t,r,n,a){var f;const i=xn(n.topic,n.key),c=this.active.get(i);let l=!0;if(c)c.handlers.add(a),c.lastUpdate&&a(c.lastUpdate);else{const d={daemonId:r,request:n,handlers:new Set([a])};this.active.set(i,d),hr("subscribe",{daemonId:r,topic:n.topic,key:n.key}),l=((f=t.sendData)==null?void 0:f.call(t,r,n))??!1}const u=()=>{var m;const d=this.active.get(i);if(!d||(d.handlers.delete(a),d.handlers.size>0))return;this.active.delete(i);const h={type:"unsubscribe",topic:n.topic,key:n.key};hr("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(m=t.sendData)==null||m.call(t,r,h)};return u.initialSendAccepted=l,u}publish(t){const r=xn(t.topic,t.key),n=this.active.get(r);n&&(n.lastUpdate=t,ks.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.publish",topic:t.topic,payload:{key:t.key}}),n.handlers.forEach(a=>{a(t),ks.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.handler_invoked",topic:t.topic,payload:{key:t.key}})}))}updateParams(t,r,n){const a=xn(t,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(t){var r;hr("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);hr("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)}}const qt=new xm;function bm(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 gm(e){const t=[],r=new Map;for(const n of e)if(n.parentId){const a=r.get(n.parentId)||[];a.push(n),r.set(n.parentId,a)}else t.push(n);return{topLevel:t,childrenByParent:r}}function Fr(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:i,timestamp:c}=t,l=c||e.timestamp||Date.now(),u=e.sessions||[],{topLevel:f,childrenByParent:d}=gm(u),h=bm(i,n),m=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,w=f.filter(x=>x.kind==="workspace"&&x.transport==="cdp-page"),S=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},cdpConnected:w.some(x=>!!x.cdpConnected)});for(const x of w){const j=h.get(x.id),b=Bs(x,j),N=(d.get(x.id)||[]).map(T=>Bs(T,h.get(T.id)));r.push({id:`${n}:ide:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,status:b.cdpConnected?"online":"detected",daemonId:n,instanceId:x.id,workspace:b.workspace,terminals:0,childSessions:N,agents:N.map(T=>({id:T.id,name:T.providerName||T.providerType,type:T.providerType,status:T.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 S){const j=h.get(x.id),b=Bs(x,j);r.push({id:`${n}:cli:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,agentType:b.providerType,status:b.status||"running",daemonId:n,instanceId:x.id,cliName:b.providerName||b.providerType,mode:b.mode||(j==null?void 0:j.mode)||"terminal",workspace:b.workspace||"",activeChat:b.activeChat,...b.resume!==void 0&&{resume:b.resume},...b.runtimeKey!==void 0&&{runtimeKey:b.runtimeKey},...b.runtimeDisplayName!==void 0&&{runtimeDisplayName:b.runtimeDisplayName},...b.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:b.runtimeWorkspaceLabel},...b.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:b.runtimeWriteOwner},...b.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:b.runtimeAttachedClients},...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l,_isCli:!0})}for(const x of p){const j=h.get(x.id),b=Bs(x,j);r.push({id:`${n}:acp:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,agentType:b.providerType,status:b.status||"running",daemonId:n,instanceId: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 ym=15e3,vm=15e3,wm=6e4,jm=1200,Co=12,km=8e3,Sm=4e3,bn=new Map,gn=new Map,xr=new Set,Ws=new Map;function Nm(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 Io(e,t){const r=Ws.get(e);!r||r.size===0||(Ws.delete(e),r.forEach(n=>n(t)))}function Cm(e,t){return new Promise(r=>{const n=Ws.get(e)||new Set;Ws.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&Ws.delete(e),r(c)},i=setTimeout(()=>a(!1),t);n.add(a)})}function nr(){const{sendCommand:e,sendData:t}=jt(),{injectEntries:r,getIdes:n}=Gs();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??wm,l=gn.get(a)||0;if(!(i!=null&&i.force)&&xr.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const u=bn.get(a);if(u)return u;const f=(async()=>{if(t&&!xr.has(a)){const p=qt.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},x=>{const j=n(),b=j.find(T=>T.id===a),N=Fr(x.status,{daemonId:a,existingDaemon:b,existingEntries:j,timestamp:x.timestamp});N.length>0&&r(N),gn.set(a,Date.now()),Io(a,!0)});if(p.initialSendAccepted?xr.add(a):xr.delete(a),!(i!=null&&i.force)&&p.initialSendAccepted&&await Cm(a,jm))return}const d=await e(a,"get_status_metadata"),h=Nm(d);if(!h)return;const m=n(),w=m.find(p=>p.id===a),S=Fr(h,{daemonId:a,existingDaemon:w,existingEntries:m,timestamp:h.timestamp||Date.now()});S.length>0&&r(S,{authoritativeDaemonIds:[a]}),gn.set(a,Date.now()),Io(a,!0)})().finally(()=>{bn.delete(a)});return bn.set(a,f),f},[n,r,e,t])}function Im(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:Je(e)||qe(e)?{agentType:Kt(e)}:e.streamSource==="agent-stream"?{agentType:Kt(e)}:t}function Js(e){return e?sr(e):""}function Rs(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function Aa(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function Am(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 Mm=60,Tm=1e3;function nc(e={}){return e.isCliLike?Tm:Mm}function Lm(e={}){return nc(e)}const ar=60,Rm=1e3,Ma=12e4,Pm=new Set(["generating","waiting_approval","starting","streaming","working"]),Ao=new Map;function ac(e,t){return`${e}::${t}`}function sa(e=ar){return{liveMessages:[],cursor:oc([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function ra(e){return ji(e)}function oc(e,t=ar){return{knownMessageCount:e.length,lastMessageSignature:ra(e[e.length-1]),tailLimit:t}}function br(e,t){const r=e[e.length-1];if(!r)return"empty:";let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return["",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function _m(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 Dm{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);Ge(this,"pendingSubscribeRetryTimer",null);this.manager=t.manager||qt,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.snapshot=sa(Math.max(0,t.tailLimit??ar))}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=oc(n,this.snapshot.cursor.tailLimit);br(this.snapshot.liveMessages)===br(n)&&this.snapshot.cursor.knownMessageCount===a.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===a.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:n,cursor:a},this.emit())}subscribe(t){return this.listeners.add(t),t(this.snapshot),()=>{this.listeners.delete(t)}}retain(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),!(this.retainCount!==0||this.pendingDisconnectTimer)&&(this.pendingDisconnectTimer=setTimeout(()=>{this.pendingDisconnectTimer=null,this.retainCount===0&&this.disconnect()},0))}async loadHistoryPage(t){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=await t(),a=Array.isArray(n.messages)?n.messages:[];this.snapshot={...this.snapshot,historyMessages:[...a,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+a.length,hasMoreHistory:n.hasMore===!0,historyError:null}}catch(n){this.snapshot={...this.snapshot,historyError:n instanceof Error?n.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=r,r}buildSubscribeRequest(){return{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},knownMessageCount:this.snapshot.cursor.knownMessageCount,lastMessageSignature:this.snapshot.cursor.lastMessageSignature,...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{}}}}clearPendingSubscribeRetry(){this.pendingSubscribeRetryTimer&&(clearTimeout(this.pendingSubscribeRetryTimer),this.pendingSubscribeRetryTimer=null)}scheduleSubscribeRetry(){this.pendingSubscribeRetryTimer||!this.sendData||!this.daemonId||!this.sessionId||this.retainCount===0||(this.pendingSubscribeRetryTimer=setTimeout(()=>{if(this.pendingSubscribeRetryTimer=null,!this.sendData||!this.daemonId||!this.sessionId||this.retainCount===0)return;this.sendData(this.daemonId,this.buildSubscribeRequest())||this.scheduleSubscribeRetry()},Rm))}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)}),this.transportSubscription.initialSendAccepted||this.scheduleSubscribeRetry())}disconnect(){var t;this.clearPendingSubscribeRetry(),(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){this.clearPendingSubscribeRetry();const r=typeof t.lastMessageSignature=="string"?t.lastMessageSignature:"",n=ra(this.snapshot.liveMessages[this.snapshot.liveMessages.length-1]);if(t.syncMode!=="full"&&r&&n===r){const 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=_m(this.snapshot.liveMessages,t),i={knownMessageCount:a.length,lastMessageSignature:typeof t.lastMessageSignature=="string"?t.lastMessageSignature:ra(a[a.length-1]),tailLimit:this.snapshot.cursor.tailLimit};br(this.snapshot.liveMessages)===br(a)&&this.snapshot.cursor.knownMessageCount===i.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===i.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:a,cursor:i},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:i.knownMessageCount,lastMessageSignature:i.lastMessageSignature}),this.emit())}}function ic(e){const t=ac(e.daemonId,e.sessionId),r=Ao.get(t);if(r)return r.updateOptions(e),r;const n=new Dm(e);return Ao.set(t,n),n}function Em(e,t){return{...e,loadHistoryPage:t}}function $m(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function Bm(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(Pm.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??Ma)),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 Km(e=Ma){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Om(e,t={}){const r=new Set,n=[];for(const a of e){if(!Bm(a,t))continue;const i=sr(a),c=a.sessionId||"";if(!i||!c)continue;const l=ac(i,c);if(r.has(l))continue;r.add(l);const u=rr(a);n.push({daemonId:i,sessionId:c,historySessionId:u||c,subscriptionKey:`daemon:${i}:session:${c}`})}return n.sort($m),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Wm(e,t){const{sendData:r,sendCommand:n}=jt(),a=(t==null?void 0:t.enabled)!==!1,i=sr(e),c=e.sessionId||"",l=rr(e)||c,u=`daemon:${i}:session:${c}`,f=Math.max(0,(t==null?void 0:t.tailLimit)??ar),d=o.useMemo(()=>!a||!i||!c?null:ic({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())||sa(f));o.useEffect(()=>{if(!d){m(sa(f));return}d.retain(),m(d.getSnapshot());const S=d.subscribe(p=>{m(p)});return()=>{S(),d.release()}},[d,f]),o.useEffect(()=>{d&&(d.hydrateLiveMessages(e.messages),m(d.getSnapshot()))},[e.messages,d]);const w=o.useCallback(async()=>{!d||!i||!c||await d.loadHistoryPage(async()=>{const S=e.agentType,p=await n(i,"chat_history",{agentType:S,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(()=>Em(h,w),[w,h])}function Hm(e,t){const{sendData:r}=jt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??ar),i=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Ma)),c=Km(i),[l,u]=o.useState(0);o.useEffect(()=>{if(!n||e.length===0)return;const d=setInterval(()=>{u(h=>h+1)},c);return()=>{clearInterval(d)}},[e.length,n,c]);const f=o.useMemo(()=>Om(e,{recentActivityMs:i}),[e,i,l]);o.useEffect(()=>{if(!n||!r||f.descriptors.length===0)return;const d=f.descriptors.map(h=>ic({...h,sendData:r,tailLimit:a}));return d.forEach(h=>h.retain()),()=>{d.forEach(h=>h.release())}},[f.signature,n,r,a])}function Fm(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function Um(e){return Fm(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const zm=60;function na({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 ye,ge,ve,z,F;const w=o.useRef(new Map),S=nr();tr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const p=St.useMemo(()=>Ms(e),[e.status,e.connectionState]),x=o.useMemo(()=>dm(e,t),[e,t]),j=o.useMemo(()=>{var Q;return ka((Q=x.targetEntry)==null?void 0:Q.providerControls,{hostIdeType:e.hostIdeType,providerType:x.providerType})},[e.hostIdeType,x.providerType,(ye=x.targetEntry)==null?void 0:ye.providerControls]),b=nc({isCliLike:x.isCli||x.isAcp}),N=Lm({isCliLike:x.isCli||x.isAcp}),T=Wm(e,{enabled:m&&!!e.sessionId,tailLimit:N}),[y,C]=o.useState(b),k=e.tabKey,v=T.historyMessages,g=T.hasMoreHistory,D=T.historyError,M=T.liveMessages.length>0?T.liveMessages:e.messages;o.useEffect(()=>{C(b)},[b,k]);const I=Math.max(0,M.length-y),P=Sa(e),K=sr(e),V=Um(e),L=Aa(e),R=a||L,G=!!L,[B,E]=o.useState(!1);o.useEffect(()=>{const Q=x.targetEntry;K&&(!Q||Q.providerControls===void 0||Q.controlValues===void 0)&&S(K,{minFreshMs:3e4}).catch(()=>{})},[K,x.isAcp,(ge=x.targetEntry)==null?void 0:ge.providerControls,(ve=x.targetEntry)==null?void 0:ve.controlValues,S]);const W=o.useCallback(async()=>{if(!B){if(M.length>y){C(Q=>Math.min(M.length,Q+zm));return}E(!0);try{await T.loadHistoryPage()}finally{E(!1)}}},[T,B,M.length,y]),{allMessages:J,receivedAtMap:be}=o.useMemo(()=>{const Q=I>0?M.slice(-y):M,ue=v.length===0?Q:[...v,...Q],te={};return ue.forEach((fe,ne)=>{const xe=`${e.tabKey}:${Kr(fe,ne)}`;let re=Im(fe)||w.current.get(xe)||0;re||(re=Date.now(),w.current.set(xe,re)),te[Kr(fe,ne)]=re}),{allMessages:ue,receivedAtMap:te}},[e.tabKey,I,v,M,y]),he=o.useMemo(()=>l.filter(Q=>Q.routeId===e.tabKey).sort((Q,ue)=>Q.timestamp-ue.timestamp),[l,e.tabKey]),de=o.useMemo(()=>{if(M.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[s.jsx("div",{className:"connecting-logo-float",children:s.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),s.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[s.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",s.jsx("span",{className:"connecting-dots"})]}),s.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((p.isGenerating||e.status==="streaming")&&E(!1),e.status==="not_monitored"&&V)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(Ys,{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(Ss,{size:14})," Open ",P," 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"&&V)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(Ii,{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(Ss,{size:14})," Open ",P," 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"&&!B)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,V,i,c,B,M.length,P,p.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[f&&s.jsx(rc,{conversation:e,className:"chat-pane-meta-row"}),s.jsx(ru,{messages:J,actionLogs:he,agentName:Ns(e)||P||"Agent",userName:u,isCliMode:x.isCli||x.isAcp,isWorking:p.isGenerating,contextKey:e.tabKey,receivedAtMap:be,onLoadMore:W,isLoadingMore:B,hasMoreHistory:g,hiddenLiveCount:I,loadError:D??void 0,emptyState:de,scrollToBottomRequestNonce:d,isVisible:m}),s.jsx(sm,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:x.providerType,displayLabel:x.displayLabel,controls:(z=x.targetEntry)==null?void 0:z.providerControls,controlValues:(F=x.targetEntry)==null?void 0:F.controlValues,isActive:h,isCliTerminal:x.isCliTerminal}),!x.isCliTerminal&&s.jsx(Vi,{contextKey:e.tabKey,panelLabel:P,isSending:n,isBusy:G,statusMessage:R,onSend:r,isActive:h,showControlsToggle:j.length>0})]})}let cc=cs;function lc(){return cc()}class Vm{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 dc=new Vm;class Gm{sendPtyInput(t,r,n){return!1}retryConnection(t){}getState(t){return"disconnected"}sendData(t,r){return!1}get(t){}onScreenshot(t,r){return()=>{}}onRuntimeEvent(t,r,n){return()=>{}}requestRuntimeSnapshot(t,r){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let at=new Gm;function qm(e){e.dashboardWS&&(dc=e.dashboardWS),e.connectionManager&&(at=e.connectionManager),e.useDaemonsHook&&(cc=e.useDaemonsHook)}const Ym=.5,Xm=1.25;function tt(e){return Sa(e)}function us(e){return Ji(e).join(" · ")}function uc(e){const t=Xi(e);return t||(e.title?e.title:us(e)||"No messages yet")}function mc(e,t){const{isReconnecting:r,isConnecting:n}=Ms(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function Jm(e,t){const r=["Chat",...Ji(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function ts(e){return mc(e)||us(e)}function Qm(e){return`${tt(e)} · ${uc(e)}`}function Zm(e){const t=Hr(e),r=t?Ze(t):Ns(e);return`${tt(e)} — ${r||"Agent"}`}function ef(e){return Ns(e)||"CLI"}function fc(e){return Yi(e)}function pc(e){return e?`Remote · ${tt(e)||e.workspaceName||"Session"}`:"Remote"}function tf({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0,isInputActive:l=!0}){var oe;cs();const{sendPtyInput:u}=jt(),[f,d]=o.useState(!1),h=o.useRef(!1);h.current=f;const[m,w]=o.useState("Runtime terminal unavailable"),[S,p]=o.useState(1),[x,j]=o.useState({width:0,height:0}),[b,N]=o.useState({width:0,height:0}),T=o.useRef(null),y=o.useRef(null),C=o.useRef(!1),k=o.useRef(!1),v=o.useRef(0),g=o.useRef(!1),D=o.useRef(""),M=o.useRef(null),I=o.useRef(!1),P=o.useRef(null),K=32*1024,V=()=>{var Y,X,ae,A;return((X=(Y=T.current)==null?void 0:Y.ownerDocument)==null?void 0:X.defaultView)||((A=(ae=y.current)==null?void 0:ae.ownerDocument)==null?void 0:A.defaultView)||window},L=Y=>{const X=V();return{ownerWindow:X,frameId:X.requestAnimationFrame(Y)}},R=()=>{const Y=P.current;if(Y){try{Y.ownerWindow.cancelAnimationFrame(Y.frameId)}catch{}P.current=null}},G=()=>{c&&P.current===null&&(P.current=L(()=>{ne()}))},B=e.tabKey,E=e.sessionId||"",W=e.daemonId||((oe=e.routeId)==null?void 0:oe.split(":")[0])||e.routeId||"",J=Aa(e),be=f?i||J:m,he=Ym,de=Xm,ye=.05,ge=()=>{const Y=b.width,X=b.height;if(!Number.isFinite(x.width)||x.width<=0||!Number.isFinite(x.height)||x.height<=0||!Number.isFinite(Y)||Y<=0||!Number.isFinite(X)||X<=0)return 1;const ae=x.width/Y,A=x.height/X;return Number(Math.min(de,Math.max(he,Math.min(ae,A))).toFixed(2))},ve=ge(),z=C.current&&S>ve,F=Number.isFinite(b.width)&&b.width>0?Math.max(x.width,Math.round(b.width*S)):x.width,Q=Number.isFinite(b.height)&&b.height>0?Math.max(x.height,Math.round(b.height*S)):x.height,ue=()=>{L(()=>{const Y=y.current;Y&&(Y.scrollLeft=0,Y.scrollTop=Y.scrollHeight-Y.clientHeight)})},te=()=>{var Y,X;v.current=0,g.current=!1,D.current="",M.current=null,I.current=!1,C.current||(k.current=!1,p(1)),P.current!==null&&R(),d(!1),w("Runtime terminal unavailable"),(X=(Y=r.current)==null?void 0:Y.reset)==null||X.call(Y)},fe=()=>{var Y,X;v.current=0,g.current=!1,D.current="",M.current=null,I.current=!1,P.current!==null&&R(),d(!0),w(""),(X=(Y=r.current)==null?void 0:Y.reset)==null||X.call(Y)},ne=()=>{var ae;if(P.current=null,!c)return;const Y=D.current;if(!Y)return;const X=Y.slice(0,K);D.current=Y.slice(X.length),(ae=r.current)==null||ae.write(X),D.current.length>0&&G()},xe=Y=>{Y&&(D.current+=Y,G())},re=(Y,X=0,ae,A)=>{var H,ce,me,we;X>0&&v.current>=X||X===0&&g.current||(v.current=X,d(!0),w(""),typeof ae=="number"&&typeof A=="number"&&ae>0&&A>0&&((ce=(H=r.current)==null?void 0:H.resize)==null||ce.call(H,ae,A)),D.current="",(we=(me=r.current)==null?void 0:me.reset)==null||we.call(me),Y&&xe(Y))};o.useEffect(()=>{te()},[E]),o.useEffect(()=>{var X;if(!E)return;const Y=((X=at.onRuntimeEvent)==null?void 0:X.call(at,E,ae=>{if(!(!ae||ae.sessionId!==E)){if(ae.type==="runtime_snapshot"){if(!c){M.current={text:ae.text||"",seq:ae.seq||0,cols:ae.cols,rows:ae.rows};return}re(ae.text||"",ae.seq||0,ae.cols,ae.rows);return}if(ae.type==="session_output"){g.current=!0,typeof ae.seq=="number"&&(v.current=Math.max(v.current,ae.seq)),h.current||d(!0),h.current||w(""),typeof ae.data=="string"&&xe(ae.data);return}if(ae.type==="session_cleared"){if(!c){I.current=!0,D.current="",M.current=null;return}fe();return}if(ae.type==="session_io_error"){const A=typeof ae.error=="string"&&ae.error?ae.error:typeof ae.reason=="string"&&ae.reason?ae.reason:"unknown error";d(!1),w(`Runtime input failed: ${A}`);return}}},W))||(()=>{});return()=>{Y()}},[W,E,r,c]);const le=async()=>{var Y;if(!(!W||!E)){w("Loading runtime terminal...");try{const X=await((Y=at.requestRuntimeSnapshot)==null?void 0:Y.call(at,W,E));X&&X.success===!1&&(d(!1),w(`Runtime terminal unavailable: ${X.error}`))}catch(X){d(!1),w(`Runtime terminal unavailable: ${(X==null?void 0:X.message)||String(X)}`)}}};return o.useEffect(()=>{var X,ae;if(!E)return;W&&((X=at.getState)==null?void 0:X.call(at,W))==="connected"&&le();const Y=(ae=at.onStateChange)==null?void 0:ae.call(at,(A,H)=>{A!==W||H!=="connected"||le()});return()=>{Y==null||Y()}},[W,E,r]),o.useEffect(()=>{t&&te()},[t,B,r]),o.useEffect(()=>{var A,H;const Y=T.current,X=(H=(A=Y==null?void 0:Y.ownerDocument)==null?void 0:A.defaultView)==null?void 0:H.ResizeObserver;if(!Y||!X)return;const ae=new X(ce=>{const me=ce[0];if(!me)return;const{width:we,height:_e}=me.contentRect;j(Ae=>{const Ke=Math.round(we),Fe=Math.round(_e);return Ae.width===Ke&&Ae.height===Fe?Ae:{width:Ke,height:Fe}})});return ae.observe(Y),()=>ae.disconnect()},[]),o.useEffect(()=>{if(C.current)return;const Y=ge();!Number.isFinite(Y)||Y<=0||p(X=>k.current?Y<X-ye?Y:X:(k.current=!0,Y))},[b.height,b.width,x.height,x.width]),o.useEffect(()=>{z&&ue()},[z,Q,F]),o.useEffect(()=>{var X;if(!c)return;I.current&&(I.current=!1,fe());const Y=M.current;Y&&(M.current=null,re(Y.text,Y.seq,Y.cols,Y.rows)),W&&E&&((X=at.getState)==null?void 0:X.call(at,W))==="connected"&&le(),D.current&&P.current===null&&G(),L(()=>{var ae;(ae=r.current)==null||ae.bumpResize()})},[W,c,E]),o.useEffect(()=>()=>{P.current!==null&&R()},[]),o.useEffect(()=>{const Y=A=>{var ce;const H=A.detail;H!=null&&H.sessionId&&H.sessionId!==E||f&&((ce=r.current)==null||ce.bumpResize())},X=V(),ae=X===window?[window]:[window,X];for(const A of ae)A.addEventListener("adhdev:fit-cli-terminal",Y);return()=>{for(const A of ae)A.removeEventListener("adhdev:fit-cli-terminal",Y)}},[f,E,r]),s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:T,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{C.current=!0,p(Y=>{const X=Math.max(ve,Number((Y-.1).toFixed(2)));return X>ve&&ue(),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:()=>{C.current=!0,p(Y=>{const X=Math.min(de,Number((Y+.1).toFixed(2)));return X>ve&&ue(),X})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:y,className:z?"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:F>0?`${F}px`:"100%",height:Q>0?`${Q}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:b.width>0?`${b.width}px`:"100%",height:b.height>0?`${b.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:S},children:s.jsx(_i,{ref:r,readOnly:!f||!c,sizingMode:"measured",onViewportMetrics:N,onInput:Y=>{!f||(u==null||u(W,E,Y))}})})})}),!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(Vi,{contextKey:e.tabKey,panelLabel:tt(e),isSending:a,isBusy:!f||!!J,statusMessage:be,onSend:async Y=>!f||J?!1:n(Y),isActive:l&&c,showControlsToggle:!1,animateVisibility:!1})]})}const sf=2500;function rf(e){return e==="disconnected"||e==="reconnecting"}function nf({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=sf}){const i=rf(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 j=setTimeout(()=>{u.current=!0,l(!0)},a);return()=>clearTimeout(j)},[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))"},w={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},S={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},p="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",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:w[h],color:S[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",children:[e==="offline"&&"Network offline — waiting for connection...",e==="disconnected"&&"Reconnecting to server...",e==="reconnecting"&&"Reconnecting to server...",e==="auth_failed"&&(r?s.jsxs(s.Fragment,{children:["Session expired."," ",s.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — refresh the page or try again shortly.")]}),n&&e!=="auth_failed"&&s.jsx("button",{type:"button",className:"ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:n,disabled:e==="offline",children:"Reconnect now"})]})}),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 af({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 Ta({mode:e,onChange:t,compact:r=!1}){const n=r?14:15;return s.jsx("button",{type:"button",onClick:()=>t(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:e==="chat"?"Switch to Terminal view":"Switch to Chat view",children:e==="chat"?s.jsx(ga,{size:n}):s.jsx(Ft,{size:n})})}const $t="New session",hc="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 of({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 Mo({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function To({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=Jr(e.updatedAt),l=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${l?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",c].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[l?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick: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 cf({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:w,inboxOpen:S,onInboxOpenChange:p,hiddenOpen:x,onHiddenOpenChange:j,onOpenNewSession:b,actionShortcuts:N,notifications:T,notificationUnreadCount:y,onOpenNotification:C,onMarkNotificationRead:k,onMarkNotificationUnread:v,onDeleteNotification:g}){const{ides:D,p2pStates:M={}}=cs(),I=!!e&&Je(e)&&!qe(e),P=!!e&&qe(e),K=l||(e?Gi(e)?"terminal":"chat":null),[V,L]=o.useState(!1),R=o.useRef(null),G=o.useRef(null),B=D.filter(z=>z.type==="adhdev-daemon"),E=of({wsStatus:t,isConnected:r,daemonCount:B.length,p2pStates:M}),W=E.subtitle,J=E.tone==="connected"?"#22c55e":E.tone==="limited"?"#eab308":"#ef4444",be=E.tone==="connected"?"0 0 4px #22c55e80":E.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",he=o.useMemo(()=>T.filter(z=>!z.readAt),[T]),de=o.useMemo(()=>T.filter(z=>!!z.readAt),[T]),ye=o.useMemo(()=>he.slice(0,9),[he]),ge=y;o.useEffect(()=>{if(!S)return;const z=F=>{var Q;(Q=R.current)!=null&&Q.contains(F.target)||p(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[S,p]),o.useEffect(()=>{if(!x)return;const z=F=>{var Q;(Q=G.current)!=null&&Q.contains(F.target)||j(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[x,j]),o.useEffect(()=>{if(!x&&!S)return;const z=F=>{if(!F.altKey)return;const Q=F.code.match(/^Digit([1-9])$/);if(!Q)return;const ue=Number(Q[1])-1,te=x?d[ue]:void 0,fe=S?ye[ue]:void 0;if(!(!te&&!fe)){if(F.preventDefault(),F.stopPropagation(),te){h==null||h(te),j(!1);return}fe&&(C(fe),p(!1))}};return window.addEventListener("keydown",z,!0),()=>window.removeEventListener("keydown",z,!0)},[d,x,S,ye,j,p,C,h]);const ve=z=>{if(!z)return;const F=n.find(Q=>Q.tabKey===z);F&&(f==null||f(F))};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?tt(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:be}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[s.jsx("span",{title:E.title,className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:J,boxShadow:be}}),W&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",W]}),b&&s.jsx("button",{type:"button",onClick:b,className:"btn btn-secondary btn-sm ml-2",title:$t,"aria-label":$t,children:s.jsx(Ti,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(I||P||!qe(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:us(e)||tt(e),children:tt(e)}),(I||P)&&c&&s.jsxs(s.Fragment,{children:[I&&u&&K&&s.jsx(Ta,{mode:K,onChange:u,compact:!0}),s.jsx("button",{onClick:()=>c(e),className:"btn btn-secondary btn-sm",title:P?"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(wt,{size:14})})]}),!qe(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(ba,{size:14})}),!I&&!qe(e)&&s.jsx("button",{onClick:i,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(Ct,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:R,children:[s.jsxs("div",{className:`dashboard-header-hidden${V?" is-drop-target":""}`,ref:G,onDragEnter:z=>{z.dataTransfer.types.includes("text/tab-key")&&(z.preventDefault(),L(!0))},onDragOver:z=>{z.dataTransfer.types.includes("text/tab-key")&&(z.preventDefault(),z.dataTransfer.dropEffect="move",L(!0))},onDragLeave:z=>{z.currentTarget.contains(z.relatedTarget)||L(!1)},onDrop:z=>{const F=z.dataTransfer.getData("text/tab-key");z.preventDefault(),L(!1),ve(F)},children:[s.jsxs("button",{type:"button",onClick:()=>j(!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(Ai,{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(Mo,{value:N==null?void 0:N.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[w&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:w,children:"Reset panels"}),d.length>0&&m&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{m(),j(!1)},children:"Restore all"})]})]}),e&&f&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>f(e),children:[s.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[s.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),s.jsx(Mo,{value:N==null?void 0:N.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:tt(e)})]}),d.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:d.map(z=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{h==null||h(z),j(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:tt(z)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[d.indexOf(z)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",d.indexOf(z)+1]}):null,us(z)]})]},z.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>p(!S),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(Xr,{size:16}),ge>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:ge})]}),S&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[he.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),he.map(z=>s.jsx(To,{notification:z,shortcutIndex:ye.indexOf(z)>=0?ye.indexOf(z)+1:void 0,onOpen:()=>C(z),onMarkRead:()=>k(z.id),onMarkUnread:()=>v(z.id),onDelete:()=>g(z.id)},z.id))]}),de.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),de.map(z=>s.jsx(To,{notification:z,onOpen:()=>C(z),onMarkRead:()=>k(z.id),onMarkUnread:()=>v(z.id),onDelete:()=>g(z.id)},z.id))]}),T.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function ht(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function lf(e,t){return String(e||"")!==String(t||"")}function df(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&&!Wi(c.summaryMetadata).map(u=>u.toLowerCase()).join(`
|
|
31
|
-
`).includes(a)))}function uf(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 xc(e,t={}){return uf(df(e,t),t.sortMode||"recent")}function Ur(e){return e?"Resume saved history":"Start fresh"}function La(e){return e?"Resuming saved history…":"Starting fresh…"}function mf(){return"Start fresh"}function bc(e,t=!1){return e==="cli"?Ur(t):e==="ide"?"Start IDE":"Start ACP session"}function gc(e,t=!1){return e==="cli"?La(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function ff(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function pf(){return"Open saved history"}function hf(){return"Saved History"}function Ra(){return"Use saved history when you want continuity in the same provider conversation."}function xf(){return"No saved history found yet."}function bf(){return"Refresh saved history"}function gf(){return"Refreshing saved history…"}function ss(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function rs(e){return e==="start-fresh"?"Review the provider and target folder before starting fresh.":e==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Cs(e){return e==="start-fresh"?"Start fresh":"Restart"}function Is(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Pa(e){return`Resume saved history with ${e}?`}function _a(){return"Review or change the target workspace before resuming saved history."}function yf(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 Da({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:w}){var v;const S=t.find(g=>g.id===e.routeId),p=(S==null?void 0:S.chats)||[],x=(v=S==null?void 0:S.activeChat)==null?void 0:v.id,j=Je(e)&&!qe(e),[b,N]=o.useState(()=>ht()),T=l||b,y=g=>{if(u){u(g);return}N(g)},C=o.useMemo(()=>xc(a,{textQuery:T.textQuery,workspaceQuery:T.workspaceQuery,modelQuery:T.modelQuery,resumableOnly:T.resumableOnly,sortMode:T.sortMode}),[T.modelQuery,T.resumableOnly,T.sortMode,T.textQuery,T.workspaceQuery,a]),k=s.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:f,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:j?hf():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Zm(e)}),j&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Ra()})]}),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(wt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!j&&s.jsx("button",{onClick: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"}),j?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:T.textQuery,onChange:g=>y({...T,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:T.workspaceQuery,onChange:g=>y({...T,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:T.modelQuery,onChange:g=>y({...T,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:T.sortMode,onChange:g=>y({...T,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:T.resumableOnly,onChange:g=>y({...T,resumableOnly:g.target.checked})}),"Resume-ready only"]})]}),C.map(g=>{const D=e.providerSessionId===g.providerSessionId,M=D||!g.canResume||!!c;return s.jsxs("button",{type:"button",onClick:()=>{M||!w||w(g)},disabled:M,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${D?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${M?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${D?"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:yf(g.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:g.preview||"No saved preview yet"}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[g.workspace||"Workspace unknown",ds(g.summaryMetadata)?` · ${ds(g.summaryMetadata)}`:"",g.messageCount>0?` · ${g.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:D?"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)),(j&&!i&&C.length===0||!j&&p.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(Dd,{size:32})}),s.jsx("div",{className:"text-[13px]",children:j?a.length>0?"No saved history matches these filters.":xf():"No recent chat sessions found."})]}),j&&i&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:gf()})})]}),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(er,{size:13})," ",j?bf():"Refresh History"]})})})]})]});return typeof document>"u"?k:zs.createPortal(k,document.body)}const Lo={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 yc({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=Lo[n.type]||Lo.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(wt,{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 vf=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function wf(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function jf(e){return e.sessionId||e.instanceId||e.agentType}function yn(e,t){return e||t}function vc(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Mt(r,{fallbackId:r.id}));return t}function wc(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 Ea(e,t={}){return kf(e,wc(e,t))}function kf(e,t={}){var d,h,m,w,S,p;const r=[],n=t.machineName,a=t.connectionState,i=wf(e),c=ju(e.type,{agentName:e.cliName}),l=Je(e)||qe(e)?c:Ze(e.type),u=Array.isArray(e.childSessions)?e.childSessions.map(x=>{var j,b;return{sessionId:x.id,instanceId:x.id,providerSessionId:x.providerSessionId,transport:x.transport,sessionCapabilities:x.capabilities,agentType:x.providerType,agentName:x.providerName||Ze(x.providerType),status:x.status,title:x.title,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,messages:((j=x.activeChat)==null?void 0:j.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=vf(e);if(f){const x=e.sessionId||e.instanceId,j=c,b=(d=e.activeChat)==null?void 0:d.activeModal,N=b&&Array.isArray(b.buttons)&&b.buttons.length>0,T=bt((h=e.activeChat)==null?void 0:h.status,{activeModal:(m=e.activeChat)==null?void 0:m.activeModal})||bt((S=(w=e.agents)==null?void 0:w[0])==null?void 0:S.status)||"idle",y=e.activeChat||{title:"",messages:[]};let C=y.title&&String(y.title).trim()?String(y.title).trim():"";const k=(p=e.activeChat)==null?void 0:p.id,v=e.chats;if(k&&Array.isArray(v)&&v.length>0){const I=v.find(P=>P.id===k||P.id&&String(P.id)===String(k));I!=null&&I.title&&String(I.title).trim()&&(C=String(I.title).trim())}const g=(Je(e)||qe(e),e.type),D=(Je(e)||qe(e))&&vo(C,j,g)?"":C,M=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:Je(e)?e.mode||"terminal":"chat",agentName:j,agentType:g,status:T,title:D,messages:M,resume:e.resume,hostIdeType:!Je(e)&&!qe(e)?e.type:void 0,workspaceName:i,displayPrimary:D||i||(Je(e)?e.mode==="chat"?j:"Terminal":j),displaySecondary:l,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:N?b.buttons:void 0,modalMessage:N?b.message:void 0,streamSource:"native",tabKey:yn(x,e.id),machineName:n,connectionState:a})}if(f&&(Je(e)||qe(e)))return r;for(const x of u){const j=x.activeModal&&Array.isArray(x.activeModal.buttons)&&x.activeModal.buttons.length>0,b=ku(x),N=jf(x),T=`${e.id}:${N}`,y=x.title&&String(x.title).trim()||"",C=vo(y,x.agentName,x.agentType)?"":y,k=x.messages||[];(x.transport==="cdp-webview"||x.sessionId||x.providerSessionId||k.length>0||j||C||!["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:C,messages:k,hostIdeType:e.type,workspaceName:i,displayPrimary:C||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:j?x.activeModal.buttons:void 0,modalMessage:j?x.activeModal.message:void 0,streamSource:"agent-stream",tabKey:yn(x.sessionId||x.instanceId,T),machineName:n,connectionState:a})}return r.length===0&&r.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:i,displayPrimary:i||l,displaySecondary:l,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:yn(e.sessionId||e.instanceId,e.id),connectionState:a}),r}function Sf(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 jc(e,t){const r=Sf(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const kc=[{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:"🏄"}],Sc=[{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:"🧩"}],Nc=[{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:"🟠"}],Nf=kc,Cf=Sc,If=Nc;function ms(...e){return Yl(Xl(e))}function Af({icon:e,title:t,subtitle:r,badge:n,actions:a,className:i}){return s.jsxs("div",{className:ms("dashboard-header",i),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,n&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[n.count!==void 0?n.count:""," ",n.text]})]}),r&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),a&&s.jsx("div",{className:"flex gap-2",children:a})]})}function Cc({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(Af,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:ms("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}const aa="adhdev:themechange";function Mf(){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"?Mf():e}function Ic(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Lr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(aa,{detail:{preference:e,theme:t}}))}function Tf(){const e=xs(),t=bs(e);Ic(t),Lr(e,t)}function $a(){const[e,t]=o.useState(xs),[r,n]=o.useState(()=>bs(xs()));o.useEffect(()=>{Ic(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),Lr("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(aa,c),window.addEventListener("storage",l),()=>{window.removeEventListener(aa,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=bs(c);t(c),n(l);try{localStorage.setItem("theme",c)}catch{}Lr(c,l)},[]),i=o.useCallback(()=>{t(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=bs(l);n(u);try{localStorage.setItem("theme",l)}catch{}return Lr(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const Ro={dark:"Dark",light:"Light",system:"System"};function Lf({collapsed:e}){const{preference:t,cycleTheme:r}=$a(),n=t==="dark"?s.jsx($d,{size:16}):t==="light"?s.jsx(Ed,{size:16}):s.jsx(Bd,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Ro[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:Ro[t]})]})}function vn(e,t){return e?typeof e=="function"?e(t):e:null}function Rf({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}}),w=()=>d(!0),S=()=>d(!1),p=()=>{m(N=>{const T=!N;try{localStorage.setItem(u,T?"1":"0")}catch{}return T})},x=o.useMemo(()=>({collapsed:h,mobileMenuOpen:f,openMobileMenu:w,closeMobileMenu:S,toggleCollapsed:p}),[h,f]),j=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:j(N),id:`nav-${N.id}`,onClick:()=>{N.onSelect(),S()},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:w,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),f&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:S,onKeyDown:N=>N.key==="Escape"&&S()}),s.jsxs("aside",{className:`sidebar ${f?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${h?"justify-center gap-0":""}`,children:vn(t,x)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:S,children:s.jsx(wt,{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),vn(i,x),s.jsx(Lf,{collapsed:h}),vn(c,x)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function Nt({title:e,icon:t,description:r,accentColor:n,className:a,children:i}){return s.jsxs("div",{className:ms("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",a),style:n?{borderLeftColor:n}:void 0,children:[(e||r)&&s.jsxs("div",{className:"mb-4",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[t&&s.jsx("span",{className:"mr-1.5",children:t}),e]}),r&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),i]})}function Ac({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:ms("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const Pf={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"},_f={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function gr({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:ms("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Pf[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:_f[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 Df={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"},Ef={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function $f({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:ms("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Df[e],r),children:[s.jsx("span",{className:ms("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Ef[e])}),n]})}function Qt({label:e,description:t,checked:r,disabled:n,onChange:a,extra:i}){return s.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,s.jsxs("button",{type:"button",role:"switch","aria-checked":r,"aria-disabled":n,disabled:n,onClick:()=>a(!r),className:`relative inline-flex items-center ${n?"cursor-not-allowed":"cursor-pointer"}`,children:[s.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:r?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),s.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${r?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function Bf({onPrefChange:e}){const[t,r]=Pu(),[n,a]=o.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);o.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,l)=>{r({[c]:l}),e==null||e(c,l)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Xr,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:c=>i("globalEnabled",c)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ct,{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:()=>{Ui().then(a)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:"Allow notifications"})]}),n==="denied"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),n==="unsupported"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),t.globalEnabled&&t.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Kd,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Od,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ys,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!t.globalEnabled&&s.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function zr(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function Kf(e,t){const r=zr(e),n=zr(t);if(!r||!n)return e.localeCompare(t);for(let a=0;a<3;a+=1){if(r[a]<n[a])return-1;if(r[a]>n[a])return 1}return 0}function Mc(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function Hs(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||Kf(r,t)>=0)return!1;const n=zr(r),a=zr(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Of(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function wn(e,t){return e instanceof Error?e.message:t}function Wf({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(Ac,{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(Ff,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function Po({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 zs.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 Hf(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Nf,...Cf,...If].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 Ff({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var K,V;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[f,d]=o.useState(null),[h,m]=o.useState("idle"),[w,S]=o.useState(""),p=e.version||null,x=((K=e.machine)==null?void 0:K.platform)||((V=e.system)==null?void 0:V.platform)||"",j=Mt(e,{fallbackId:e.id}),b=x==="win32"?"🪟":x==="darwin"?"🍎":"🐧",N=t.filter(L=>L.daemonId===e.id&&L.transport==="cdp-page"),T=t.filter(L=>L.daemonId===e.id&&L.transport==="pty"),y=t.filter(L=>L.daemonId===e.id&&L.transport==="acp"),C=e.p2p,k=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const L=Of(await r(e.id,"daemon_upgrade",{}));L.alreadyLatest?(c("done"),u(`Already on v${L.version||"latest"}.`)):L.upgraded||L.success?(c("done"),u(`Upgrade to v${L.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(L.error||"Upgrade failed"))}catch(L){c("error"),u(wn(L,"Connection lost during upgrade"))}}},v=async()=>{if(d(null),!!n){m("loading");try{await n(e.id),m("done"),S("Machine disconnected.")}catch(L){m("error"),S(wn(L,"Failed to disconnect"))}}},g=async()=>{if(d(null),!!a){m("loading");try{await a(e.id),m("done"),S("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(L){m("error"),S(wn(L,"Failed to revoke token"))}}},D="0.9.22",M=Mc(e,D),I=Hs(e,D),P=N.length+T.length+y.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:b}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:j}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),p&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${M?"":"bg-bg-secondary"}`,style:M?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",p,!M&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&M&&s.jsx("button",{onClick:k,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${D}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${I?"↑ Update now":`↑ Update${` to v${D}`}`}`}),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($f,{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:[C&&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 ${C.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${C.state==="connecting"||C.state==="new"?"animate-pulse":""}`,style:C.state==="connecting"||C.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",C.state==="connected"?"connected":C.state==="connecting"||C.state==="new"?"connecting...":C.state||"off"]}),C.peers!==void 0&&C.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",C.peers," peer",C.peers!==1?"s":"",")"]})]}),C&&P>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),P>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[N.map(L=>{const R=Hf(L.type),G=L.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:R.icon}),s.jsx("span",{children:R.name}),G!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${G?"bg-green-400":"animate-pulse"}`,style:G?void 0:{background:"var(--status-warning)"},title:G?"CDP connected":"CDP connecting..."})]},L.id)}),T.map(L=>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:L.cliName||"CLI"})]},L.id)),y.map(L=>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:L.cliName||"ACP"})]},L.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||w)&&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:w||l})]}),f==="disconnect"&&s.jsx(Po,{title:"🔌 Disconnect Machine",message:`Disconnect "${j}" from ADHDev?
|
|
31
|
+
`).includes(a)))}function uf(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 xc(e,t={}){return uf(df(e,t),t.sortMode||"recent")}function Ur(e){return e?"Resume saved history":"Start fresh"}function La(e){return e?"Resuming saved history…":"Starting fresh…"}function mf(){return"Start fresh"}function bc(e,t=!1){return e==="cli"?Ur(t):e==="ide"?"Start IDE":"Start ACP session"}function gc(e,t=!1){return e==="cli"?La(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function ff(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function pf(){return"Open saved history"}function hf(){return"Saved History"}function Ra(){return"Use saved history when you want continuity in the same provider conversation."}function xf(){return"No saved history found yet."}function bf(){return"Refresh saved history"}function gf(){return"Refreshing saved history…"}function ss(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function rs(e){return e==="start-fresh"?"Review the provider and target folder before starting fresh.":e==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Cs(e){return e==="start-fresh"?"Start fresh":"Restart"}function Is(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Pa(e){return`Resume saved history with ${e}?`}function _a(){return"Review or change the target workspace before resuming saved history."}function yf(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 Da({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:w}){var v;const S=t.find(g=>g.id===e.routeId),p=(S==null?void 0:S.chats)||[],x=(v=S==null?void 0:S.activeChat)==null?void 0:v.id,j=Je(e)&&!qe(e),[b,N]=o.useState(()=>ht()),T=l||b,y=g=>{if(u){u(g);return}N(g)},C=o.useMemo(()=>xc(a,{textQuery:T.textQuery,workspaceQuery:T.workspaceQuery,modelQuery:T.modelQuery,resumableOnly:T.resumableOnly,sortMode:T.sortMode}),[T.modelQuery,T.resumableOnly,T.sortMode,T.textQuery,T.workspaceQuery,a]),k=s.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:f,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:j?hf():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Zm(e)}),j&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Ra()})]}),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(wt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!j&&s.jsx("button",{onClick: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"}),j?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:T.textQuery,onChange:g=>y({...T,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:T.workspaceQuery,onChange:g=>y({...T,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:T.modelQuery,onChange:g=>y({...T,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:T.sortMode,onChange:g=>y({...T,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:T.resumableOnly,onChange:g=>y({...T,resumableOnly:g.target.checked})}),"Resume-ready only"]})]}),C.map(g=>{const D=e.providerSessionId===g.providerSessionId,M=D||!g.canResume||!!c;return s.jsxs("button",{type:"button",onClick:()=>{M||!w||w(g)},disabled:M,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${D?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${M?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${D?"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:yf(g.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:g.preview||"No saved preview yet"}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[g.workspace||"Workspace unknown",ds(g.summaryMetadata)?` · ${ds(g.summaryMetadata)}`:"",g.messageCount>0?` · ${g.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:D?"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)),(j&&!i&&C.length===0||!j&&p.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(Dd,{size:32})}),s.jsx("div",{className:"text-[13px]",children:j?a.length>0?"No saved history matches these filters.":xf():"No recent chat sessions found."})]}),j&&i&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:gf()})})]}),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(er,{size:13})," ",j?bf():"Refresh History"]})})})]})]});return typeof document>"u"?k:zs.createPortal(k,document.body)}const Lo={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 yc({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=Lo[n.type]||Lo.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(wt,{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 vf=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function wf(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function jf(e){return e.sessionId||e.instanceId||e.agentType}function yn(e,t){return e||t}function vc(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Mt(r,{fallbackId:r.id}));return t}function wc(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 Ea(e,t={}){return kf(e,wc(e,t))}function kf(e,t={}){var d,h,m,w,S,p;const r=[],n=t.machineName,a=t.connectionState,i=wf(e),c=ju(e.type,{agentName:e.cliName}),l=Je(e)||qe(e)?c:Ze(e.type),u=Array.isArray(e.childSessions)?e.childSessions.map(x=>{var j,b;return{sessionId:x.id,instanceId:x.id,providerSessionId:x.providerSessionId,transport:x.transport,sessionCapabilities:x.capabilities,agentType:x.providerType,agentName:x.providerName||Ze(x.providerType),status:x.status,title:x.title,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,messages:((j=x.activeChat)==null?void 0:j.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=vf(e);if(f){const x=e.sessionId||e.instanceId,j=c,b=(d=e.activeChat)==null?void 0:d.activeModal,N=b&&Array.isArray(b.buttons)&&b.buttons.length>0,T=bt((h=e.activeChat)==null?void 0:h.status,{activeModal:(m=e.activeChat)==null?void 0:m.activeModal})||bt((S=(w=e.agents)==null?void 0:w[0])==null?void 0:S.status)||"idle",y=e.activeChat||{title:"",messages:[]};let C=y.title&&String(y.title).trim()?String(y.title).trim():"";const k=(p=e.activeChat)==null?void 0:p.id,v=e.chats;if(k&&Array.isArray(v)&&v.length>0){const I=v.find(P=>P.id===k||P.id&&String(P.id)===String(k));I!=null&&I.title&&String(I.title).trim()&&(C=String(I.title).trim())}const g=(Je(e)||qe(e),e.type),D=(Je(e)||qe(e))&&vo(C,j,g)?"":C,M=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:Je(e)?e.mode||"terminal":"chat",agentName:j,agentType:g,status:T,title:D,messages:M,resume:e.resume,hostIdeType:!Je(e)&&!qe(e)?e.type:void 0,workspaceName:i,displayPrimary:D||i||(Je(e)?e.mode==="chat"?j:"Terminal":j),displaySecondary:l,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:N?b.buttons:void 0,modalMessage:N?b.message:void 0,streamSource:"native",tabKey:yn(x,e.id),machineName:n,connectionState:a})}if(f&&(Je(e)||qe(e)))return r;for(const x of u){const j=x.activeModal&&Array.isArray(x.activeModal.buttons)&&x.activeModal.buttons.length>0,b=ku(x),N=jf(x),T=`${e.id}:${N}`,y=x.title&&String(x.title).trim()||"",C=vo(y,x.agentName,x.agentType)?"":y,k=x.messages||[];(x.transport==="cdp-webview"||x.sessionId||x.providerSessionId||k.length>0||j||C||!["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:C,messages:k,hostIdeType:e.type,workspaceName:i,displayPrimary:C||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:j?x.activeModal.buttons:void 0,modalMessage:j?x.activeModal.message:void 0,streamSource:"agent-stream",tabKey:yn(x.sessionId||x.instanceId,T),machineName:n,connectionState:a})}return r.length===0&&r.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:i,displayPrimary:i||l,displaySecondary:l,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:yn(e.sessionId||e.instanceId,e.id),connectionState:a}),r}function Sf(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 jc(e,t){const r=Sf(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const kc=[{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:"🏄"}],Sc=[{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:"🧩"}],Nc=[{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:"🟠"}],Nf=kc,Cf=Sc,If=Nc;function ms(...e){return Yl(Xl(e))}function Af({icon:e,title:t,subtitle:r,badge:n,actions:a,className:i}){return s.jsxs("div",{className:ms("dashboard-header",i),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,n&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[n.count!==void 0?n.count:""," ",n.text]})]}),r&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),a&&s.jsx("div",{className:"flex gap-2",children:a})]})}function Cc({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(Af,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:ms("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}const aa="adhdev:themechange";function Mf(){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"?Mf():e}function Ic(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Lr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(aa,{detail:{preference:e,theme:t}}))}function Tf(){const e=xs(),t=bs(e);Ic(t),Lr(e,t)}function $a(){const[e,t]=o.useState(xs),[r,n]=o.useState(()=>bs(xs()));o.useEffect(()=>{Ic(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),Lr("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(aa,c),window.addEventListener("storage",l),()=>{window.removeEventListener(aa,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=bs(c);t(c),n(l);try{localStorage.setItem("theme",c)}catch{}Lr(c,l)},[]),i=o.useCallback(()=>{t(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=bs(l);n(u);try{localStorage.setItem("theme",l)}catch{}return Lr(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const Ro={dark:"Dark",light:"Light",system:"System"};function Lf({collapsed:e}){const{preference:t,cycleTheme:r}=$a(),n=t==="dark"?s.jsx($d,{size:16}):t==="light"?s.jsx(Ed,{size:16}):s.jsx(Bd,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Ro[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:Ro[t]})]})}function vn(e,t){return e?typeof e=="function"?e(t):e:null}function Rf({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}}),w=()=>d(!0),S=()=>d(!1),p=()=>{m(N=>{const T=!N;try{localStorage.setItem(u,T?"1":"0")}catch{}return T})},x=o.useMemo(()=>({collapsed:h,mobileMenuOpen:f,openMobileMenu:w,closeMobileMenu:S,toggleCollapsed:p}),[h,f]),j=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:j(N),id:`nav-${N.id}`,onClick:()=>{N.onSelect(),S()},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:w,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),f&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:S,onKeyDown:N=>N.key==="Escape"&&S()}),s.jsxs("aside",{className:`sidebar ${f?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${h?"justify-center gap-0":""}`,children:vn(t,x)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:S,children:s.jsx(wt,{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),vn(i,x),s.jsx(Lf,{collapsed:h}),vn(c,x)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function Nt({title:e,icon:t,description:r,accentColor:n,className:a,children:i}){return s.jsxs("div",{className:ms("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",a),style:n?{borderLeftColor:n}:void 0,children:[(e||r)&&s.jsxs("div",{className:"mb-4",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[t&&s.jsx("span",{className:"mr-1.5",children:t}),e]}),r&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),i]})}function Ac({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:ms("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const Pf={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"},_f={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function gr({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:ms("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Pf[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:_f[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 Df={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"},Ef={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function $f({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:ms("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Df[e],r),children:[s.jsx("span",{className:ms("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Ef[e])}),n]})}function Qt({label:e,description:t,checked:r,disabled:n,onChange:a,extra:i}){return s.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,s.jsxs("button",{type:"button",role:"switch","aria-checked":r,"aria-disabled":n,disabled:n,onClick:()=>a(!r),className:`relative inline-flex items-center ${n?"cursor-not-allowed":"cursor-pointer"}`,children:[s.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:r?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),s.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${r?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function Bf({onPrefChange:e}){const[t,r]=Pu(),[n,a]=o.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);o.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,l)=>{r({[c]:l}),e==null||e(c,l)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Xr,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:c=>i("globalEnabled",c)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ct,{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:()=>{Ui().then(a)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:"Allow notifications"})]}),n==="denied"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),n==="unsupported"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),t.globalEnabled&&t.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Kd,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Od,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ys,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!t.globalEnabled&&s.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function zr(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function Kf(e,t){const r=zr(e),n=zr(t);if(!r||!n)return e.localeCompare(t);for(let a=0;a<3;a+=1){if(r[a]<n[a])return-1;if(r[a]>n[a])return 1}return 0}function Mc(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function Hs(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||Kf(r,t)>=0)return!1;const n=zr(r),a=zr(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Of(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function wn(e,t){return e instanceof Error?e.message:t}function Wf({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(Ac,{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(Ff,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function Po({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 zs.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 Hf(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Nf,...Cf,...If].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 Ff({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var K,V;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[f,d]=o.useState(null),[h,m]=o.useState("idle"),[w,S]=o.useState(""),p=e.version||null,x=((K=e.machine)==null?void 0:K.platform)||((V=e.system)==null?void 0:V.platform)||"",j=Mt(e,{fallbackId:e.id}),b=x==="win32"?"🪟":x==="darwin"?"🍎":"🐧",N=t.filter(L=>L.daemonId===e.id&&L.transport==="cdp-page"),T=t.filter(L=>L.daemonId===e.id&&L.transport==="pty"),y=t.filter(L=>L.daemonId===e.id&&L.transport==="acp"),C=e.p2p,k=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const L=Of(await r(e.id,"daemon_upgrade",{}));L.alreadyLatest?(c("done"),u(`Already on v${L.version||"latest"}.`)):L.upgraded||L.success?(c("done"),u(`Upgrade to v${L.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(L.error||"Upgrade failed"))}catch(L){c("error"),u(wn(L,"Connection lost during upgrade"))}}},v=async()=>{if(d(null),!!n){m("loading");try{await n(e.id),m("done"),S("Machine disconnected.")}catch(L){m("error"),S(wn(L,"Failed to disconnect"))}}},g=async()=>{if(d(null),!!a){m("loading");try{await a(e.id),m("done"),S("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(L){m("error"),S(wn(L,"Failed to revoke token"))}}},D="0.9.23",M=Mc(e,D),I=Hs(e,D),P=N.length+T.length+y.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:b}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:j}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),p&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${M?"":"bg-bg-secondary"}`,style:M?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",p,!M&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&M&&s.jsx("button",{onClick:k,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${D}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${I?"↑ Update now":`↑ Update${` to v${D}`}`}`}),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($f,{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:[C&&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 ${C.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${C.state==="connecting"||C.state==="new"?"animate-pulse":""}`,style:C.state==="connecting"||C.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",C.state==="connected"?"connected":C.state==="connecting"||C.state==="new"?"connecting...":C.state||"off"]}),C.peers!==void 0&&C.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",C.peers," peer",C.peers!==1?"s":"",")"]})]}),C&&P>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),P>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[N.map(L=>{const R=Hf(L.type),G=L.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:R.icon}),s.jsx("span",{children:R.name}),G!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${G?"bg-green-400":"animate-pulse"}`,style:G?void 0:{background:"var(--status-warning)"},title:G?"CDP connected":"CDP connecting..."})]},L.id)}),T.map(L=>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:L.cliName||"CLI"})]},L.id)),y.map(L=>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:L.cliName||"ACP"})]},L.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||w)&&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:w||l})]}),f==="disconnect"&&s.jsx(Po,{title:"🔌 Disconnect Machine",message:`Disconnect "${j}" from ADHDev?
|
|
32
32
|
|
|
33
33
|
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
34
34
|
|
|
@@ -39,7 +39,7 @@ This will:
|
|
|
39
39
|
• Delete the machine registration
|
|
40
40
|
• Require restarting ADHDev on that machine
|
|
41
41
|
|
|
42
|
-
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:g,onCancel:()=>d(null)})]})}const Uf=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function zf(){const{preference:e,setPreference:t}=$a();return s.jsx("div",{className:"flex gap-2",children:Uf.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 Vf(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 Gf(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function jn(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function _o(e){const{r:t,g:r,b:n}=Gf(e);return .2126*jn(t)+.7152*jn(r)+.0722*jn(n)}function Do(e,t){const r=_o(e),n=_o(t),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function Tc(e){const t=Vf(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return Do(t,r)>=Do(t,n)?r:n}const oa={bgPrimary:"#0a0e1a",bgSecondary:"#0f1320",surfacePrimary:"#111726",textPrimary:"#f0f0f5",textSecondary:"#9ca3af",textMuted:"#6b7280",borderSubtle:"#1d2536",borderDefault:"#313c52",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#111726",assistantText:"#f0f0f5",containerBg:"#0f1320",sendButton:"#d97706",inputBorder:"#313c52",bubbleRadius:16},ia={bgPrimary:"#fff8ee",bgSecondary:"#fff1de",surfacePrimary:"#ffffff",textPrimary:"#24160f",textSecondary:"#6f6255",textMuted:"#938374",borderSubtle:"#e7d3ba",borderDefault:"#d7b892",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#fffaf4",assistantText:"#24160f",containerBg:"#fff8ee",sendButton:"#d97706",inputBorder:"#d7b892",bubbleRadius:16},qf=[{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"}}}],Lc="adhdev-chat-theme",Rc="adhdev-chat-theme-custom";function Rr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Lc)||"ember"}catch{return"ember"}}function Pt(e){try{const t=localStorage.getItem(Rc);if(t){const r=JSON.parse(t);return{...e==="dark"?oa:ia,...r[e]}}}catch{}return e==="dark"?oa:ia}function yr(e,t){try{localStorage.setItem(Rc,JSON.stringify({dark:e,light:t}))}catch{}}function It(e,t){const r=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${r}, ${n}, ${a}, ${t})`}function Vr(e,t){const r=Math.min(255,parseInt(e.slice(1,3),16)+t),n=Math.min(255,parseInt(e.slice(3,5),16)+t),a=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const Yf={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Fs(e,t){var a;const r=(a=Yf[e])==null?void 0:a[t];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",Vr(r,24)),n.style.setProperty("--accent-on-primary",Tc(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Vr(r,18)})`),n.style.setProperty("--border-accent",It(r,.35)),n.style.setProperty("--nav-active-bg",It(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${It(r,.06)}`)}function ns(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",It(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",It(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",It(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",It(e.borderSubtle,.5)),t.style.setProperty("--border-default",It(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Vr(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Tc(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Vr(e.accentColor,40)})`),t.style.setProperty("--border-accent",It(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",It(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${It(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${It(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function Ba(){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 Xf(e){try{localStorage.setItem(Lc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=as()?"dark":"light";ns(Pt(t))}else Ba(),Fs(e,as()?"dark":"light")}function Jf(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Rr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=as()?"dark":"light";ns(Pt(t))}else Ba(),Fs(e,as()?"dark":"light")}function as(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function xt({label:e,value:t,onChange:r}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,onChange:n=>{/^#[0-9a-fA-F]{0,6}$/.test(n.target.value)&&r(n.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function Ps({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 Qf({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=o.useState(()=>Pt(r));o.useEffect(()=>{a(Pt(r))},[r]);const i=o.useCallback((c,l)=>{a(u=>{const f={...u,[c]:l},h=Pt(r==="dark"?"light":"dark");return r==="dark"?yr(f,h):yr(h,f),ns(f),t(f),f})},[r,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",s.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(Ps,{title:"App Background",children:[s.jsx(xt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(xt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(xt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(Ps,{title:"App Text",children:[s.jsx(xt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(xt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(xt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(Ps,{title:"Borders & Accent",children:[s.jsx(xt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(xt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(xt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Ps,{title:"Chat Bubbles",children:[s.jsx(xt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(xt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),s.jsx(xt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(xt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(Ps,{title:"Chat Layout",children:[s.jsx(xt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(xt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(xt,{label:"Input border",value:n.inputBorder,onChange:c=>i("inputBorder",c)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.jsx("input",{type:"range",min:4,max:24,value:n.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?oa:ia,u=Pt(e?"light":"dark");e?yr(c,u):yr(u,c),a(c),ns(c),t(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:"Reset to defaults"})]})}function Zf(){const[e,t]=o.useState(Rr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Pt("dark"));o.useEffect(()=>{n(as());const u=new MutationObserver(()=>{const h=as();n(h);const m=Rr();m==="custom"?ns(Pt(h?"dark":"light")):Fs(m,h?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const f=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{const h=as();n(h);const m=Rr();m==="custom"?ns(Pt(h?"dark":"light")):Fs(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"?ns(Pt(r?"dark":"light")):(Ba(),Fs(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Pt(r?"dark":"light"))},[r]);const c=u=>{t(u),Xf(u)},l=[...qf,{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(Qf,{dark:r,onColorsChange:u=>i(u)})]})}const Ka="adhdev_mobileDashboardMode_v1",ca="adhdev:mobile-dashboard-mode-change";function Oa(){try{return localStorage.getItem(Ka)==="workspace"?"workspace":"chat"}catch{return"chat"}}function ep(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??Oa())},r=a=>{const i=a.detail;t(i)},n=a=>{a.key&&a.key!==Ka||t()};return window.addEventListener(ca,r),window.addEventListener("storage",n),()=>{window.removeEventListener(ca,r),window.removeEventListener("storage",n)}}function tp(e){try{localStorage.setItem(Ka,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(ca,{detail:e}))}function sp(){const[e,t]=o.useState(!0);return o.useEffect(()=>{t(Oa()==="chat")},[]),s.jsx(Qt,{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),tp(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const kn=new Map,Eo=new Map;function rp(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 np(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 Pc(){const{sendCommand:e}=jt(),{injectEntries:t,getIdes:r}=Gs();return o.useCallback(async(n,a)=>{if(!n)return;const i=(a==null?void 0:a.minFreshMs)??vm,c=Eo.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<i)return;const l=kn.get(n);if(l)return l;const u=(async()=>{const f=await e(n,"get_machine_runtime_stats"),d=rp(f);if(!d)return;const h=r().find(w=>w.id===n),m=np(h,n,d.machine,d.timestamp||Date.now());t([m]),Eo.set(n,Date.now())})().finally(()=>{kn.delete(n)});return kn.set(n,u),u},[r,t,e])}function ap(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 op(e,t){const{sendData:r}=jt(),{injectEntries:n,getIdes:a}=Gs(),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=>qt.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(w=>w.id===u),m=ap(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 ip(e,t){const{sendData:r}=jt(),[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=qt.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},f=>{l&&(clearTimeout(l),l=null),a(f.diagnostics),c(!1)});return u.initialSendAccepted?l=setTimeout(()=>{c(!1)},Sm):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 cp(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function _c(e){const{sendData:t}=jt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=cp(e);if(!a||!e.sessionId||!t){n({});return}const i=qt.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),ks.record({interactionId:c.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:c.status,modalButtonCount:Array.isArray(c.modalButtons)?c.modalButtons.length:0}})});return i.initialSendAccepted||n({}),()=>{i()}},[e.daemonId,e.routeId,e.sessionId,t]),r}const Dc="adhdev_hiddenTabs";function lp(){try{const e=localStorage.getItem(Dc);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ps(e){try{localStorage.setItem(Dc,JSON.stringify([...e]))}catch{}}function Sn(e){return Ca(e)}function Wa(e,t){return ws(t).some(r=>e.has(r))}function dp(){const[e,t]=o.useState(lp),r=o.useCallback(f=>{const d=Sn(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=Sn(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=Sn(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 w of d)m.add(w);return ps(m),m})},[]),l=o.useCallback((f,d)=>{t(h=>{const m=new Set(h);for(const w of d)m.delete(w);return ps(m),m})},[]),u=o.useCallback(f=>Wa(e,f),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function Ec(e){return e instanceof Error?e.message:String(e||"")}function $c(e){const t=Ec(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 Bc(e){const t=Ec(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Kc({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!Je(e)||qe(e))return;const i=Ts(e);if(i===t)return;const c=e.sessionId;c&&a(l=>({...l,[c]:t}));try{await n(fs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Kt(e),mode:t})}catch(l){const u=Bc(l);c&&!u&&a(f=>{const d={...f};return i===Oc(r,c)?delete d[c]:d[c]=i,d}),$c(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 $o(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 up(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=$o(a,t),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>$o(u,t)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function Oc(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))Oc(t,a)===i&&(delete n[a],r=!0);return r?n:e}function fp({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{Ui()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:fc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Eu(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 pp(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=r.get(n.id);if(!a){r.set(n.id,n);continue}const i=(a.workspace?1:0)+(a.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>i||(n.timestamp||0)>(a.timestamp||0))&&r.set(n.id,n)}return Array.from(r.values())}function Nn(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function hp(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 Bo(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?hp(Vs(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 xp(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||""),Bo(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||""),Bo(r.activeChat)].join(":"))].join("|")}function bp(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 gp(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 yp(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function vp(e){const t=yp(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=Vs(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function wp({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=o.useMemo(()=>pp(e),[e]),i=o.useMemo(()=>vc(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 T=new Map,y=[];for(const g of a){const{connectionState:D="new",machineName:M}=wc(g,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),I=xp(g),P=f.current.get(g.id);if(P&&P.ide===g&&P.sourceSignature===I&&P.connectionState===D&&P.machineName===M){T.set(g.id,P),y.push(...P.conversations);continue}const K=Ea(g,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),V={ide:g,sourceSignature:I,connectionState:D,machineName:M,conversations:K};T.set(g.id,V),y.push(...K)}f.current=T;const C=new Map,k=g=>{const D=vp(g),M=d.current.get(g.tabKey);if(M&&M.signature===D)return C.set(g.tabKey,M),M.timestamp;const I={signature:D,timestamp:ec(g)||(M==null?void 0:M.timestamp)||0};return C.set(g.tabKey,I),I.timestamp},v=[...y].sort((g,D)=>tc(g,D,k));return d.current=C,v},[a,t,i]),m=o.useMemo(()=>{const T=bp(h,r);return Nn(c.current,T)?c.current:(c.current=T,T)},[h,r]),w=o.useMemo(()=>{const T=new Map,y=Array.from(new Set(m.map(C=>C.routeId)));for(const C of y){const k=_t(m,C);k&&T.set(C,k)}return T},[m]),S=o.useMemo(()=>{const T=new Map;for(const y of m){const C=w.get(y.routeId),k=y.streamSource==="native"&&C?C:y;for(const v of ws({providerSessionId:y.providerSessionId,sessionId:y.sessionId}))T.set(v,k)}return T},[m,w]),p=o.useMemo(()=>gp(m,w),[m,w]),x=o.useCallback(T=>{if(T)return S.get(T)},[S]),j=o.useCallback(T=>{if(T)return p.get(T)},[p]),b=o.useMemo(()=>{const T=m.filter(y=>!Wa(n,y));return Nn(l.current,T)?l.current:(l.current=T,T)},[m,n]),N=o.useMemo(()=>{const T=b.map(y=>y.tabKey);return Nn(u.current,T)?u.current:(u.current=T,T)},[b]);return{chatIdes:a,conversations:m,visibleConversations:b,visibleTabKeys:N,resolveConversationBySessionId:x,resolveConversationByTarget:j}}function jp({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(()=>{lt.setIdes(e)},[e]),o.useEffect(()=>{lt.setResolveAction((a,i,c)=>{t(a,i,c).catch(()=>{})})},[t]),o.useEffect(()=>{const a=lt.onToast(i=>{r(l=>l.some(f=>f.message===i.message&&i.timestamp-f.timestamp<3e3)?l:[...l.slice(-4),{id:i.id,message:i.message,type:i.type,timestamp:i.timestamp,targetKey:i.targetKey,actions:i.actions}]);const c=i.duration||5e3;setTimeout(()=>r(l=>l.filter(u=>u.id!==i.id)),c)});return()=>{a()}},[r]),o.useEffect(()=>{const a=dc.on("status_event",i=>{lt.handleRawEvent(i,"ws")});return()=>{a()}},[]),o.useEffect(()=>{var i;const a=c=>{var p;const l=c.data;if((l==null?void 0:l.type)!=="notification_action"||typeof l.action!="string"||!l.action.startsWith("approval_")||!(l.daemonId||l.targetSessionId||l.targetKey))return;const 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",w=String(m).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),S=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(w);t(d,"resolve_action",{action:S?"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 Sp="adhdev_dashboardLayout_v1",Np="adhdev_dashboardDockview_v1",Cp="adhdev_dashboardDockviewHiddenRestore_v1",_s={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Ha(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function Ip(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Wc(e){return`${Sp}:${e}`}function Ap(e){const t=Wc(e);return Ha(t,null)}function Mp(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=Wc(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Hc(e){return`${Np}:${e}`}function Tp(e){const t=Hc(e);return Ha(t,null)}function Lp(e,t){try{const r=Hc(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Fc(e){return`${Cp}:${e}`}function Rp(e){const t=Fc(e);return Ha(t,{})}function Pp(e,t){try{const r=Fc(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function _p(){return{groupAssignments:[..._s.groupAssignments],focusedGroup:_s.focusedGroup,groupActiveTabIds:{..._s.groupActiveTabIds},groupTabOrders:{..._s.groupTabOrders},groupSizes:[..._s.groupSizes]}}function Dp(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function Ep(){const[e]=o.useState(()=>Ip(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),[w,S]=o.useState(!1),p=o.useCallback(()=>{if(w)return;const g=Ap(e)??_p();r(new Map(g.groupAssignments)),a(g.focusedGroup),c(g.groupActiveTabIds),u(g.groupTabOrders),d(g.groupSizes),S(!0)},[w,e]);o.useEffect(()=>{w&&Mp(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:f})},[w,e,t,n,i,l,f]),o.useEffect(()=>{const g=window.matchMedia("(max-width: 767px)"),D=M=>m(M.matches);return g.addEventListener("change",D),()=>g.removeEventListener("change",D)},[]);const x=o.useCallback(g=>{r(g)},[]),j=o.useCallback(g=>{a(g)},[]),b=o.useCallback(g=>{c(g)},[]),N=o.useCallback(g=>{u(g)},[]),T=o.useCallback(g=>{d(g)},[]),y=o.useCallback(g=>{j(g)},[j]),C=o.useCallback((g,D)=>{c(M=>(M[g]??null)===(D??null)?M:{...M,[g]:D})},[]),k=o.useCallback((g,D)=>{u(M=>{const I=M[g];return Dp(I,D)?M:{...M,[g]:D}})},[]),v=o.useCallback((g,D)=>{const M=D.get(g)??0;return C(M,g),y(M),M},[y,C]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:x,focusedGroup:n,updateFocusedGroup:j,focusGroup:y,groupActiveTabIds:i,updateGroupActiveTabIds:b,setGroupActiveTab:C,groupTabOrders:l,updateGroupTabOrders:N,setGroupTabOrder:k,groupSizes:f,updateGroupSizes:T,isMobile:h,hasHydratedStoredLayout:w,hydrateStoredLayout:p,focusConversationTab:v}}function $p(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=Na(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Bp({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 w=o.useRef(!1),S=o.useRef(!1),p=o.useRef(null),x=o.useRef(!1);o.useEffect(()=>{if(!e||w.current||t.length===0)return;if(!a){i();return}const j=r(e);j&&(c(j.tabKey,n),w.current=!0,S.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),l(b=>{const N=new URLSearchParams(b);return N.delete("activeTab"),N},{replace:!0}))},[e,t,r,n,a,i,c,l]),o.useEffect(()=>{if(!(S.current||a)&&t.length!==0){if(!e){i(),S.current=!0;return}if(w.current){S.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(S.current||a)&&(i(),S.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,t.length,a,i]),o.useEffect(()=>{if(!u){x.current=!1;return}if(!f||x.current||d)return;const j=h.find(b=>b.id===f.routeId);j&&(!j.chats||j.chats.length===0||$p(j.chats,f))&&(x.current=!0,m())},[u,f,d,h,m]),o.useEffect(()=>{if(!f)return;let j=null,b=0,N=-1,T=0;const y=()=>{j=null;const C=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(v=>v.offsetParent!==null);if(C.length===0){b<18&&(b+=1,j=requestAnimationFrame(y));return}let k=0;for(const v of C)v.scrollTop=v.scrollHeight,k+=v.scrollHeight;k===N?T+=1:(T=0,N=k),b+=1,!(T>=2||b>=18)&&(j=requestAnimationFrame(y))};return j=requestAnimationFrame(y),()=>{j!=null&&cancelAnimationFrame(j)}},[f==null?void 0:f.tabKey])}function Cn(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0];if((r==null?void 0:r.active)===!0)return!0;const n=Na(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Uc({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 S=>{try{await e("standalone","launch_ide",{ideType:S,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),h=o.useCallback(async(S,p)=>{try{const x=S||(t==null?void 0:t.daemonId)||"",j=await e(x,"switch_chat",{id:p,sessionId:p,...js(t)}),b=j==null?void 0:j.result;if((j==null?void 0:j.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?Rs(a,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?Rs(a,`⚠️ Switch error: ${b}`):Rs(a,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),Rs(a,`❌ Switch failed: ${x.message||"connection error"}`)}},[t,e,a]),m=o.useCallback(async()=>{if(!(!t||c)){l(!0);try{const S=Js(t);await e(S,"new_chat",{...js(t)}),i(p=>({...p,[t.tabKey]:Date.now()}))}catch(S){console.error("New chat failed",S)}finally{l(!1)}}},[t,c,e,i]),w=o.useCallback(async()=>{var S,p;if(!(!t||u)){f(!0);try{const x=Js(t),j=async()=>e(x,"list_chats",{forceExpand:!0,...js(t)});let b=await j(),N=(b==null?void 0:b.chats)||((S=b==null?void 0:b.result)==null?void 0:S.chats);Cn(N,t)&&(await new Promise(T=>setTimeout(T,450)),b=await j(),N=(b==null?void 0:b.chats)||((p=b==null?void 0:b.result)==null?void 0:p.chats)),b!=null&&b.success&&Array.isArray(N)&&(n(t.routeId,N),Cn(N,t)&&!Cn(r,t)&&Rs(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:w}}function Kp(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 Op(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function Ko(e,t){const r=Object.keys(e),n=Object.keys(t);return r.length!==n.length?!1:r.every(a=>t[Number(a)]===e[Number(a)])}function vr(e,t){const r=new Set(t),n=t.length>0?[0]:[];for(const[c,l]of e)!r.has(c)||l<=0||n.includes(l)||n.push(l);n.sort((c,l)=>c-l);const a={};n.forEach((c,l)=>{a[c]=l}),n.length===0&&(a[0]=0);const i=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const 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 Oo(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 Wp(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 Hp(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 Wo(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 Ho(e){return Array(e).fill(100/e)}function Fp({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(()=>vr(e,f),[e,f]),m=h.assignments,w=o.useMemo(()=>l?1:h.groupCount,[h.groupCount,l]),S=w>1,p=o.useCallback((y,C)=>{t(k=>{const v=new Map(vr(k,f).assignments);return C===0?v.delete(y):v.set(y,C),v}),n(k=>({...k,[C]:y})),r(C)},[t,f,n,r]),x=o.useCallback(y=>{t(C=>{const k=vr(C,f).assignments,v=new Map;for(const[g,D]of k)D!==y&&(D>y?v.set(g,D-1):v.set(g,D));return v}),c(C=>{if(C.length<=1)return[];const k=[...C];k.splice(y,1);const v=k.reduce((g,D)=>g+D,0);return v>0?k.map(g=>g/v*100):[]}),r(0)},[t,f,c,r]),j=o.useCallback((y,C)=>{C.preventDefault();const k=d.current;if(!k)return;const v=C.clientX,g=k.offsetWidth,D=i.length===w?[...i]:Ho(w),M=P=>{const V=(P.clientX-v)/g*100,L=[...D];L[y]=Math.max(15,D[y]+V),L[y+1]=Math.max(15,D[y+1]-V),c(L)},I=()=>{document.removeEventListener("mousemove",M),document.removeEventListener("mouseup",I),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",M),document.addEventListener("mouseup",I)},[i,w,c]),b=o.useCallback((y,C,k)=>{if(w>=4)return;const v=k==="left"?C:C+1;t(g=>{const D=vr(g,f).assignments,M=new Map;for(const I of u){const P=D.get(I.tabKey)??0,K=P>=v?P+1:P;K>0&&M.set(I.tabKey,K)}return v>0&&M.set(y,v),M}),c(g=>{const D=g.length===w?[...g]:Ho(w),M=D[C]??100/w,I=Math.max(15,M/2),P=Math.max(15,M/2),K=[...D];K[C]=I,K.splice(v,0,P);const V=K.reduce((L,R)=>L+R,0);return K.map(L=>L/V*100)}),n(g=>{const D=Wo(g,v);return D[v]=y,D}),a(g=>{const D=Wo(g,v);return D[v]=[y],D}),r(v)},[w,t,f,u,c,n,a,r]);o.useEffect(()=>{Kp(e,m)||t(m)},[e,m,t]),o.useEffect(()=>{const{mapping:y,usedGroups:C}=h;n(k=>{const v=Oo(k,y);return Ko(k,v)?k:v}),a(k=>{const v=Oo(k,y);return Ko(k,v)?k:v}),r(k=>{const v=l?0:Wp(k,C,y);return k===v?k:v}),c(k=>{const v=l?[]:Hp(k,C,h.groupCount);return Op(k,v)?k:v})},[h,l,n,a,r,c]);const N=o.useMemo(()=>{const y=Array.from({length:w},()=>[]);for(const C of u){const k=m.get(C.tabKey)??0,v=Math.min(k,w-1);y[v].push(C)}return y},[u,m,w]),T=o.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:d,normalizedGroupAssignments:m,numGroups:w,isSplitMode:S,groupedConvs:N,moveTabToGroup:p,closeGroup:x,handleResizeStart:j,splitTabRelative:b,clearAllSplits:T}}function Up({ides:e,sendDaemonCommand:t}){const r="0.9.22",n=o.useMemo(()=>e.filter(d=>d.type!=="adhdev-daemon"?!1:Mc(d,r)).sort((d,h)=>Number(Hs(h,r))-Number(Hs(d,r))),[r,e]),a=o.useMemo(()=>n.some(d=>Hs(d,r)),[r,n]),[i,c]=o.useState(!1),[l,u]=o.useState({}),f=o.useCallback(async d=>{var h,m;u(w=>({...w,[d]:"upgrading"}));try{const w=await t(d,"daemon_upgrade",{});(h=w==null?void 0:w.result)!=null&&h.upgraded||(m=w==null?void 0:w.result)!=null&&m.success?u(S=>({...S,[d]:"done"})):u(S=>({...S,[d]:"error"}))}catch{u(w=>({...w,[d]:"error"}))}},[t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:f}}const zc=80;function Pr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function zp(e){return{...e,createdAt:Pr(e.createdAt),updatedAt:Pr(e.updatedAt,e.createdAt),lastEventAt:Pr(e.lastEventAt,e.updatedAt||e.createdAt)}}function Vp(e){const t=Ca(e);return t==="unknown:"?e.id:t}function Gp(e){return[e.type,Zi(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function qp(e,t=zc){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=Vp(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 Yp(e,t){const r=Date.now(),n=[];for(const a of e){const i=a.sessionId?t.get(a.sessionId):void 0;if(i!=null&&i.surfaceHidden)continue;const c=Qr(a,t),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const u=Pr(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),f=Gp({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(zp({id:f,dedupKey:f,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Yi(a),preview:om(a),createdAt:u,updatedAt:u,lastEventAt:u}))}return qp(n)}function Xp(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function Jp(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=zc}=e,a=o.useMemo(()=>Yp(t,r).slice(0,Math.max(0,n)),[t,r,n]),i=o.useMemo(()=>Xp(a),[a]);return{notifications:a,unreadCount:i}}function Qp({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 tn(...e){const t=new Set,r=[],n=a=>{const i=typeof a=="string"?a.trim():"";if(!i)return;const c=i.toLowerCase();t.has(c)||(t.add(c),r.push(i))};for(const a of e){if(Array.isArray(a)){for(const i of a)n(i);continue}n(a)}return r}function Zp(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const r=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),a=(r[2]||"").replace(/[\\/]+/g,"\\");return a?`${n}:\\${a}`:`${n}:\\`}return null}function sn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=Zp(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 eh(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 th(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function rn(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=th(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 sh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Fo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function rh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function nh({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=Fo(n.workspacePath),l=e.find(f=>{var S,p,x,j;if(!f||f.type==="adhdev-daemon"||sh(f.daemonId||f.id)!==n.machineId||(Xs(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=Fo(f.workspace||f.runtimeWorkspaceLabel);return b?b===c:!1}return Number(f.lastUpdated||f._lastUpdate||f.timestamp||((j=(x=(p=(S=f.activeChat)==null?void 0:S.messages)==null?void 0:p.at)==null?void 0:x.call(p,-1))==null?void 0:j.timestamp)||0)>=n.startedAt-5e3});if(!l)return;const u=sc({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 ah({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:i}){const c=o.useCallback(async(m,w)=>rn(e,m,w),[e]),l=o.useCallback(async(m,w)=>{if(!w.trim())return{ok:!1,error:"Choose a workspace path first."};try{const S=await e(m,"workspace_add",{path:w.trim()});return S!=null&&S.success?{ok:!0}:{ok:!1,error:(S==null?void 0:S.error)||"Could not save workspace"}}catch(S){return{ok:!1,error:S instanceof Error?S.message:"Could not save workspace"}}},[e]),u=o.useCallback(async(m,w,S)=>{var p;try{const x={ideType:w,enableCdp:!0};(p=S==null?void 0:S.workspacePath)!=null&&p.trim()&&(x.workspace=S.workspacePath.trim());const j=await e(m,"launch_ide",x);return!(j!=null&&j.success)&&(j==null?void 0:j.success)!==void 0?{ok:!1,error:(j==null?void 0:j.error)||"Could not launch IDE"}:(t({machineId:m,kind:"ide",providerType:w,workspacePath:(S==null?void 0:S.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,w,S,p)=>{var j,b,N;const x=Date.now();try{const T={cliType:S};(j=p==null?void 0:p.workspacePath)!=null&&j.trim()?T.dir=p.workspacePath.trim():p!=null&&p.workspaceId&&(T.workspaceId=p.workspaceId),(b=p==null?void 0:p.resumeSessionId)!=null&&b.trim()&&(T.resumeSessionId=p.resumeSessionId.trim()),Array.isArray(p==null?void 0:p.cliArgs)&&p.cliArgs.length>0&&(T.cliArgs=p.cliArgs),(N=p==null?void 0:p.initialModel)!=null&&N.trim()&&(T.initialModel=p.initialModel.trim());const y=await e(m,"launch_cli",T),C=(y==null?void 0:y.result)||y,k=(C==null?void 0:C.sessionId)||(C==null?void 0:C.id);return y!=null&&y.success&&k?(r(k),{ok:!0}):y!=null&&y.success?(t({machineId:m,kind:w,providerType:S,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)||(C==null?void 0:C.error)||`Could not launch ${w.toUpperCase()} session`}}catch(T){return rh(T)?(t({machineId:m,kind:w,providerType:S,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:x}),{ok:!0}):{ok:!1,error:T instanceof Error?T.message:`Could not launch ${w.toUpperCase()} session`}}},[r,e,t]),d=o.useCallback(async(m,w)=>{if(!m||!w)return[];try{const S=await e(m,"list_saved_sessions",{providerType:w,kind:"cli",limit:30}),p=(S==null?void 0:S.result)??S;return Array.isArray(p==null?void 0:p.sessions)?p.sessions:[]}catch(S){return console.error("List saved sessions failed",S),[]}},[e]),h=o.useCallback(async m=>{await Kc({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 oh(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 ih(e,t,r=Date.now()){return!e||!oh(t)?null:{tabKey:e,nonce:r}}function ch({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,j;if(!e){if(l){const b=t.find(N=>N.tabKey===l);if(b)return b}return r[0]}const p=n[a];if(p){const b=t.find(N=>N.tabKey===p);if(b)return b}return((x=i[a])==null?void 0:x[0])||((j=i[0])==null?void 0:j[0])},[t,l,a,n,i,e,r]),m=o.useCallback(p=>{u(p)},[]),w=o.useCallback(p=>{u(p.tabKey),c(x=>{const j=new URLSearchParams(x),b=cm(p);return b?j.set("activeTab",b):j.delete("activeTab"),j},{replace:!0})},[c]),S=o.useCallback((p,x)=>{const j=ih(p,x);j&&d(j)},[]);return{activeConv:h,openDesktopConversation:w,requestScrollToBottom:S,scrollToBottomRequest:f,setDesktopActiveTab:m}}function lh({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:i,setToasts:c,setClearedTabs:l,setSearchParams:u}){var L;const[f,d]=o.useState(!1),[h,m]=o.useState([]),[w,S]=o.useState(()=>ht()),[p,x]=o.useState(!1),[j,b]=o.useState(null),N=o.useRef(null),T=o.useMemo(()=>r||t||e,[e,r,t]),y=!!T&&Je(T)&&!qe(T),C=o.useMemo(()=>{if(!T||!y)return null;const R=T.daemonId||T.routeId||"",G=Kt(T);return`${R}:${G}`},[T,y]),{isCreatingChat:k,isRefreshingHistory:v,handleSwitchSession:g,handleNewChat:D,handleRefreshHistory:M}=Uc({sendDaemonCommand:a,activeConv:T,chats:(L=n.find(R=>R.id===(T==null?void 0:T.routeId)))==null?void 0:L.chats,updateRouteChats:i,setToasts:c,setClearedTabs:l}),I=o.useCallback(()=>{d(!0)},[]),P=o.useCallback(()=>{d(!1)},[]),K=o.useCallback(async()=>{if(!(!T||!y||p)){x(!0);try{const R=T.daemonId||T.routeId,G=Kt(T),B=await a(R,"list_saved_sessions",{agentType:G,providerType:G,kind:"cli",limit:50}),E=(B==null?void 0:B.result)??B;m(Array.isArray(E==null?void 0:E.sessions)?E.sessions:[])}catch(R){console.error("Refresh saved sessions failed",R),m([])}finally{x(!1)}}},[T,p,y,a]);o.useEffect(()=>{if(!f){N.current=null;return}if(!y){N.current=null,m([]),x(!1);return}!C||p||N.current!==C&&(N.current=C,K())},[K,f,p,y,C]);const V=o.useCallback(async R=>{if(!T||!y||!R.providerSessionId||!R.workspace)return;const G=T.daemonId||T.routeId,B=Kt(T);try{b(R.providerSessionId);const E=await a(G,"launch_cli",{cliType:B,dir:R.workspace,resumeSessionId:R.providerSessionId,initialModel:Hi(R.summaryMetadata,"model",{preferShortValue:!0})||void 0}),W=(E==null?void 0:E.result)??E,J=typeof(W==null?void 0:W.sessionId)=="string"?W.sessionId:typeof(W==null?void 0:W.id)=="string"?W.id:"";J&&u(be=>{const he=new URLSearchParams(be);return he.set("activeTab",J),he},{replace:!0}),P()}catch(E){console.error("Resume saved session failed",E)}finally{b(null)}},[P,T,y,a,u]);return{historyModalOpen:f,openHistoryModal:I,closeHistoryModal:P,historyTargetConv:T,isSavedSessionHistoryTarget:y,isHistoryCreatingChat:k,isHistoryRefreshingHistory:v,handleHistorySwitchSession:g,handleHistoryNewChat:D,handleHistoryRefresh:M,savedHistorySessions:h,savedHistoryFilters:w,setSavedHistoryFilters:S,isSavedHistoryLoading:p,resumingSavedHistorySessionId:j,handleRefreshSavedHistory:K,handleResumeSavedHistorySession:V}}function dh({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 j=l(n);return j&&!Je(j)&&!qe(j)?j:null},[e,n,l]),w=o.useMemo(()=>{const j=u==null?void 0:u.routeId;if(!j)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)===j?b:_t(i,j)},[i,u,a]),S=o.useMemo(()=>{if(w)return c.find(j=>j.id===w.routeId)},[c,w]);o.useEffect(()=>{m&&(f({routeId:m.routeId,tabKey:So(m)}),h(m),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,m]);const p=o.useCallback(j=>{j&&(f({routeId:j.routeId,tabKey:So(j)}),h(j))},[]),x=o.useCallback(()=>{f(null),h(null)},[]);return{remoteDialogConv:w,remoteDialogIdeEntry:S,remoteDialogActiveConv:d,setRemoteDialogActiveConv:h,openRemoteDialog:p,closeRemoteDialog:x}}function uh({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:w,openRemoteDialog:S,closeRemoteDialog:p}=dh({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}),[x,j]=o.useState(!1),[b,N]=o.useState(null),T=o.useCallback(async k=>{const v=k||u;!v||!Je(v)&&!qe(v)||(N(v),j(!0))},[u]),y=o.useCallback(()=>{j(!1),N(null)},[]),C=o.useCallback(async k=>{const v=b||u;if(!v||!Je(v)&&!qe(v)){y();return}j(!1);try{const g=Kt(v),D=v.routeId||v.daemonId||"";await f(D,"stop_cli",{cliType:g,targetSessionId:v.sessionId,mode:k})}catch(g){console.error("Stop CLI failed:",g)}finally{N(null)}},[u,y,b,f]);return{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:m,setRemoteDialogActiveConv:w,openRemoteDialog:S,closeRemoteDialog:p,cliStopDialogOpen:x,cliStopTargetConv:b,requestCliStop:T,cancelCliStop:y,confirmCliStop:C}}function Vc(){return"select_session"}function mh(){return"open_panel"}function fh({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function ph(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function Uo(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 Fa(e){return e instanceof Error?e.message:String(e||"")}function Vo(e){const t=Fa(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Go(e,t){const r=Fa(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function nn({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,i]=o.useState(!1),[c,l]=o.useState(!1),[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 j=x.trim(),b=Aa(t);if(fh({hasMessage:!!j,blockedMessage:b,sendInFlight:d.current}))return b&&f(b),!1;const N=Date.now(),T={tabKey:t.tabKey,message:j,timestamp:N};if(ph(h.current,T))return f(null),!0;d.current=!0,l(!0),f(null),h.current=T;try{const y=Js(t);if(!y)return h.current=Uo(h.current,T),f("Unable to send message right now."),!1;const C=await e(y,"send_chat",{message:j,...js(t)}),k=zo(C);if(k!=null&&k.deduplicated)return f(null),!0;if((k==null?void 0:k.sent)===!1)throw new Error((k==null?void 0:k.error)||"Send failed");if((k==null?void 0:k.success)===!1)throw new Error((k==null?void 0:k.error)||"Send failed");return f(null),!0}catch(y){const C=Fa(y);return C.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",C):console.warn("Send blocked/failed",y),h.current=Uo(h.current,T),f(Am(y)),!1}finally{d.current=!1,l(!1)}},[t,e]),w=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]),S=o.useCallback(async x=>{if(t)try{const b=(t.modalButtons||[]).indexOf(x),N=x.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),T=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(N),y=Js(t);if(!y)return;const C=await e(y,"resolve_action",{button:x,action:T?"approve":"reject",...b>=0&&{buttonIndex:b},...js(t)}),k=zo(C);k.success||r(v=>[...v,{routeId:t.tabKey,text:Go(x,k==null?void 0:k.error),timestamp:Date.now()}])}catch(j){Vo(j)||console.error("[ModalButton] Error:",j),r(b=>[...b,{routeId:t.tabKey,text:Vo(j)?Go(x,j):`❌ **${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:w,handleModalButton:S,handleFocusAgent:p}}function In(e,t=!0){return(e??!0)&&t}const Ua=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:w,userName:S,scrollToBottomRequestNonce:p,isInputActive:x=!0,isVisible:j=!0}){const[b,N]=o.useState(n),T=o.useRef(n);o.useEffect(()=>{const I=T.current;if(T.current=n,!n){N(!1);return}if(I){N(!0);return}N(!1);let P=0,K=0;return P=window.requestAnimationFrame(()=>{K=window.requestAnimationFrame(()=>{N(!0)})}),()=>{window.cancelAnimationFrame(P),window.cancelAnimationFrame(K)}},[n]);const y=n&&b,C=!n||!b,k=In(j,n),v=In(j,C),g=In(j),D=_c(t),M=D.status||D.modalMessage||D.modalButtons?{...t,...D.status?{status:D.status}:{},...D.modalMessage!==void 0?{modalMessage:D.modalMessage}:{},...D.modalButtons!==void 0?{modalButtons:D.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx($i,{activeConv:M,onModalButton:c}),M.transport!=="pty"&&M.transport!=="acp"&&M.cdpConnected===!1?s.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:s.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[s.jsx("span",{className:"text-sm",children:s.jsx(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,M.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:y?"visible":"hidden",pointerEvents:y?"auto":"none"},children:s.jsx(tf,{activeConv:M,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,isVisible:k,isInputActive:x&&k})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:C?"visible":"hidden",pointerEvents:C?"auto":"none"},children:s.jsx(na,{activeConv:M,ideEntry:a,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:m,actionLogs:w,userName:S,scrollToBottomRequestNonce:p,isInputActive:x&&v,isVisible:v})})]}):s.jsx(na,{activeConv:M,ideEntry:a,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:m,actionLogs:w,userName:S,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 hh({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:w,onHideConversation:S,onStopCli:p,cliViewMode:x,onSetCliViewMode:j,handleSendChat:b,handleFocusAgent:N,handleModalButton:T,handleRelaunch:y}){const C=o.useRef(null),k=Je(e)&&!t,v=k&&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(xa,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:tt(e)}),s.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:s.jsx(rc,{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:[k&&x&&s.jsx(Ta,{mode:x,onChange:j,compact:!0}),k&&p&&s.jsx("button",{onClick:()=>{p(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(wt,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>m(e),type:"button",children:s.jsx(ba,{size:14})}),!t&&!k&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>w(e),type:"button",children:s.jsx(Ct,{size:14})}),S&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(e),type:"button",title:"Close chat",children:s.jsx(wt,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(Ua,{activeConv:e,clearToken:0,isCliTerminal:v,ideEntry:n,terminalRef:C,handleModalButton:T,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 xh(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Gc(){const[e,t]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{t(xh())},[]);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 qc({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Ct},{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 wr({title:e,className:t=""}){return s.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${t}`,children:s.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function hs({children:e,className:t=""}){return s.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${t}`,children:e})}function Ds({icon:e,title:t,subtitle:r,children:n}){return s.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[s.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function jr({item:e,type:t,getAvatarText:r,onOpenConversation:n}){const a=t==="needs_attention"||t==="task_complete",i=t==="working",c=t==="earlier",l=t==="task_complete",{isReconnecting:u,isConnecting:f}=Ms(e.conversation),d=tt(e.conversation),h=us(e.conversation),m=mc(e.conversation,{requiresAction:t==="needs_attention"}),w=a?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":i?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",S=a?"bg-accent-primary shadow-glow":i?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":c?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",p=c?"text-text-secondary":"text-text-primary",x=c?"text-text-muted":"text-text-secondary",j=c?"text-text-secondary opacity-80":"text-text-muted",b=c?"text-text-muted opacity-80":"text-text-muted",N="text-[color:var(--status-warning)]";return s.jsxs("button",{className:`group flex items-start gap-3.5 px-4 py-3.5 w-full text-left relative overflow-hidden transition-colors active:scale-[0.995] ${w}`,onClick:()=>n(e.conversation),type:"button",children:[a||i?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${S}`,style:a?{color:"var(--accent-on-primary)"}:void 0,children:r(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:Ei(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] ${j}`,children:e.preview})]}),a&&!l&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),l&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Done"}),i&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Live"})]},e.conversation.tabKey)}function qo({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 bh({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:w,onSectionChange:S,wsStatus:p="connected",isStandalone:x=!1}){const j=p==="disconnected"||p==="reconnecting"||p==="offline"||p==="auth_failed",b=c.length>0,N=t.length>0||r.length>0||n.length>0||a.length>0,T=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",C=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:T}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||r.length>0)&&s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[s.jsx(Xr,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:w,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:s.jsx(Yr,{size:18})})]})]})}),s.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${C}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:j?s.jsx(Ds,{icon:s.jsx(qo,{label:"Reconnecting…"}),title:"Connecting to server",subtitle:p==="offline"?"Your device appears to be offline. Waiting for network…":p==="auth_failed"?"Session expired. Please log in again.":"Establishing connection to the server. This usually takes a moment."}):c.length===0?s.jsx(Ds,{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(Gc,{})})}):s.jsx(hs,{children:c.map((k,v)=>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] ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>m(k.id),type:"button",children:[s.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:l(k.label)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:k.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:k.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[k.unread," new"]}):k.total>0?`${k.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:k.subtitle}),k.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[k.total," chat",k.total!==1?"s":"",k.unread>0?` · ${k.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},k.id))})}),e==="chats"&&t.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(wr,{title:"Needs attention",className:"mb-0"}),s.jsx(hs,{children:t.map((k,v)=>s.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"needs_attention",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))})]}),e==="chats"&&r.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(wr,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(hs,{children:r.map((k,v)=>s.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"task_complete",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))})]}),e==="chats"&&n.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(wr,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(hs,{children:n.map((k,v)=>s.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"working",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&s.jsx(wr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(hs,{children:a.map((k,v)=>s.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"earlier",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))}):N?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):j?s.jsx(Ds,{icon:s.jsx(qo,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):b?s.jsx(Ds,{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:hc,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":$t,title:$t,children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s.jsx("span",{children:$t})]})}):s.jsx(Ds,{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((k,v)=>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 ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(k),type:"button",children:[s.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-bg-primary border border-border-subtle text-text-secondary",children:l(tt(k))}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:tt(k)}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:us(k)}),s.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},k.tabKey))})]})]}),e==="chats"&&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":$t,title:$t,children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),s.jsx(qc,{section:e,onSectionChange:S})]})}function gh(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 Yc(e){const t=[e.workspace||"Workspace unknown"],r=ds(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=gh(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function an({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:u,onConfirm:f}){const[d,h]=o.useState(r);o.useEffect(()=>{h(r)},[r]);const m=eh(r),w=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(wt,{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(xa,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:d,onChange:S=>h(S.target.value),onKeyDown:S=>{S.key!=="Enter"||!w||a||(S.preventDefault(),u(w))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!w||a||u(w)},disabled:!w||a,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):i?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):n.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:n.map(S=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>u(S.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Ss,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:S.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:S.path})]})]},S.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>f(w||r),disabled:!w&&!r||a,children:c})]})]})})}function za({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:w,onModelChange:S,historyProviderNode:p,onConfirm:x,onCancel:j}){const b=n==null?void 0:n.find(N=>N.key===a);return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:j,"aria-label":"Close launch confirmation",children:s.jsx(wt,{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&&S&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),s.jsx("input",{type:"text",value:w||"",onChange:N=>S(N.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled: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:j,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(ya,{size:14}),u?l:c]})]})]})})}function Yo(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function os(e){const{machine:t,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,i=[];a&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const u of t.workspaces||[])i.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${Yo(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:Yo(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 yh(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function vh(e){return[yh(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function wh(e){return e.lastLaunchedAt?Jr(e.lastLaunchedAt):""}function Xc(e){return{metaText:vh(e),updatedLabel:wh(e)}}function Mn(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function jh({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var ut,mt,Xe,rt;const c=nr(),[l,u]=o.useState(!1),f=(((ut=e.detectedIdes)==null?void 0:ut.length)||0)>0,d=o.useMemo(()=>(e.workspaces||[]).map(je=>({id:je.id,path:je.path,label:je.label})),[e]),h=e.defaultWorkspaceId||null,[m,w]=o.useState(h||((mt=d[0])==null?void 0:mt.id)||""),[S,p]=o.useState(""),[x,j]=o.useState(""),[b,N]=o.useState([]),[T,y]=o.useState(!1),[C,k]=o.useState(""),[v,g]=o.useState(!1),[D,M]=o.useState(Mn(f,t.length,r.length)),I=o.useRef(null),[P,K]=o.useState(null),V=o.useRef("__home__"),[L,R]=o.useState("__home__"),[G,B]=o.useState(""),[E,W]=o.useState(""),[J,be]=o.useState(""),[he,de]=o.useState([]),[ye,ge]=o.useState(()=>ht().textQuery),[ve,z]=o.useState(()=>ht().workspaceQuery),[F,Q]=o.useState(()=>ht().modelQuery),[ue,te]=o.useState(()=>ht().resumableOnly),[fe,ne]=o.useState(()=>ht().sortMode),[xe,re]=o.useState(!1),[le,oe]=o.useState(!1),Y=o.useRef(null),X=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const ae=m==="__custom__"?S.trim():((Xe=d.find(je=>je.id===m))==null?void 0:Xe.path)||"",A=m==="__custom__"&&!!ae&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),H=m!=="__custom__"&&((rt=d.find(je=>je.id===m))==null?void 0:rt.path)||"",ce=o.useMemo(()=>(e.recentLaunches||[]).map(je=>je.workspace),[e]),me=o.useCallback(async je=>{y(!0),k("");try{const Ee=await a(je);j(Ee.path),p(Ee.path),N(Ee.directories)}catch(Ee){k(Ee instanceof Error?Ee.message:"Could not load folder")}finally{y(!1)}},[a]),we=o.useCallback(()=>{var Ee;w("__custom__"),g(!0);const je=sn(e.platform,tn(S.trim(),H,ce,e.defaultWorkspacePath,(Ee=d.find(Be=>Be.id===h))==null?void 0:Ee.path,d.map(Be=>Be.path)));me(je)},[S,h,me,ce,H,e.platform,d]),_e=o.useCallback(je=>{if(je!=null&&je.workspaceId){w(je.workspaceId),p("");return}if(je!=null&&je.workspacePath){w("__custom__"),p(je.workspacePath);return}w(""),p("")},[]),Ae=o.useCallback(je=>{if(w(je),je==="__custom__"){we();return}p("")},[we]),Ke=o.useCallback(je=>{w("__custom__"),p(je)},[]),Fe=o.useCallback((je,Ee)=>{I.current=Ee,V.current=je.selectedWorkspaceKey||"__home__",R(je.selectedWorkspaceKey||"__home__"),B(je.initialArgs||""),W(je.initialModel||""),be(""),de([]);const Be=je.providerType?`${e.id}:${je.providerType}`:null;if(lf(X.current,Be)){const nt=ht();ge(nt.textQuery),z(nt.workspaceQuery),Q(nt.modelQuery),te(nt.resumableOnly),ne(nt.sortMode)}X.current=Be,K(je),je.providerType&&i&&(re(!0),i(je.providerType).then(nt=>de(nt||[])).catch(nt=>console.warn("Failed to load saved sessions",nt)).finally(()=>re(!1)))},[i,e.id]),ze=o.useMemo(()=>xc(he,{textQuery:ye,workspaceQuery:ve,modelQuery:F,resumableOnly:ue,sortMode:fe}),[F,ue,he,fe,ye,ve]);o.useEffect(()=>{J&&(ze.some(je=>je.providerSessionId===J)||be(""))},[ze,J]);const ot=o.useCallback(()=>{I.current&&(oe(!0),I.current().finally(()=>{I.current=null,oe(!1),K(null)}))},[]),it=o.useCallback(()=>{I.current=null,K(null)},[]),dt=o.useCallback(je=>{V.current=je,R(je)},[]);return o.useEffect(()=>{var je;Y.current!==e.id&&(Y.current=e.id,w(h||((je=d[0])==null?void 0:je.id)||"__custom__"),p(""),j(""),N([]),k(""),g(!1),ge(ht().textQuery),z(ht().workspaceQuery),Q(ht().modelQuery),te(ht().resumableOnly),ne(ht().sortMode),X.current=null,M(Mn(f,t.length,r.length)))},[r.length,t.length,h,f,e.id,d]),o.useEffect(()=>{var je;m!=="__custom__"&&(m&&d.some(Ee=>Ee.id===m)||w(h||((je=d[0])==null?void 0:je.id)||"__custom__"))},[h,m,d]),o.useEffect(()=>{D==="ide"&&f||D==="cli"&&t.length>0||D==="acp"&&r.length>0||M(Mn(f,t.length,r.length))},[D,r.length,t.length,f]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:f,workspaceRows:d,defaultWorkspaceId:h,workspaceChoice:m,customWorkspacePath:S,browseCurrentPath:x,browseDirectories:b,browseBusy:T,browseError:C,browseDialogOpen:v,activeLauncherKind:D,launchConfirm:P,launchConfirmWorkspaceKeyRef:V,launchConfirmWorkspaceKey:L,launchConfirmArgs:G,launchConfirmModel:E,launchConfirmResumeId:J,launchConfirmSavedSessions:he,launchConfirmTextFilter:ye,launchConfirmWorkspaceFilter:ve,launchConfirmModelFilter:F,launchConfirmResumableOnly:ue,launchConfirmSortMode:fe,filteredLaunchConfirmSavedSessions:ze,launchConfirmSessionsLoading:xe,launchConfirmBusy:le,resolvedWorkspacePath:ae,canCreateMissingWorkspace:A,openBrowseDialog:we,loadBrowsePath:me,handleWorkspaceChoiceChange:Ae,chooseCustomWorkspacePath:Ke,setCustomWorkspacePath:p,setBrowseDialogOpen:g,setActiveLauncherKind:M,openLaunchConfirm:Fe,handleConfirmLaunch:ot,closeLaunchConfirm:it,setWorkspaceSelectionFromOption:_e,setLaunchConfirmWorkspaceKeyAndSync:dt,setLaunchConfirmArgs:B,setLaunchConfirmModel:W,setLaunchConfirmResumeId:be,setLaunchConfirmTextFilter:ge,setLaunchConfirmWorkspaceFilter:z,setLaunchConfirmModelFilter:Q,setLaunchConfirmResumableOnly:te,setLaunchConfirmSortMode:ne}}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:w,onOpenRecent:S,onOpenMachineDetails:p,onMachineUpgrade:x,onLaunchDetectedIde:j,onAddWorkspace:b,onBrowseDirectory:N,onLaunchWorkspaceProvider:T,onListSavedSessions:y}){const C=L=>L==="ide"?"IDE":L==="cli"?"CLI":"ACP",k=r.slice(0,4),v=t.slice(0,3),g=jh({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:N,onListSavedSessions:y}),D=o.useMemo(()=>k.map(L=>{const{metaText:R,updatedLabel:G}=Xc(L);return{key:`recent-launch:${L.id}`,primary:L.label,secondary:R,updatedLabel:G,onClick:()=>{const{options:B,selectedKey:E}=os({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspacePath:L.workspace});g.openLaunchConfirm({title:L.kind==="ide"?ss("restart-ide",L.label):L.providerSessionId?Pa(L.label):ss("start-fresh",L.label),description:L.kind==="ide"?rs("restart-ide"):L.providerSessionId?_a():rs("start-fresh"),confirmLabel:L.kind==="ide"?Cs("restart-ide"):L.providerSessionId?Ur(!0):Cs("start-fresh"),busyLabel:L.kind==="ide"?Is("restart-ide"):L.providerSessionId?La(!0):Is("start-fresh"),workspaceOptions:B,selectedWorkspaceKey:E,details:[{label:"Mode",value:C(L.kind)},...L.providerType?[{label:"Provider",value:L.providerType}]:[]]},async()=>{const W=B.find(J=>J.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(W),await S({...L,workspace:(W==null?void 0:W.workspacePath)??null})})}}}),[g,S,k]),M=o.useMemo(()=>v.map(L=>({key:`recent-chat:${L.conversation.tabKey}`,primary:tt(L.conversation),secondary:Jm(L.conversation,{timestampLabel:L.timestamp?Ei(L.timestamp):null}),unread:L.unread,onClick:()=>w(L.conversation)})),[w,v]),I=g.showAllRecent?D:D.slice(0,4),P=D.length>0,K=M.length>0,V=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 ${V} 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(xa,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children: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:[K&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:M.map(L=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${L.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:L.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:L.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:L.secondary})]},L.key))})]}),P&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:I.map(L=>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:L.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:L.primary}),L.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:L.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:L.secondary})]},L.key))}),D.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(L=>!L),children:g.showAllRecent?"Show fewer":`Show ${D.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:L=>g.handleWorkspaceChoiceChange(L.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(L=>s.jsxs("option",{value:L.id,children:[L.id===g.defaultWorkspaceId?"⭐ ":"",Zr(L.path,L.label)||L.path]},L.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(Ss,{size:17})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),s.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children: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(L=>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:R,selectedKey:G}=os({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspaceId:g.workspaceChoice!=="__custom__"?g.workspaceChoice:null,currentWorkspacePath:g.resolvedWorkspacePath});g.openLaunchConfirm({title:`Launch ${L.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:R,selectedWorkspaceKey:G,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:L.name}]},async()=>{const B=R.find(E=>E.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(B),j(L.type,{workspacePath:(B==null?void 0:B.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:L.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:g.resolvedWorkspacePath||"Use selected workspace"})]},L.type)):(g.activeLauncherKind==="cli"?n:a).map(L=>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 R=g.activeLauncherKind==="cli"?"cli":"acp",{options:G,selectedKey:B}=os({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspaceId:g.workspaceChoice!=="__custom__"?g.workspaceChoice:null,currentWorkspacePath:g.resolvedWorkspacePath});g.openLaunchConfirm({title:`Launch ${L.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${R.toUpperCase()}`,workspaceOptions:G,selectedWorkspaceKey:B,details:[{label:"Mode",value:R.toUpperCase()},{label:"Provider",value:L.displayName}],showArgsInput:!0,showModelInput:R==="acp",initialArgs:"",initialModel:"",providerType:L.type},async()=>{const E=G.find(W=>W.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(E),T(R,L.type,{workspaceId:(E==null?void 0:E.workspaceId)??null,workspacePath:(E==null?void 0:E.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:[L.icon?`${L.icon} `:"",L.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:g.resolvedWorkspacePath||"Use selected workspace"})]},L.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(an,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:g.browseCurrentPath,directories:g.browseDirectories,busy:g.browseBusy,error:g.browseError,confirmLabel:"Use this folder",onClose:()=>g.setBrowseDialogOpen(!1),onNavigate:L=>{g.loadBrowsePath(L)},onConfirm:L=>{g.chooseCustomWorkspacePath(L),g.setBrowseDialogOpen(!1)}}),g.launchConfirm&&s.jsx(za,{title:g.launchConfirm.title,description:g.launchConfirm.description,details:g.launchConfirm.details,workspaceOptions:g.launchConfirm.workspaceOptions,selectedWorkspaceKey:g.launchConfirmWorkspaceKey,onWorkspaceChange:g.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:g.launchConfirm.providerType?Ur(!!g.launchConfirmResumeId):g.launchConfirm.confirmLabel,busyLabel:g.launchConfirm.providerType?void 0:g.launchConfirm.busyLabel,busy:g.launchConfirmBusy,showArgsInput:g.launchConfirm.showArgsInput,argsValue:g.launchConfirmArgs,onArgsChange:g.setLaunchConfirmArgs,showModelInput:g.launchConfirm.showModelInput,modelValue:g.launchConfirmModel,onModelChange:g.setLaunchConfirmModel,historyProviderNode:g.launchConfirm.providerType&&(g.launchConfirmSessionsLoading||g.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),g.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:Ra()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:g.launchConfirmTextFilter,onChange:L=>g.setLaunchConfirmTextFilter(L.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:L=>g.setLaunchConfirmWorkspaceFilter(L.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:L=>g.setLaunchConfirmModelFilter(L.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:L=>g.setLaunchConfirmSortMode(L.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:L=>g.setLaunchConfirmResumableOnly(L.target.checked),disabled:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:g.launchConfirmResumeId,onChange:L=>g.setLaunchConfirmResumeId(L.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(L=>s.jsxs("option",{value:L.providerSessionId,disabled:!L.canResume,children:[L.title||L.providerSessionId," ",L.canResume?"":"(workspace missing)"]},L.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 L=g.filteredLaunchConfirmSavedSessions.find(G=>G.providerSessionId===g.launchConfirmResumeId);if(!L)return null;const R=Yc(L);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:R.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:R.providerSessionId}),s.jsx("div",{className:"mt-1",children:R.metaLine}),R.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:R.updatedLabel}),R.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:R.preview})]})})()]}),onConfirm:g.handleConfirmLaunch,onCancel:g.closeLaunchConfirm}),d&&s.jsx(qc,{section:f,onSectionChange:m})]})}function Sh(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 Nh(e,t){if(!e)return[];const r=e.recentLaunches||[];return r.length>0?r.map(n=>({id:n.id,label:n.title||n.providerName||n.providerType,kind:n.kind,providerType:n.providerType,providerSessionId:n.providerSessionId,subtitle:ds(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):t.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var c,l,u,f,d;const a=Xs(n)?"cli":ys(n)?"acp":"ide",i=ds(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(Xs(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 Ch(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=Jn(n),u=a.filter(h=>h.unread||h.requiresAction).length,f=Sh(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?Qm(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 Ih(e){return e==="chat"}function kr(e,t){var r;if(!(typeof window>"u"))try{if(!(!!((r=import.meta.env)!=null&&r.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,t)}catch{}}function Ah({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:w,setSelectedTabKey:S,setScreen:p,setSelectedMachineId:x,setSection:j,setMachineBackTarget:b,resetMachineAction:N}){const T=o.useRef(null),y=o.useCallback(C=>{if(!(C!=null&&C.sessionId))return;const k=Or(C,c),v=Math.max(Date.now(),es(C),k.lastUpdated||0);kr("mark_read:start",{tabKey:C.tabKey,sessionId:C.sessionId,displayPrimary:tt(C),inboxBucket:k.inboxBucket,unread:k.unread,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,activityAt:es(C),readAt:v}),l(fs(C)||C.routeId,"mark_session_seen",{sessionId:C.sessionId,seenAt:v}).then(g=>{kr("mark_read:result",{tabKey:C.tabKey,sessionId:C.sessionId,result:g})}).catch(g=>{kr("mark_read:error",{tabKey:C.tabKey,sessionId:C.sessionId,error:g instanceof Error?g.message:String(g)})})},[c,l]);return o.useEffect(()=>{var k;if(!n){Ih(i)&&p("inbox"),S(((k=e[0])==null?void 0:k.tabKey)||null),T.current=null;return}if(i!=="chat"){T.current=null;return}const C=`${n.tabKey}:${n.sessionId||""}`;T.current!==C&&(T.current=C,y(n))},[e,y,i,n,p,S]),o.useEffect(()=>{if(!u)return;const C=e.find(k=>k.tabKey===u);C&&(S(C.tabKey),p("chat"),f==null||f())},[e,f,u,p,S]),o.useEffect(()=>{if(!d)return;const C=t.find(k=>k.id===d);C&&(x(C.id),N(),j("machines"),b("inbox"),p("machine"),h==null||h())},[t,h,d,N,b,p,j,x]),o.useEffect(()=>{m&&(j(m),p("inbox"),w==null||w())},[w,m,p,j]),o.useEffect(()=>{const C=r.filter(k=>k.inboxBucket==="task_complete"||k.unread);C.length!==0&&kr("inbox_state",{screen:i,selectedTabKey:a,items:C.map(k=>{const v=Or(k.conversation,c);return{liveState:v,tabKey:k.conversation.tabKey,sessionId:k.conversation.sessionId,displayPrimary:tt(k.conversation),serverBucket:v.inboxBucket,computedBucket:k.inboxBucket,serverUnread:v.unread,computedUnread:k.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,activityAt:es(k.conversation)}})})},[r,c,i,a]),{markConversationRead:y}}function Mh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Xo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Th(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Lh({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,T)=>{var y;try{i("loading"),l(`Launching ${N}…`);const C={ideType:N,enableCdp:!0};(y=T==null?void 0:T.workspacePath)!=null&&y.trim()&&(C.workspace=T.workspacePath.trim()),await e(b,"launch_ide",C),i("done"),l(`${N} launch requested`)}catch(C){i("error"),l(C instanceof Error?C.message:"Launch IDE failed"),console.error("Launch IDE failed",C)}},[e]),m=o.useCallback(async(b,N,T)=>{if(N.trim())try{i("loading"),l(T!=null&&T.createIfMissing?"Creating folder…":"Saving workspace…");const y=await e(b,"workspace_add",{path:N.trim(),createIfMissing:(T==null?void 0:T.createIfMissing)===!0});if(y!=null&&y.success){i("done"),l(T!=null&&T.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]),w=o.useCallback(async b=>{var N,T,y,C,k,v;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${((T=g==null?void 0:g.result)==null?void 0:T.version)||"latest"}.`);return}if((y=g==null?void 0:g.result)!=null&&y.upgraded||(C=g==null?void 0:g.result)!=null&&C.success){i("done"),l(`Upgrade to v${((k=g==null?void 0:g.result)==null?void 0:k.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((v=g==null?void 0:g.result)==null?void 0:v.error)||"Upgrade failed")}catch(g){i("error"),l(g instanceof Error?g.message:"Upgrade failed")}},[e]),S=o.useCallback(async(b,N,T,y)=>{var v,g,D;const C=Date.now(),k={machineId:b,kind:N,providerType:T,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:C};try{i("loading"),l(`Launching ${T}…`),f(k);const M={cliType:T};(v=y==null?void 0:y.workspacePath)!=null&&v.trim()?M.dir=y.workspacePath.trim():y!=null&&y.workspaceId&&(M.workspaceId=y.workspaceId),y!=null&&y.resumeSessionId&&(M.resumeSessionId=y.resumeSessionId),(g=y==null?void 0:y.args)!=null&&g.trim()&&(M.cliArgs=y.args.trim().split(/\s+/).filter(Boolean)),(D=y==null?void 0:y.model)!=null&&D.trim()&&(M.initialModel=y.model.trim());const I=await e(b,"launch_cli",M),P=(I==null?void 0:I.result)||I,K=(P==null?void 0:P.sessionId)||(P==null?void 0:P.id);if(I!=null&&I.success&&K){f(null),i("done"),l(`${T} launched`),t(Gt(K));return}if(I!=null&&I.success){i("loading"),l(`${T} launch requested — waiting for session…`);return}f(null),i("error"),l((I==null?void 0:I.error)||(P==null?void 0:P.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(M){if(Th(M)){i("loading"),l(`${T} launch requested — waiting for session…`);return}f(null),i("error"),l(M instanceof Error?M.message:`Could not launch ${N.toUpperCase()} workspace`)}},[t,e]),p=o.useCallback(async(b,N)=>{try{const T=await e(b,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),y=(T==null?void 0:T.result)??T;return Array.isArray(y==null?void 0:y.sessions)?y.sessions:[]}catch(T){return console.error("Failed to list saved sessions on mobile:",T),[]}},[e]),x=o.useCallback(async(b,N)=>rn(e,b,N),[e]);o.useEffect(()=>{if(!u)return;const b=Xo(u.workspacePath),N=r.find(y=>{var M,I,P,K;if(!y||y.type==="adhdev-daemon"||Mh(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 V=Xo(y.workspace||y.runtimeWorkspaceLabel);return V?V===b:!1}return Number(y.lastUpdated||y._lastUpdate||y.timestamp||((K=(P=(I=(M=y.activeChat)==null?void 0:M.messages)==null?void 0:I.at)==null?void 0:P.call(I,-1))==null?void 0:K.timestamp)||0)>=u.startedAt-5e3});if(!N)return;const T=sc({entrySessionId:N.sessionId,entryInstanceId:N.instanceId,entryRouteId:N.id,conversations:n});T&&(f(null),i("done"),l(`${u.providerType} launched`),t(Gt(T)))},[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 j=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 S(b,N.kind,N.providerType,{workspacePath:N.workspace||null,resumeSessionId:N.providerSessionId||null})},[h,S]);return{machineAction:{state:a,message:c},resetMachineAction:d,handleLaunchDetectedIde:h,handleAddWorkspace:m,handleMachineUpgrade:w,handleLaunchWorkspaceProvider:S,handleListSavedSessions:p,handleBrowseDirectory:x,handleOpenRecent:j}}function Rh({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:f}){const d=o.useCallback(j=>{i(j.tabKey),c("chat"),n(j)},[n,c,i]),h=o.useCallback(j=>{const b=e.find(N=>N.routeId===j.routeId&&N.streamSource==="native");b&&(i(b.tabKey),c("chat"),n(b))},[e,n,c,i]),m=o.useCallback(()=>{n(t),c("inbox")},[n,t,c]),w=o.useCallback((j,b="inbox")=>{l(j),a(),u("machines"),f(b),c("machine")},[a,f,c,u,l]),S=o.useCallback(j=>{const b=fs(j);b&&w(b,"chat")},[w]),p=o.useCallback(()=>{a(),c(r)},[r,a,c]),x=o.useCallback(j=>{u(j),c("inbox")},[c,u]);return{openConversation:d,openNativeConversation:h,backFromConversation:m,openMachine:w,openConversationMachine:S,backFromMachine:p,changeMachineSection:x}}function Ph(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function Sr(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function _h({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:w,onOpenHistory:S,onOpenRemote:p,onStopCli:x,wsStatus:j,isConnected:b,onShowHiddenConversation:N,onShowAllHiddenConversations:T,onHideConversation:y,onOpenNewSession:C,liveSessionInboxState:k,setCliViewModeOverrides:v}){const[g,D]=o.useState(()=>{var H;return((H=e[0])==null?void 0:H.tabKey)||null}),[M,I]=o.useState(()=>e[0]?"chat":"inbox"),[P,K]=o.useState("chats"),[V,L]=o.useState(null),[R,G]=o.useState("inbox"),B=As(),E="0.9.22",W=o.useMemo(()=>e.find(H=>H.tabKey===g)||e[0]||null,[e,g]),J=o.useMemo(()=>W?r.find(H=>H.id===W.routeId):void 0,[r,W]),be=o.useMemo(()=>!W||qe(W)||!Je(W)?null:Ts(W),[W]),he=o.useMemo(()=>r.filter(H=>H.type==="adhdev-daemon").sort(wa),[r]),de=o.useMemo(()=>he.find(H=>H.id===V)||null,[he,V]),ye=nn({sendDaemonCommand:a,activeConv:W||void 0,setActionLogs:i,isStandalone:c}),ge=Lh({sendDaemonCommand:a,navigate:B,ides:r,conversations:e}),ve=o.useMemo(()=>e.map(H=>{const ce=M==="chat"&&(W==null?void 0:W.tabKey)===H.tabKey,me=Qr(H,k,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ce}),we=es(H),_e=uc(H);return{conversation:H,timestamp:we,preview:_e,unread:me.unread,requiresAction:me.requiresAction,isWorking:me.isWorking,inboxBucket:me.inboxBucket}}),[e,k,M,W]),{markConversationRead:z}=Ah({conversations:e,machineEntries:he,items:ve,selectedConversation:W,selectedTabKey:g,screen:M,liveSessionInboxState:k,sendDaemonCommand:a,requestedActiveTabKey:u,onRequestedActiveTabConsumed:f,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:m,onRequestedMobileSectionConsumed:w,setSelectedTabKey:D,setScreen:I,setSelectedMachineId:L,setSection:K,setMachineBackTarget:G,resetMachineAction:ge.resetMachineAction}),F=Rh({conversations:e,selectedConversation:W,machineBackTarget:R,markConversationRead:z,resetMachineAction:ge.resetMachineAction,setSelectedTabKey:D,setScreen:I,setSelectedMachineId:L,setSection:K,setMachineBackTarget:G}),Q=o.useMemo(()=>Sr(ve.filter(H=>H.requiresAction)),[ve]),ue=o.useMemo(()=>Sr(ve.filter(H=>H.unread&&!H.requiresAction)),[ve]),te=o.useMemo(()=>Sr(ve.filter(H=>!H.unread&&!H.requiresAction&&H.isWorking)),[ve]),fe=o.useMemo(()=>Sr(ve.filter(H=>!H.unread&&!H.requiresAction&&!H.isWorking)),[ve]),ne=o.useMemo(()=>de?ve.filter(H=>fs(H.conversation)===de.id):[],[ve,de]),xe=o.useMemo(()=>Nh(de,r),[r,de]),re=(de==null?void 0:de.version)||null,le=!!de&&!!re&&!0&&re!==E,oe=o.useMemo(()=>(de==null?void 0:de.availableProviders)||[],[de]),Y=o.useMemo(()=>oe.filter(H=>H.category==="cli"&&H.installed!==!1).map(H=>({type:H.type,displayName:H.displayName||H.type,icon:H.icon})),[oe]),X=o.useMemo(()=>oe.filter(H=>H.category==="acp"&&H.installed!==!1).map(H=>({type:H.type,displayName:H.displayName||H.type,icon:H.icon})),[oe]),ae=o.useMemo(()=>Ch(he,ve),[ve,he]),A=o.useCallback(async H=>{de&&await ge.handleOpenRecent(de.id,H)},[ge,de]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:M==="chat"&&W?s.jsx(hh,{selectedConversation:W,isAcp:qe(W),isStandalone:c,selectedIdeEntry:J,actionLogs:n,userName:l,isSendingChat:ye.isSendingChat,sendFeedbackMessage:ye.sendFeedbackMessage,isFocusingAgent:ye.isFocusingAgent,handleModalButton:ye.handleModalButton,handleRelaunch:ye.handleRelaunch,onBack:F.backFromConversation,onOpenNativeConversation:F.openNativeConversation,onOpenMachine:F.openConversationMachine,onHideConversation:y,onOpenHistory:S,onOpenRemote:p,onStopCli:x,cliViewMode:be,onSetCliViewMode:async H=>{await Kc({conversation:W,mode:H,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:v})},handleSendChat:ye.handleSendChat,handleFocusAgent:ye.handleFocusAgent}):M==="machine"&&de?s.jsx(kh,{selectedMachineEntry:de,selectedMachineConversations:ne,selectedMachineRecentLaunches:xe,cliProviders:Y,acpProviders:X,selectedMachineNeedsUpgrade:le,appVersion:E,machineAction:ge.machineAction,isStandalone:c,section:P,showBottomNav:R==="inbox",onBack:F.backFromMachine,onSectionChange:F.changeMachineSection,onOpenConversation:F.openConversation,onOpenRecent:A,onOpenMachineDetails:()=>B(`/machines/${de.id}`),onMachineUpgrade:()=>ge.handleMachineUpgrade(de.id),onLaunchDetectedIde:(H,ce)=>ge.handleLaunchDetectedIde(de.id,H,ce),onAddWorkspace:(H,ce)=>ge.handleAddWorkspace(de.id,H,ce),onBrowseDirectory:H=>ge.handleBrowseDirectory(de.id,H),onLaunchWorkspaceProvider:(H,ce,me)=>ge.handleLaunchWorkspaceProvider(de.id,H,ce,me),onListSavedSessions:H=>ge.handleListSavedSessions(de.id,H)}):s.jsx(bh,{section:P,attentionItems:Q,unreadItems:ue,workingItems:te,completedItems:fe,hiddenConversations:t,machineCards:ae,getAvatarText:Ph,onOpenConversation:F.openConversation,onShowConversation:N,onShowAllHidden:T,onOpenNewSession:C,onOpenMachine:F.openMachine,onOpenSettings:()=>B("/settings"),onSectionChange:K,wsStatus:j,isConnected:b,isStandalone:c})})}function Tn(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function Dh({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))},[]),w=o.useCallback(x=>{if(!x.dataTransfer.types.includes("text/tab-key"))return;if(x.preventDefault(),!Tn(t,r)){d("merge");return}const j=x.currentTarget.getBoundingClientRect(),b=x.clientX-j.left,N=j.width/3;b<N?d("split-left"):b>N*2?d("split-right"):d("merge")},[t,r]),S=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 j=x.dataTransfer.getData("text/tab-key"),b=j?e.some(T=>T.tabKey===j):!1,N=f;if(d(null),i(),!!j){if(x.preventDefault(),N==="split-left"&&Tn(t,r)){r==null||r(j,"split-left");return}if(N==="split-right"&&Tn(t,r)){r==null||r(j,"split-right");return}if(b){a(j);return}n==null||n(j)}},[e,f,t,r,n,a,i]);return{dragOver:l,dropAction:f,resetDragState:h,handleDragEnter:m,handleDragOver:w,handleDragLeave:S,handleDrop:p}}function Eh(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 $h({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),w=o.useRef(n),S=o.useRef(a);o.useEffect(()=>{w.current=n},[n]),o.useEffect(()=>{S.current=a},[a]),o.useEffect(()=>{t&&t!==i&&c(t)},[t,i]),o.useEffect(()=>{u(k=>{const v=Eh(k,e);return v.length===k.length&&v.every((g,D)=>g===k[D])?k:v})},[e]);const p=o.useMemo(()=>{const k=f??l;if(k.length===0)return e;const v=new Map(k.map((g,D)=>[g,D]));return[...e].sort((g,D)=>{const M=v.get(g.tabKey)??999,I=v.get(D.tabKey)??999;return M-I})},[e,f,l]);o.useEffect(()=>{var v,g;if(p.length===0){i!==null&&(c(null),(v=w.current)==null||v.call(w,null));return}if(i&&p.some(D=>D.tabKey===i))return;const k=p[0].tabKey;k!==i&&(c(k),(g=w.current)==null||g.call(w,k))},[p,i]);const x=o.useMemo(()=>p.find(k=>k.tabKey===i),[p,i]),j=o.useCallback(k=>{var v;c(k),(v=w.current)==null||v.call(w,k)},[]),b=o.useCallback((k,v,g)=>{u(D=>{var K;const M=D.filter(V=>V!==k),I=M.indexOf(v);if(I<0)return D;const P=g==="left"?I:I+1;return M.splice(P,0,k),(K=S.current)==null||K.call(S,M),M}),d(null)},[]),N=o.useCallback((k,v,g)=>{const M=(l.length>0?l:e.map(K=>K.tabKey)).filter(K=>K!==k),I=M.indexOf(v);if(I<0)return;const P=g==="left"?I:I+1;M.splice(P,0,k),h.current=M,d(M)},[l,e]),T=o.useCallback(()=>{var v;const k=h.current;k&&(u(k),(v=S.current)==null||v.call(S,k))},[]),y=o.useCallback(()=>{h.current=null,d(null)},[]),C=o.useCallback(k=>{u(v=>{var D;const g=v.filter(M=>M!==k);return g.push(k),(D=S.current)==null||D.call(S,g),g})},[]);return{activeTabId:i,activeConv:x,sortedConversations:p,previewOrderRef:h,draggingTabRef:m,selectTab:j,handleTabReorder:b,updatePreviewOrder:N,commitPreviewOrder:T,clearPreviewOrder:y,moveTabToEnd:C,setDraggingTabKey:k=>{m.current=k}}}function Bh({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 Va({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?hc: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:$t,"aria-label":$t,children:[s.jsx(Ti,{size:14}),s.jsx("span",{children:$t})]})}),c&&s.jsx(Gc,{}),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 Jc="adhdev-tab-shortcuts";function Qc(){try{return JSON.parse(localStorage.getItem(Jc)||"{}")}catch{return{}}}function Zc({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>Qc()),[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(Jc,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 w=f(m);if(!w)return;const S={...i};for(const[p,x]of Object.entries(S))x===w&&delete S[p];S[l]=w,d(S),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[w,S]of Object.entries(i))if(t.includes(w)&&f(m)===S){m.preventDefault(),r(),n(w);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 Kh=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:w,onClearPreviewOrder:S,onDragStateReset:p,onDragTabKeyChange:x,onReceiveTab:j,onOpenContextMenu:b,longPressTimer:N,isGroupActive:T}){const y=Ms(t),C=y.isGenerating?"agent-tab-generating":y.isWaiting?"agent-tab-waiting":"",k=y.isReconnecting,v=o.useCallback(R=>{l.current=t.tabKey,x(t.tabKey),R.dataTransfer.setData("text/tab-key",t.tabKey),R.dataTransfer.effectAllowed="move"},[t.tabKey,l,x]),g=o.useCallback(()=>{l.current=null,x(null),w(),S(),p()},[l,x,w,S,p]),D=o.useCallback(R=>{const G=l.current;if(!(!G||G===t.tabKey)&&R.dataTransfer.types.includes("text/tab-key")){R.preventDefault(),R.stopPropagation();const B=R.currentTarget.getBoundingClientRect(),E=R.clientX<B.left+B.width/2?"left":"right";h(G,t.tabKey,E)}},[t.tabKey,l,h]),M=o.useCallback(R=>{R.preventDefault(),R.stopPropagation();const G=R.dataTransfer.getData("text/tab-key");if(G&&G!==t.tabKey){const B=R.currentTarget.getBoundingClientRect(),E=R.clientX<B.left+B.width/2?"left":"right";c.includes(G)?m(G,t.tabKey,E):j&&j(G)}S()},[t.tabKey,c,m,j,S]),I=o.useCallback(R=>{R.stopPropagation(),u(),f(t.tabKey),d(t)},[t,d,u,f]),P=o.useCallback(R=>{R.preventDefault(),b(R.clientX,R.clientY,t.tabKey)},[t.tabKey,b]),K=o.useCallback(R=>{const G=R.touches[0];N.current=setTimeout(()=>{b(G.clientX,G.clientY,t.tabKey)},600)},[t.tabKey,N,b]),V=o.useCallback(()=>{N.current&&clearTimeout(N.current)},[N]),L=["adhdev-dockview-tab",C,r&&"is-active",T&&"is-group-active",k&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:L,draggable:!0,onDragStart:v,onDragEnd:g,onDragOver:D,onDrop:M,onClick:I,onContextMenu:P,onTouchStart:K,onTouchEnd:V,onTouchMove:V,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:y.isGenerating?s.jsx("div",{className:"tab-spinner"}):y.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):k?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):y.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:tt(t),children:tt(t)}),s.jsx("span",{className:"adhdev-dockview-tab-meta",children:k?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ts(t)}):y.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[ts(t),s.jsx("span",{className:"connecting-dots"})]}):ts(t)})]}),i&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${i}`,children:i})]})},(e,t)=>e.conv===t.conv&&e.isActive===t.isActive&&e.isDraggedTab===t.isDraggedTab&&e.isTaskCompleteUnread===t.isTaskCompleteUnread&&e.shortcut===t.shortcut&&e.conversationKeys===t.conversationKeys&&e.isGroupActive===t.isGroupActive);function Oh({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:w,onReceiveTab:S,onHideTab:p,isGroupActive:x,allowTabShortcuts:j=!0}){const[b,N]=o.useState(null),T=o.useRef(null),y=o.useRef(null),C=o.useMemo(()=>e.map(P=>P.tabKey),[e]);tr("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(b==null?void 0:b.tabKey)||null});const{isMac:k,tabShortcuts:v,shortcutListening:g,setShortcutListening:D,saveShortcuts:M}=Zc({enabled:j,sortedTabKeys:e.map(P=>P.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!b)return;const P=K=>{const V=document.querySelector("[data-pane-context-menu]");V&&V.contains(K.target)||N(null)};return window.addEventListener("mousedown",P,!0),()=>window.removeEventListener("mousedown",P,!0)},[b]),o.useEffect(()=>{const P=y.current;if(!P)return;const K=V=>{Math.abs(V.deltaY)<=Math.abs(V.deltaX)||(V.preventDefault(),P.scrollLeft+=V.deltaY)};return P.addEventListener("wheel",K,{passive:!1}),()=>P.removeEventListener("wheel",K)},[]);const I=o.useCallback((P,K,V)=>{N({x:P,y:K,tabKey:V})},[]);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(P=>s.jsx(Kh,{conv:P,isActive:t===P.tabKey,isDraggedTab:a.current===P.tabKey,isTaskCompleteUnread:n.has(P.tabKey),shortcut:j?v[P.tabKey]:void 0,conversationKeys:C,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:f,onCommitPreviewOrder:d,onClearPreviewOrder:h,onDragStateReset:m,onDragTabKeyChange:w,onReceiveTab:S,onOpenContextMenu:I,longPressTimer:T,isGroupActive:x},P.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),b&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:b.x,top:b.y},children:[j&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:P=>{P.stopPropagation(),D(b.tabKey),N(null)},children:["⌨ ",v[b.tabKey]?`Change shortcut (${v[b.tabKey]})`:"Set shortcut"]}),v[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 P={...v};delete P[b.tabKey],M(P),N(null)},children:"✕ Remove shortcut"})]}),p&&s.jsxs(s.Fragment,{children:[j&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onClick:()=>{p(b.tabKey),N(null)},children:"🚫 Hide from Dashboard"})]})]}),j&&g&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>D(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:P=>P.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",k?"⌘+1":"Ctrl+1",", ",k?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function Wh({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:w,onReceiveTab:S,style:p,onActiveTabChange:x,initialActiveTabId:j,initialTabOrder:b,onTabOrderChange:N,onHideTab:T,isFocused:y,allowTabShortcuts:C=!0,onOpenNewSession:k,liveSessionInboxState:v}){const{sendCommand:g}=jt(),D=o.useRef(null),{activeTabId:M,activeConv:I,sortedConversations:P,draggingTabRef:K,selectTab:V,handleTabReorder:L,updatePreviewOrder:R,commitPreviewOrder:G,clearPreviewOrder:B,moveTabToEnd:E,setDraggingTabKey:W}=$h({conversations:e,initialActiveTabId:j,initialTabOrder:b,onActiveTabChange:x,onTabOrderChange:N}),J=nn({sendDaemonCommand:a,activeConv:I,setActionLogs:i,isStandalone:c}),{dragOver:be,dropAction:he,resetDragState:de,handleDragEnter:ye,handleDragOver:ge,handleDragLeave:ve,handleDrop:z}=Dh({conversations:e,numGroups:m,onMoveTab:w,onReceiveTab:S,onOwnTabDrop:E,onClearPreviewOrder:B}),F=I&&!qe(I)&&Ts(I)==="terminal",Q=o.useMemo(()=>I?t.find(ne=>ne.id===I.routeId):void 0,[t,I]),ue=o.useMemo(()=>I?n.filter(ne=>ne.routeId===I.tabKey):[],[n,I]),te=o.useMemo(()=>new Set(P.filter(ne=>pu(ne,v,{isOpenConversation:ne.tabKey===M})).map(ne=>ne.tabKey)),[M,v,P]);tr("PaneGroup",{groupIndex:f,conversationCount:e.length,activeTabId:M,dragOver:be});const fe=o.useCallback(ne=>{ne.streamSource==="agent-stream"&&ne.agentType&&g(ne.routeId,Vc(),{agentType:ne.agentType,...ne.sessionId&&{targetSessionId:ne.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:be?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(Oh,{conversations:P,activeTabId:M,groupIndex:f,numGroups:m,unreadTabKeys:te,draggingTabRef:K,onFocus:d,onSelectTab:V,onConversationActivated:fe,onPreviewReorder:R,onReorderTab:L,onCommitPreviewOrder:G,onClearPreviewOrder:B,onDragStateReset:de,onDragTabKeyChange:W,onMoveTab:w,onReceiveTab:S,onHideTab:T,isGroupActive:y??!1,allowTabShortcuts:C}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ye,onDragOver:ge,onDragLeave:ve,onDrop:z,children:[be&&s.jsx(Bh,{dropAction:he,canSplit:!!(m<4&&w)}),I?s.jsx(Ua,{activeConv:I,clearToken:r[I.tabKey]||0,isCliTerminal:!!F,ideEntry:Q,terminalRef:D,handleModalButton:J.handleModalButton,handleRelaunch:J.handleRelaunch,handleSendChat:J.handleSendChat,isSendingChat:J.isSendingChat,sendFeedbackMessage:J.sendFeedbackMessage,handleFocusAgent:J.handleFocusAgent,isFocusingAgent:J.isFocusingAgent,actionLogs:ue,userName:u,isInputActive:!h||!!y}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(Va,{conversationsCount:e.length,isSplitMode:h,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:k})})]})]})}function Hh({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:w,focusGroup:S,moveTabToGroup:p,splitTabRelative:x,closeGroup:j,handleResizeStart:b,groupActiveTabIds:N,setGroupActiveTab:T,groupTabOrders:y,setGroupTabOrder:C,toggleHiddenTab:k,onOpenNewSession:v,allowTabShortcuts:g=!0,liveSessionInboxState:D}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((M,I)=>{const P=t&&n.length===r?`${n[I]}%`:void 0;return s.jsxs(St.Fragment,{children:[t&&I>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:K=>b(I-1,K),onDoubleClick:()=>j(I),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(Wh,{style:t?{flexBasis:P??`${100/r}%`,flexGrow:P?0:1,flexShrink:P?0:1}:void 0,conversations:M,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setActionLogs:f,isStandalone:d,hasRegisteredMachines:h,userName:m,groupIndex:I,isFocused:t&&w===I,onFocus:()=>S(I),isSplitMode:t,numGroups:r,onMoveTab:(K,V)=>{V==="left"&&I>0?p(K,I-1):V==="right"&&I<r-1?p(K,I+1):V==="split-left"&&r<4?x(K,I,"left"):V==="split-right"&&r<4&&x(K,I,"right")},onReceiveTab:K=>p(K,I),onActiveTabChange:K=>T(I,K),initialActiveTabId:N[I],initialTabOrder:y[I],onTabOrderChange:K=>C(I,K),onHideTab:k,onOpenNewSession:v,allowTabShortcuts:g,liveSessionInboxState:D})]},I)})})}function el({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?at.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=at.onStatus)==null?void 0:d.call(at,(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?at.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?at.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 tl="adhdev-dashboard-action-shortcuts",Fh=1200,Uh={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function zh(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function Qe(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 sl(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:Qe("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:Qe("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:Qe("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:Qe("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:Qe("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:Qe("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:Qe("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:Qe("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:Qe("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:Qe("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:Qe("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:Qe("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:Qe("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:Qe("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:Qe("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:Qe("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:Qe("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:Qe("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:Qe("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:Qe("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:Qe("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:Qe("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:Qe("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:Qe("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:Qe("toggleCliView",e)}]}function la(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Gr(e){const t=Object.fromEntries(sl(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(tl)||"{}"),n={...t,...r};for(const[a,i]of Object.entries(Uh))n[a]===i&&(n[a]=t[a]);return n}catch{return t}}function rl(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Vh({enabled:e=!0,onTrigger:t}){const r=zh(),[n,a]=o.useState(()=>Gr(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(rl(p.key)),x.join("+"))},[r]),h=o.useCallback(p=>{a(p);try{localStorage.setItem(tl,JSON.stringify(p))}catch{}},[]);o.useEffect(()=>{const p=Gr(r),x=Object.entries(n),j=Object.entries(p);x.length===j.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}},[]),w=o.useCallback(()=>{typeof window>"u"||(f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current.timer=window.setTimeout(()=>{f.current={parts:[],timer:null}},Fh))},[]);o.useEffect(()=>{if(!i)return;const p=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){c(null),u([]);return}const j=d(x);if(!j)return;const N=!(x.metaKey||x.ctrlKey||x.altKey)&&/^[A-Z0-9]$/.test(j);if(l.length===0&&N){u([j]);return}const y=[...l,j].slice(0,2).join(" "),C={...n};for(const[k,v]of Object.entries(C))v===y&&delete C[k];C[i]=y,h(C),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 j=d(x);if(!j)return;const b=x.metaKey||x.ctrlKey||x.altKey;if(la(x.target)&&!b)return;const N=f.current.parts,T=b?[j]:[...N.slice(-1),j].slice(-2),y=T.join(" "),C=T[T.length-1],k=Object.entries(n).filter(([,I])=>!!I),v=k.find(([,I])=>I===y);if(v){x.preventDefault(),m(),t(v[0]);return}if(k.some(([,I])=>I.startsWith(`${y} `))){x.preventDefault(),f.current.parts=T,w();return}const D=k.find(([,I])=>I===C);if(D){x.preventDefault(),m(),t(D[0]);return}if(k.some(([,I])=>I.startsWith(`${C} `))){x.preventDefault(),f.current.parts=[C],w();return}m()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,w,e,d,t,m,i]),o.useEffect(()=>()=>m(),[m]);const S=o.useMemo(()=>sl(r),[r]);return{isMac:r,actionDefinitions:S,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:h}}function Gh({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 nl(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Jo({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!nl(n):!0}function qh({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:nl(r)}const al=o.createContext(null);function on(){const e=o.useContext(al);if(!e)throw new Error("DashboardDockviewContext missing");return e}function _r(e){return tt(e)||e.tabKey}function Yh(e){return`remote:${e}`}function Lt(e){return e.startsWith("remote:")}function Qo(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Ln(e){var r,n,a,i,c;const t=e==null?void 0:e.defaultView;if(t)try{t.focus(),(n=(r=e==null?void 0:e.body)==null?void 0:r.focus)==null||n.call(r),(i=(a=e==null?void 0:e.documentElement)==null?void 0:a.focus)==null||i.call(a),(c=t.requestAnimationFrame)==null||c.call(t,()=>{var l,u;try{t.focus(),(u=(l=e==null?void 0:e.body)==null?void 0:l.focus)==null||u.call(l)}catch{}})}catch{}}function Nr(e,t){e.classList.remove(Un.className,zn.className),e.classList.add(t==="light"?Un.className:zn.className)}function Zo(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 Xh(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 Jh(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:_r(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 ei(e,t){const r=new Set(t.map(n=>n.tabKey));for(const n of[...e.panels])Lt(n.id)||r.has(n.id)||e.removePanel(n);for(const n of t){const a=e.getPanel(n.tabKey);if(a){a.update({params:{tabKey:n.tabKey}}),a.title!==_r(n)&&a.api.setTitle(_r(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:_r(n),params:{kind:"conversation",tabKey:n.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function ti(e,t,r){var u,f;const n=r?Yh(r):null;for(const d of[...e.panels])Lt(d.id)&&(!n||d.id!==n)&&e.removePanel(d);if(!r||!n)return;const a=_t(t,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=pc(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 Qh({params:e,api:t}){var h;const r=on(),n=o.useRef(null),[a,i]=o.useState(t.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=nn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(t.isActive);const m=[t.onDidActiveChange(w=>i(w.isActive)),t.onDidActiveGroupChange(w=>{if(!t.isActive&&!w.isActive){i(!1);return}i(t.isActive)})];return()=>{for(const w of m)w.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(Va,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const d=!qe(c)&&Ts(c)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(Ua,{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 Zh({params:e}){var u;const t=on(),r=o.useMemo(()=>_t([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=o.useMemo(()=>t.ides.find(f=>f.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((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}=el({doId:a,targetSessionId:r?Qi(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(Di,{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 ex(){const e=on();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(Va,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function tx(e){var w,S;Xh(e);const t=on(),r=o.useCallback(p=>{"button"in p&&p.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const p=_t([...t.conversationsByTabKey.values()],e.params.routeId),x=((w=e.api.group.activePanel)==null?void 0:w.id)===e.api.id,j=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${x?" is-active":""}${j?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(p==null?void 0:p.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:p!=null&&p.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:p.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const n=t.conversationsByTabKey.get(e.params.tabKey);if(!n)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const a=((S=e.api.group.activePanel)==null?void 0:S.id)===e.api.id,i=e.api.isGroupActive,c=Qr(n,t.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,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:tt(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:tt(n)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ts(n)}):u?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ts(n)}):s.jsx("span",{children:ts(n)})})]}),m&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:m,children:m})]})}function sx({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:w,onOpenNewSession:S,onRequestScrollToBottom:p,requestedActiveTabKey:x,requestedRemoteIdeId:j,onRequestedActiveTabConsumed:b,scrollToBottomRequest:N,liveSessionInboxState:T,layoutProfile:y}){var ft,He,vt;const{theme:C}=$a(),{sendCommand:k}=jt(),v=o.useRef(null),g=o.useRef(null),D=o.useRef(!1),M=o.useRef(!1),I=o.useRef(!1),P=o.useRef(null),K=o.useRef([]),[V,L]=o.useState(null),[R,G]=o.useState(!1),[B,E]=o.useState(!1),[W,J]=o.useState(0),be=o.useRef(null),he=o.useRef(typeof window>"u"?{}:Rp(y)),de=o.useMemo(()=>new Map(e.map($=>[$.tabKey,$])),[e]),ye=o.useMemo(()=>{const $=v.current;return $?$.groups.some(O=>{try{const U=O.model.location.type;return U!=="floating"&&U!=="popout"?!1:O.panels.some(q=>de.has(q.id))}catch{return!1}}):!1},[de,W,e]),ge=o.useCallback(()=>{var $;($=v.current)==null||$.focus()},[]),ve=o.useCallback(($,O)=>{p==null||p($,O)},[p]),z=o.useCallback($=>{const O=document,U=$.document;for(const Ce of O.querySelectorAll('link[rel="stylesheet"]')){const se=U.createElement("link");se.rel="stylesheet",se.href=Ce.href,Ce.crossOrigin&&(se.crossOrigin=Ce.crossOrigin),U.head.appendChild(se)}for(const Ce of O.querySelectorAll("style")){const se=U.createElement("style");se.textContent=Ce.textContent,U.head.appendChild(se)}const q=[];for(const Ce of O.styleSheets)try{for(const se of Ce.cssRules)se instanceof CSSStyleRule&&(se.selectorText===":root"||se.selectorText==="html")&&q.push(se.cssText)}catch{}if(q.length>0){const Ce=U.createElement("style");Ce.textContent=q.join(`
|
|
42
|
+
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:g,onCancel:()=>d(null)})]})}const Uf=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function zf(){const{preference:e,setPreference:t}=$a();return s.jsx("div",{className:"flex gap-2",children:Uf.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 Vf(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 Gf(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function jn(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function _o(e){const{r:t,g:r,b:n}=Gf(e);return .2126*jn(t)+.7152*jn(r)+.0722*jn(n)}function Do(e,t){const r=_o(e),n=_o(t),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function Tc(e){const t=Vf(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return Do(t,r)>=Do(t,n)?r:n}const oa={bgPrimary:"#0a0e1a",bgSecondary:"#0f1320",surfacePrimary:"#111726",textPrimary:"#f0f0f5",textSecondary:"#9ca3af",textMuted:"#6b7280",borderSubtle:"#1d2536",borderDefault:"#313c52",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#111726",assistantText:"#f0f0f5",containerBg:"#0f1320",sendButton:"#d97706",inputBorder:"#313c52",bubbleRadius:16},ia={bgPrimary:"#fff8ee",bgSecondary:"#fff1de",surfacePrimary:"#ffffff",textPrimary:"#24160f",textSecondary:"#6f6255",textMuted:"#938374",borderSubtle:"#e7d3ba",borderDefault:"#d7b892",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#fffaf4",assistantText:"#24160f",containerBg:"#fff8ee",sendButton:"#d97706",inputBorder:"#d7b892",bubbleRadius:16},qf=[{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"}}}],Lc="adhdev-chat-theme",Rc="adhdev-chat-theme-custom";function Rr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Lc)||"ember"}catch{return"ember"}}function Pt(e){try{const t=localStorage.getItem(Rc);if(t){const r=JSON.parse(t);return{...e==="dark"?oa:ia,...r[e]}}}catch{}return e==="dark"?oa:ia}function yr(e,t){try{localStorage.setItem(Rc,JSON.stringify({dark:e,light:t}))}catch{}}function It(e,t){const r=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${r}, ${n}, ${a}, ${t})`}function Vr(e,t){const r=Math.min(255,parseInt(e.slice(1,3),16)+t),n=Math.min(255,parseInt(e.slice(3,5),16)+t),a=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const Yf={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Fs(e,t){var a;const r=(a=Yf[e])==null?void 0:a[t];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",Vr(r,24)),n.style.setProperty("--accent-on-primary",Tc(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Vr(r,18)})`),n.style.setProperty("--border-accent",It(r,.35)),n.style.setProperty("--nav-active-bg",It(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${It(r,.06)}`)}function ns(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",It(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",It(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",It(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",It(e.borderSubtle,.5)),t.style.setProperty("--border-default",It(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Vr(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Tc(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Vr(e.accentColor,40)})`),t.style.setProperty("--border-accent",It(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",It(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${It(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${It(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function Ba(){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 Xf(e){try{localStorage.setItem(Lc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=as()?"dark":"light";ns(Pt(t))}else Ba(),Fs(e,as()?"dark":"light")}function Jf(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Rr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=as()?"dark":"light";ns(Pt(t))}else Ba(),Fs(e,as()?"dark":"light")}function as(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function xt({label:e,value:t,onChange:r}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,onChange:n=>{/^#[0-9a-fA-F]{0,6}$/.test(n.target.value)&&r(n.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function Ps({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 Qf({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=o.useState(()=>Pt(r));o.useEffect(()=>{a(Pt(r))},[r]);const i=o.useCallback((c,l)=>{a(u=>{const f={...u,[c]:l},h=Pt(r==="dark"?"light":"dark");return r==="dark"?yr(f,h):yr(h,f),ns(f),t(f),f})},[r,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",s.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(Ps,{title:"App Background",children:[s.jsx(xt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(xt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(xt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(Ps,{title:"App Text",children:[s.jsx(xt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(xt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(xt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(Ps,{title:"Borders & Accent",children:[s.jsx(xt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(xt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(xt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Ps,{title:"Chat Bubbles",children:[s.jsx(xt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(xt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),s.jsx(xt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(xt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(Ps,{title:"Chat Layout",children:[s.jsx(xt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(xt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(xt,{label:"Input border",value:n.inputBorder,onChange:c=>i("inputBorder",c)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.jsx("input",{type:"range",min:4,max:24,value:n.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?oa:ia,u=Pt(e?"light":"dark");e?yr(c,u):yr(u,c),a(c),ns(c),t(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:"Reset to defaults"})]})}function Zf(){const[e,t]=o.useState(Rr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Pt("dark"));o.useEffect(()=>{n(as());const u=new MutationObserver(()=>{const h=as();n(h);const m=Rr();m==="custom"?ns(Pt(h?"dark":"light")):Fs(m,h?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const f=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{const h=as();n(h);const m=Rr();m==="custom"?ns(Pt(h?"dark":"light")):Fs(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"?ns(Pt(r?"dark":"light")):(Ba(),Fs(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Pt(r?"dark":"light"))},[r]);const c=u=>{t(u),Xf(u)},l=[...qf,{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(Qf,{dark:r,onColorsChange:u=>i(u)})]})}const Ka="adhdev_mobileDashboardMode_v1",ca="adhdev:mobile-dashboard-mode-change";function Oa(){try{return localStorage.getItem(Ka)==="workspace"?"workspace":"chat"}catch{return"chat"}}function ep(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??Oa())},r=a=>{const i=a.detail;t(i)},n=a=>{a.key&&a.key!==Ka||t()};return window.addEventListener(ca,r),window.addEventListener("storage",n),()=>{window.removeEventListener(ca,r),window.removeEventListener("storage",n)}}function tp(e){try{localStorage.setItem(Ka,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(ca,{detail:e}))}function sp(){const[e,t]=o.useState(!0);return o.useEffect(()=>{t(Oa()==="chat")},[]),s.jsx(Qt,{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),tp(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const kn=new Map,Eo=new Map;function rp(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 np(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 Pc(){const{sendCommand:e}=jt(),{injectEntries:t,getIdes:r}=Gs();return o.useCallback(async(n,a)=>{if(!n)return;const i=(a==null?void 0:a.minFreshMs)??vm,c=Eo.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<i)return;const l=kn.get(n);if(l)return l;const u=(async()=>{const f=await e(n,"get_machine_runtime_stats"),d=rp(f);if(!d)return;const h=r().find(w=>w.id===n),m=np(h,n,d.machine,d.timestamp||Date.now());t([m]),Eo.set(n,Date.now())})().finally(()=>{kn.delete(n)});return kn.set(n,u),u},[r,t,e])}function ap(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 op(e,t){const{sendData:r}=jt(),{injectEntries:n,getIdes:a}=Gs(),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=>qt.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(w=>w.id===u),m=ap(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 ip(e,t){const{sendData:r}=jt(),[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=qt.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},f=>{l&&(clearTimeout(l),l=null),a(f.diagnostics),c(!1)});return u.initialSendAccepted?l=setTimeout(()=>{c(!1)},Sm):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 cp(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function _c(e){const{sendData:t}=jt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=cp(e);if(!a||!e.sessionId||!t){n({});return}const i=qt.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),ks.record({interactionId:c.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:c.status,modalButtonCount:Array.isArray(c.modalButtons)?c.modalButtons.length:0}})});return i.initialSendAccepted||n({}),()=>{i()}},[e.daemonId,e.routeId,e.sessionId,t]),r}const Dc="adhdev_hiddenTabs";function lp(){try{const e=localStorage.getItem(Dc);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ps(e){try{localStorage.setItem(Dc,JSON.stringify([...e]))}catch{}}function Sn(e){return Ca(e)}function Wa(e,t){return ws(t).some(r=>e.has(r))}function dp(){const[e,t]=o.useState(lp),r=o.useCallback(f=>{const d=Sn(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=Sn(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=Sn(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 w of d)m.add(w);return ps(m),m})},[]),l=o.useCallback((f,d)=>{t(h=>{const m=new Set(h);for(const w of d)m.delete(w);return ps(m),m})},[]),u=o.useCallback(f=>Wa(e,f),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function Ec(e){return e instanceof Error?e.message:String(e||"")}function $c(e){const t=Ec(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 Bc(e){const t=Ec(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Kc({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!Je(e)||qe(e))return;const i=Ts(e);if(i===t)return;const c=e.sessionId;c&&a(l=>({...l,[c]:t}));try{await n(fs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Kt(e),mode:t})}catch(l){const u=Bc(l);c&&!u&&a(f=>{const d={...f};return i===Oc(r,c)?delete d[c]:d[c]=i,d}),$c(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 $o(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 up(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=$o(a,t),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>$o(u,t)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function Oc(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))Oc(t,a)===i&&(delete n[a],r=!0);return r?n:e}function fp({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{Ui()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:fc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Eu(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 pp(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=r.get(n.id);if(!a){r.set(n.id,n);continue}const i=(a.workspace?1:0)+(a.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>i||(n.timestamp||0)>(a.timestamp||0))&&r.set(n.id,n)}return Array.from(r.values())}function Nn(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function hp(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 Bo(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?hp(Vs(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 xp(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||""),Bo(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||""),Bo(r.activeChat)].join(":"))].join("|")}function bp(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 gp(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 yp(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function vp(e){const t=yp(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=Vs(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function wp({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=o.useMemo(()=>pp(e),[e]),i=o.useMemo(()=>vc(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 T=new Map,y=[];for(const g of a){const{connectionState:D="new",machineName:M}=wc(g,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),I=xp(g),P=f.current.get(g.id);if(P&&P.ide===g&&P.sourceSignature===I&&P.connectionState===D&&P.machineName===M){T.set(g.id,P),y.push(...P.conversations);continue}const K=Ea(g,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),V={ide:g,sourceSignature:I,connectionState:D,machineName:M,conversations:K};T.set(g.id,V),y.push(...K)}f.current=T;const C=new Map,k=g=>{const D=vp(g),M=d.current.get(g.tabKey);if(M&&M.signature===D)return C.set(g.tabKey,M),M.timestamp;const I={signature:D,timestamp:ec(g)||(M==null?void 0:M.timestamp)||0};return C.set(g.tabKey,I),I.timestamp},v=[...y].sort((g,D)=>tc(g,D,k));return d.current=C,v},[a,t,i]),m=o.useMemo(()=>{const T=bp(h,r);return Nn(c.current,T)?c.current:(c.current=T,T)},[h,r]),w=o.useMemo(()=>{const T=new Map,y=Array.from(new Set(m.map(C=>C.routeId)));for(const C of y){const k=_t(m,C);k&&T.set(C,k)}return T},[m]),S=o.useMemo(()=>{const T=new Map;for(const y of m){const C=w.get(y.routeId),k=y.streamSource==="native"&&C?C:y;for(const v of ws({providerSessionId:y.providerSessionId,sessionId:y.sessionId}))T.set(v,k)}return T},[m,w]),p=o.useMemo(()=>gp(m,w),[m,w]),x=o.useCallback(T=>{if(T)return S.get(T)},[S]),j=o.useCallback(T=>{if(T)return p.get(T)},[p]),b=o.useMemo(()=>{const T=m.filter(y=>!Wa(n,y));return Nn(l.current,T)?l.current:(l.current=T,T)},[m,n]),N=o.useMemo(()=>{const T=b.map(y=>y.tabKey);return Nn(u.current,T)?u.current:(u.current=T,T)},[b]);return{chatIdes:a,conversations:m,visibleConversations:b,visibleTabKeys:N,resolveConversationBySessionId:x,resolveConversationByTarget:j}}function jp({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(()=>{lt.setIdes(e)},[e]),o.useEffect(()=>{lt.setResolveAction((a,i,c)=>{t(a,i,c).catch(()=>{})})},[t]),o.useEffect(()=>{const a=lt.onToast(i=>{r(l=>l.some(f=>f.message===i.message&&i.timestamp-f.timestamp<3e3)?l:[...l.slice(-4),{id:i.id,message:i.message,type:i.type,timestamp:i.timestamp,targetKey:i.targetKey,actions:i.actions}]);const c=i.duration||5e3;setTimeout(()=>r(l=>l.filter(u=>u.id!==i.id)),c)});return()=>{a()}},[r]),o.useEffect(()=>{const a=dc.on("status_event",i=>{lt.handleRawEvent(i,"ws")});return()=>{a()}},[]),o.useEffect(()=>{var i;const a=c=>{var p;const l=c.data;if((l==null?void 0:l.type)!=="notification_action"||typeof l.action!="string"||!l.action.startsWith("approval_")||!(l.daemonId||l.targetSessionId||l.targetKey))return;const 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",w=String(m).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),S=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(w);t(d,"resolve_action",{action:S?"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 Sp="adhdev_dashboardLayout_v1",Np="adhdev_dashboardDockview_v1",Cp="adhdev_dashboardDockviewHiddenRestore_v1",_s={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Ha(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function Ip(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Wc(e){return`${Sp}:${e}`}function Ap(e){const t=Wc(e);return Ha(t,null)}function Mp(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=Wc(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Hc(e){return`${Np}:${e}`}function Tp(e){const t=Hc(e);return Ha(t,null)}function Lp(e,t){try{const r=Hc(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Fc(e){return`${Cp}:${e}`}function Rp(e){const t=Fc(e);return Ha(t,{})}function Pp(e,t){try{const r=Fc(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function _p(){return{groupAssignments:[..._s.groupAssignments],focusedGroup:_s.focusedGroup,groupActiveTabIds:{..._s.groupActiveTabIds},groupTabOrders:{..._s.groupTabOrders},groupSizes:[..._s.groupSizes]}}function Dp(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function Ep(){const[e]=o.useState(()=>Ip(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),[w,S]=o.useState(!1),p=o.useCallback(()=>{if(w)return;const g=Ap(e)??_p();r(new Map(g.groupAssignments)),a(g.focusedGroup),c(g.groupActiveTabIds),u(g.groupTabOrders),d(g.groupSizes),S(!0)},[w,e]);o.useEffect(()=>{w&&Mp(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:f})},[w,e,t,n,i,l,f]),o.useEffect(()=>{const g=window.matchMedia("(max-width: 767px)"),D=M=>m(M.matches);return g.addEventListener("change",D),()=>g.removeEventListener("change",D)},[]);const x=o.useCallback(g=>{r(g)},[]),j=o.useCallback(g=>{a(g)},[]),b=o.useCallback(g=>{c(g)},[]),N=o.useCallback(g=>{u(g)},[]),T=o.useCallback(g=>{d(g)},[]),y=o.useCallback(g=>{j(g)},[j]),C=o.useCallback((g,D)=>{c(M=>(M[g]??null)===(D??null)?M:{...M,[g]:D})},[]),k=o.useCallback((g,D)=>{u(M=>{const I=M[g];return Dp(I,D)?M:{...M,[g]:D}})},[]),v=o.useCallback((g,D)=>{const M=D.get(g)??0;return C(M,g),y(M),M},[y,C]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:x,focusedGroup:n,updateFocusedGroup:j,focusGroup:y,groupActiveTabIds:i,updateGroupActiveTabIds:b,setGroupActiveTab:C,groupTabOrders:l,updateGroupTabOrders:N,setGroupTabOrder:k,groupSizes:f,updateGroupSizes:T,isMobile:h,hasHydratedStoredLayout:w,hydrateStoredLayout:p,focusConversationTab:v}}function $p(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=Na(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Bp({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 w=o.useRef(!1),S=o.useRef(!1),p=o.useRef(null),x=o.useRef(!1);o.useEffect(()=>{if(!e||w.current||t.length===0)return;if(!a){i();return}const j=r(e);j&&(c(j.tabKey,n),w.current=!0,S.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),l(b=>{const N=new URLSearchParams(b);return N.delete("activeTab"),N},{replace:!0}))},[e,t,r,n,a,i,c,l]),o.useEffect(()=>{if(!(S.current||a)&&t.length!==0){if(!e){i(),S.current=!0;return}if(w.current){S.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(S.current||a)&&(i(),S.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,t.length,a,i]),o.useEffect(()=>{if(!u){x.current=!1;return}if(!f||x.current||d)return;const j=h.find(b=>b.id===f.routeId);j&&(!j.chats||j.chats.length===0||$p(j.chats,f))&&(x.current=!0,m())},[u,f,d,h,m]),o.useEffect(()=>{if(!f)return;let j=null,b=0,N=-1,T=0;const y=()=>{j=null;const C=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(v=>v.offsetParent!==null);if(C.length===0){b<18&&(b+=1,j=requestAnimationFrame(y));return}let k=0;for(const v of C)v.scrollTop=v.scrollHeight,k+=v.scrollHeight;k===N?T+=1:(T=0,N=k),b+=1,!(T>=2||b>=18)&&(j=requestAnimationFrame(y))};return j=requestAnimationFrame(y),()=>{j!=null&&cancelAnimationFrame(j)}},[f==null?void 0:f.tabKey])}function Cn(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0];if((r==null?void 0:r.active)===!0)return!0;const n=Na(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Uc({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 S=>{try{await e("standalone","launch_ide",{ideType:S,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),h=o.useCallback(async(S,p)=>{try{const x=S||(t==null?void 0:t.daemonId)||"",j=await e(x,"switch_chat",{id:p,sessionId:p,...js(t)}),b=j==null?void 0:j.result;if((j==null?void 0:j.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?Rs(a,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?Rs(a,`⚠️ Switch error: ${b}`):Rs(a,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),Rs(a,`❌ Switch failed: ${x.message||"connection error"}`)}},[t,e,a]),m=o.useCallback(async()=>{if(!(!t||c)){l(!0);try{const S=Js(t);await e(S,"new_chat",{...js(t)}),i(p=>({...p,[t.tabKey]:Date.now()}))}catch(S){console.error("New chat failed",S)}finally{l(!1)}}},[t,c,e,i]),w=o.useCallback(async()=>{var S,p;if(!(!t||u)){f(!0);try{const x=Js(t),j=async()=>e(x,"list_chats",{forceExpand:!0,...js(t)});let b=await j(),N=(b==null?void 0:b.chats)||((S=b==null?void 0:b.result)==null?void 0:S.chats);Cn(N,t)&&(await new Promise(T=>setTimeout(T,450)),b=await j(),N=(b==null?void 0:b.chats)||((p=b==null?void 0:b.result)==null?void 0:p.chats)),b!=null&&b.success&&Array.isArray(N)&&(n(t.routeId,N),Cn(N,t)&&!Cn(r,t)&&Rs(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:w}}function Kp(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 Op(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function Ko(e,t){const r=Object.keys(e),n=Object.keys(t);return r.length!==n.length?!1:r.every(a=>t[Number(a)]===e[Number(a)])}function vr(e,t){const r=new Set(t),n=t.length>0?[0]:[];for(const[c,l]of e)!r.has(c)||l<=0||n.includes(l)||n.push(l);n.sort((c,l)=>c-l);const a={};n.forEach((c,l)=>{a[c]=l}),n.length===0&&(a[0]=0);const i=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const 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 Oo(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 Wp(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 Hp(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 Wo(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 Ho(e){return Array(e).fill(100/e)}function Fp({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(()=>vr(e,f),[e,f]),m=h.assignments,w=o.useMemo(()=>l?1:h.groupCount,[h.groupCount,l]),S=w>1,p=o.useCallback((y,C)=>{t(k=>{const v=new Map(vr(k,f).assignments);return C===0?v.delete(y):v.set(y,C),v}),n(k=>({...k,[C]:y})),r(C)},[t,f,n,r]),x=o.useCallback(y=>{t(C=>{const k=vr(C,f).assignments,v=new Map;for(const[g,D]of k)D!==y&&(D>y?v.set(g,D-1):v.set(g,D));return v}),c(C=>{if(C.length<=1)return[];const k=[...C];k.splice(y,1);const v=k.reduce((g,D)=>g+D,0);return v>0?k.map(g=>g/v*100):[]}),r(0)},[t,f,c,r]),j=o.useCallback((y,C)=>{C.preventDefault();const k=d.current;if(!k)return;const v=C.clientX,g=k.offsetWidth,D=i.length===w?[...i]:Ho(w),M=P=>{const V=(P.clientX-v)/g*100,L=[...D];L[y]=Math.max(15,D[y]+V),L[y+1]=Math.max(15,D[y+1]-V),c(L)},I=()=>{document.removeEventListener("mousemove",M),document.removeEventListener("mouseup",I),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",M),document.addEventListener("mouseup",I)},[i,w,c]),b=o.useCallback((y,C,k)=>{if(w>=4)return;const v=k==="left"?C:C+1;t(g=>{const D=vr(g,f).assignments,M=new Map;for(const I of u){const P=D.get(I.tabKey)??0,K=P>=v?P+1:P;K>0&&M.set(I.tabKey,K)}return v>0&&M.set(y,v),M}),c(g=>{const D=g.length===w?[...g]:Ho(w),M=D[C]??100/w,I=Math.max(15,M/2),P=Math.max(15,M/2),K=[...D];K[C]=I,K.splice(v,0,P);const V=K.reduce((L,R)=>L+R,0);return K.map(L=>L/V*100)}),n(g=>{const D=Wo(g,v);return D[v]=y,D}),a(g=>{const D=Wo(g,v);return D[v]=[y],D}),r(v)},[w,t,f,u,c,n,a,r]);o.useEffect(()=>{Kp(e,m)||t(m)},[e,m,t]),o.useEffect(()=>{const{mapping:y,usedGroups:C}=h;n(k=>{const v=Oo(k,y);return Ko(k,v)?k:v}),a(k=>{const v=Oo(k,y);return Ko(k,v)?k:v}),r(k=>{const v=l?0:Wp(k,C,y);return k===v?k:v}),c(k=>{const v=l?[]:Hp(k,C,h.groupCount);return Op(k,v)?k:v})},[h,l,n,a,r,c]);const N=o.useMemo(()=>{const y=Array.from({length:w},()=>[]);for(const C of u){const k=m.get(C.tabKey)??0,v=Math.min(k,w-1);y[v].push(C)}return y},[u,m,w]),T=o.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:d,normalizedGroupAssignments:m,numGroups:w,isSplitMode:S,groupedConvs:N,moveTabToGroup:p,closeGroup:x,handleResizeStart:j,splitTabRelative:b,clearAllSplits:T}}function Up({ides:e,sendDaemonCommand:t}){const r="0.9.23",n=o.useMemo(()=>e.filter(d=>d.type!=="adhdev-daemon"?!1:Mc(d,r)).sort((d,h)=>Number(Hs(h,r))-Number(Hs(d,r))),[r,e]),a=o.useMemo(()=>n.some(d=>Hs(d,r)),[r,n]),[i,c]=o.useState(!1),[l,u]=o.useState({}),f=o.useCallback(async d=>{var h,m;u(w=>({...w,[d]:"upgrading"}));try{const w=await t(d,"daemon_upgrade",{});(h=w==null?void 0:w.result)!=null&&h.upgraded||(m=w==null?void 0:w.result)!=null&&m.success?u(S=>({...S,[d]:"done"})):u(S=>({...S,[d]:"error"}))}catch{u(w=>({...w,[d]:"error"}))}},[t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:f}}const zc=80;function Pr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function zp(e){return{...e,createdAt:Pr(e.createdAt),updatedAt:Pr(e.updatedAt,e.createdAt),lastEventAt:Pr(e.lastEventAt,e.updatedAt||e.createdAt)}}function Vp(e){const t=Ca(e);return t==="unknown:"?e.id:t}function Gp(e){return[e.type,Zi(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function qp(e,t=zc){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=Vp(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 Yp(e,t){const r=Date.now(),n=[];for(const a of e){const i=a.sessionId?t.get(a.sessionId):void 0;if(i!=null&&i.surfaceHidden)continue;const c=Qr(a,t),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const u=Pr(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),f=Gp({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(zp({id:f,dedupKey:f,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Yi(a),preview:om(a),createdAt:u,updatedAt:u,lastEventAt:u}))}return qp(n)}function Xp(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function Jp(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=zc}=e,a=o.useMemo(()=>Yp(t,r).slice(0,Math.max(0,n)),[t,r,n]),i=o.useMemo(()=>Xp(a),[a]);return{notifications:a,unreadCount:i}}function Qp({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 tn(...e){const t=new Set,r=[],n=a=>{const i=typeof a=="string"?a.trim():"";if(!i)return;const c=i.toLowerCase();t.has(c)||(t.add(c),r.push(i))};for(const a of e){if(Array.isArray(a)){for(const i of a)n(i);continue}n(a)}return r}function Zp(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const r=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),a=(r[2]||"").replace(/[\\/]+/g,"\\");return a?`${n}:\\${a}`:`${n}:\\`}return null}function sn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=Zp(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 eh(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 th(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function rn(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=th(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 sh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Fo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function rh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function nh({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=Fo(n.workspacePath),l=e.find(f=>{var S,p,x,j;if(!f||f.type==="adhdev-daemon"||sh(f.daemonId||f.id)!==n.machineId||(Xs(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=Fo(f.workspace||f.runtimeWorkspaceLabel);return b?b===c:!1}return Number(f.lastUpdated||f._lastUpdate||f.timestamp||((j=(x=(p=(S=f.activeChat)==null?void 0:S.messages)==null?void 0:p.at)==null?void 0:x.call(p,-1))==null?void 0:j.timestamp)||0)>=n.startedAt-5e3});if(!l)return;const u=sc({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 ah({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:i}){const c=o.useCallback(async(m,w)=>rn(e,m,w),[e]),l=o.useCallback(async(m,w)=>{if(!w.trim())return{ok:!1,error:"Choose a workspace path first."};try{const S=await e(m,"workspace_add",{path:w.trim()});return S!=null&&S.success?{ok:!0}:{ok:!1,error:(S==null?void 0:S.error)||"Could not save workspace"}}catch(S){return{ok:!1,error:S instanceof Error?S.message:"Could not save workspace"}}},[e]),u=o.useCallback(async(m,w,S)=>{var p;try{const x={ideType:w,enableCdp:!0};(p=S==null?void 0:S.workspacePath)!=null&&p.trim()&&(x.workspace=S.workspacePath.trim());const j=await e(m,"launch_ide",x);return!(j!=null&&j.success)&&(j==null?void 0:j.success)!==void 0?{ok:!1,error:(j==null?void 0:j.error)||"Could not launch IDE"}:(t({machineId:m,kind:"ide",providerType:w,workspacePath:(S==null?void 0:S.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,w,S,p)=>{var j,b,N;const x=Date.now();try{const T={cliType:S};(j=p==null?void 0:p.workspacePath)!=null&&j.trim()?T.dir=p.workspacePath.trim():p!=null&&p.workspaceId&&(T.workspaceId=p.workspaceId),(b=p==null?void 0:p.resumeSessionId)!=null&&b.trim()&&(T.resumeSessionId=p.resumeSessionId.trim()),Array.isArray(p==null?void 0:p.cliArgs)&&p.cliArgs.length>0&&(T.cliArgs=p.cliArgs),(N=p==null?void 0:p.initialModel)!=null&&N.trim()&&(T.initialModel=p.initialModel.trim());const y=await e(m,"launch_cli",T),C=(y==null?void 0:y.result)||y,k=(C==null?void 0:C.sessionId)||(C==null?void 0:C.id);return y!=null&&y.success&&k?(r(k),{ok:!0}):y!=null&&y.success?(t({machineId:m,kind:w,providerType:S,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)||(C==null?void 0:C.error)||`Could not launch ${w.toUpperCase()} session`}}catch(T){return rh(T)?(t({machineId:m,kind:w,providerType:S,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:x}),{ok:!0}):{ok:!1,error:T instanceof Error?T.message:`Could not launch ${w.toUpperCase()} session`}}},[r,e,t]),d=o.useCallback(async(m,w)=>{if(!m||!w)return[];try{const S=await e(m,"list_saved_sessions",{providerType:w,kind:"cli",limit:30}),p=(S==null?void 0:S.result)??S;return Array.isArray(p==null?void 0:p.sessions)?p.sessions:[]}catch(S){return console.error("List saved sessions failed",S),[]}},[e]),h=o.useCallback(async m=>{await Kc({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 oh(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 ih(e,t,r=Date.now()){return!e||!oh(t)?null:{tabKey:e,nonce:r}}function ch({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,j;if(!e){if(l){const b=t.find(N=>N.tabKey===l);if(b)return b}return r[0]}const p=n[a];if(p){const b=t.find(N=>N.tabKey===p);if(b)return b}return((x=i[a])==null?void 0:x[0])||((j=i[0])==null?void 0:j[0])},[t,l,a,n,i,e,r]),m=o.useCallback(p=>{u(p)},[]),w=o.useCallback(p=>{u(p.tabKey),c(x=>{const j=new URLSearchParams(x),b=cm(p);return b?j.set("activeTab",b):j.delete("activeTab"),j},{replace:!0})},[c]),S=o.useCallback((p,x)=>{const j=ih(p,x);j&&d(j)},[]);return{activeConv:h,openDesktopConversation:w,requestScrollToBottom:S,scrollToBottomRequest:f,setDesktopActiveTab:m}}function lh({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:i,setToasts:c,setClearedTabs:l,setSearchParams:u}){var L;const[f,d]=o.useState(!1),[h,m]=o.useState([]),[w,S]=o.useState(()=>ht()),[p,x]=o.useState(!1),[j,b]=o.useState(null),N=o.useRef(null),T=o.useMemo(()=>r||t||e,[e,r,t]),y=!!T&&Je(T)&&!qe(T),C=o.useMemo(()=>{if(!T||!y)return null;const R=T.daemonId||T.routeId||"",G=Kt(T);return`${R}:${G}`},[T,y]),{isCreatingChat:k,isRefreshingHistory:v,handleSwitchSession:g,handleNewChat:D,handleRefreshHistory:M}=Uc({sendDaemonCommand:a,activeConv:T,chats:(L=n.find(R=>R.id===(T==null?void 0:T.routeId)))==null?void 0:L.chats,updateRouteChats:i,setToasts:c,setClearedTabs:l}),I=o.useCallback(()=>{d(!0)},[]),P=o.useCallback(()=>{d(!1)},[]),K=o.useCallback(async()=>{if(!(!T||!y||p)){x(!0);try{const R=T.daemonId||T.routeId,G=Kt(T),B=await a(R,"list_saved_sessions",{agentType:G,providerType:G,kind:"cli",limit:50}),E=(B==null?void 0:B.result)??B;m(Array.isArray(E==null?void 0:E.sessions)?E.sessions:[])}catch(R){console.error("Refresh saved sessions failed",R),m([])}finally{x(!1)}}},[T,p,y,a]);o.useEffect(()=>{if(!f){N.current=null;return}if(!y){N.current=null,m([]),x(!1);return}!C||p||N.current!==C&&(N.current=C,K())},[K,f,p,y,C]);const V=o.useCallback(async R=>{if(!T||!y||!R.providerSessionId||!R.workspace)return;const G=T.daemonId||T.routeId,B=Kt(T);try{b(R.providerSessionId);const E=await a(G,"launch_cli",{cliType:B,dir:R.workspace,resumeSessionId:R.providerSessionId,initialModel:Hi(R.summaryMetadata,"model",{preferShortValue:!0})||void 0}),W=(E==null?void 0:E.result)??E,J=typeof(W==null?void 0:W.sessionId)=="string"?W.sessionId:typeof(W==null?void 0:W.id)=="string"?W.id:"";J&&u(be=>{const he=new URLSearchParams(be);return he.set("activeTab",J),he},{replace:!0}),P()}catch(E){console.error("Resume saved session failed",E)}finally{b(null)}},[P,T,y,a,u]);return{historyModalOpen:f,openHistoryModal:I,closeHistoryModal:P,historyTargetConv:T,isSavedSessionHistoryTarget:y,isHistoryCreatingChat:k,isHistoryRefreshingHistory:v,handleHistorySwitchSession:g,handleHistoryNewChat:D,handleHistoryRefresh:M,savedHistorySessions:h,savedHistoryFilters:w,setSavedHistoryFilters:S,isSavedHistoryLoading:p,resumingSavedHistorySessionId:j,handleRefreshSavedHistory:K,handleResumeSavedHistorySession:V}}function dh({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 j=l(n);return j&&!Je(j)&&!qe(j)?j:null},[e,n,l]),w=o.useMemo(()=>{const j=u==null?void 0:u.routeId;if(!j)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)===j?b:_t(i,j)},[i,u,a]),S=o.useMemo(()=>{if(w)return c.find(j=>j.id===w.routeId)},[c,w]);o.useEffect(()=>{m&&(f({routeId:m.routeId,tabKey:So(m)}),h(m),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,m]);const p=o.useCallback(j=>{j&&(f({routeId:j.routeId,tabKey:So(j)}),h(j))},[]),x=o.useCallback(()=>{f(null),h(null)},[]);return{remoteDialogConv:w,remoteDialogIdeEntry:S,remoteDialogActiveConv:d,setRemoteDialogActiveConv:h,openRemoteDialog:p,closeRemoteDialog:x}}function uh({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:w,openRemoteDialog:S,closeRemoteDialog:p}=dh({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}),[x,j]=o.useState(!1),[b,N]=o.useState(null),T=o.useCallback(async k=>{const v=k||u;!v||!Je(v)&&!qe(v)||(N(v),j(!0))},[u]),y=o.useCallback(()=>{j(!1),N(null)},[]),C=o.useCallback(async k=>{const v=b||u;if(!v||!Je(v)&&!qe(v)){y();return}j(!1);try{const g=Kt(v),D=v.routeId||v.daemonId||"";await f(D,"stop_cli",{cliType:g,targetSessionId:v.sessionId,mode:k})}catch(g){console.error("Stop CLI failed:",g)}finally{N(null)}},[u,y,b,f]);return{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:m,setRemoteDialogActiveConv:w,openRemoteDialog:S,closeRemoteDialog:p,cliStopDialogOpen:x,cliStopTargetConv:b,requestCliStop:T,cancelCliStop:y,confirmCliStop:C}}function Vc(){return"select_session"}function mh(){return"open_panel"}function fh({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function ph(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function Uo(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 Fa(e){return e instanceof Error?e.message:String(e||"")}function Vo(e){const t=Fa(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Go(e,t){const r=Fa(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function nn({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,i]=o.useState(!1),[c,l]=o.useState(!1),[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 j=x.trim(),b=Aa(t);if(fh({hasMessage:!!j,blockedMessage:b,sendInFlight:d.current}))return b&&f(b),!1;const N=Date.now(),T={tabKey:t.tabKey,message:j,timestamp:N};if(ph(h.current,T))return f(null),!0;d.current=!0,l(!0),f(null),h.current=T;try{const y=Js(t);if(!y)return h.current=Uo(h.current,T),f("Unable to send message right now."),!1;const C=await e(y,"send_chat",{message:j,...js(t)}),k=zo(C);if(k!=null&&k.deduplicated)return f(null),!0;if((k==null?void 0:k.sent)===!1)throw new Error((k==null?void 0:k.error)||"Send failed");if((k==null?void 0:k.success)===!1)throw new Error((k==null?void 0:k.error)||"Send failed");return f(null),!0}catch(y){const C=Fa(y);return C.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",C):console.warn("Send blocked/failed",y),h.current=Uo(h.current,T),f(Am(y)),!1}finally{d.current=!1,l(!1)}},[t,e]),w=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]),S=o.useCallback(async x=>{if(t)try{const b=(t.modalButtons||[]).indexOf(x),N=x.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),T=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(N),y=Js(t);if(!y)return;const C=await e(y,"resolve_action",{button:x,action:T?"approve":"reject",...b>=0&&{buttonIndex:b},...js(t)}),k=zo(C);k.success||r(v=>[...v,{routeId:t.tabKey,text:Go(x,k==null?void 0:k.error),timestamp:Date.now()}])}catch(j){Vo(j)||console.error("[ModalButton] Error:",j),r(b=>[...b,{routeId:t.tabKey,text:Vo(j)?Go(x,j):`❌ **${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:w,handleModalButton:S,handleFocusAgent:p}}function In(e,t=!0){return(e??!0)&&t}const Ua=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:w,userName:S,scrollToBottomRequestNonce:p,isInputActive:x=!0,isVisible:j=!0}){const[b,N]=o.useState(n),T=o.useRef(n);o.useEffect(()=>{const I=T.current;if(T.current=n,!n){N(!1);return}if(I){N(!0);return}N(!1);let P=0,K=0;return P=window.requestAnimationFrame(()=>{K=window.requestAnimationFrame(()=>{N(!0)})}),()=>{window.cancelAnimationFrame(P),window.cancelAnimationFrame(K)}},[n]);const y=n&&b,C=!n||!b,k=In(j,n),v=In(j,C),g=In(j),D=_c(t),M=D.status||D.modalMessage||D.modalButtons?{...t,...D.status?{status:D.status}:{},...D.modalMessage!==void 0?{modalMessage:D.modalMessage}:{},...D.modalButtons!==void 0?{modalButtons:D.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx($i,{activeConv:M,onModalButton:c}),M.transport!=="pty"&&M.transport!=="acp"&&M.cdpConnected===!1?s.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:s.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[s.jsx("span",{className:"text-sm",children:s.jsx(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,M.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:y?"visible":"hidden",pointerEvents:y?"auto":"none"},children:s.jsx(tf,{activeConv:M,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,isVisible:k,isInputActive:x&&k})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:C?"visible":"hidden",pointerEvents:C?"auto":"none"},children:s.jsx(na,{activeConv:M,ideEntry:a,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:m,actionLogs:w,userName:S,scrollToBottomRequestNonce:p,isInputActive:x&&v,isVisible:v})})]}):s.jsx(na,{activeConv:M,ideEntry:a,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:m,actionLogs:w,userName:S,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 hh({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:w,onHideConversation:S,onStopCli:p,cliViewMode:x,onSetCliViewMode:j,handleSendChat:b,handleFocusAgent:N,handleModalButton:T,handleRelaunch:y}){const C=o.useRef(null),k=Je(e)&&!t,v=k&&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(xa,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:tt(e)}),s.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:s.jsx(rc,{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:[k&&x&&s.jsx(Ta,{mode:x,onChange:j,compact:!0}),k&&p&&s.jsx("button",{onClick:()=>{p(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(wt,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>m(e),type:"button",children:s.jsx(ba,{size:14})}),!t&&!k&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>w(e),type:"button",children:s.jsx(Ct,{size:14})}),S&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(e),type:"button",title:"Close chat",children:s.jsx(wt,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(Ua,{activeConv:e,clearToken:0,isCliTerminal:v,ideEntry:n,terminalRef:C,handleModalButton:T,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 xh(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Gc(){const[e,t]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{t(xh())},[]);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 qc({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Ct},{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 wr({title:e,className:t=""}){return s.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${t}`,children:s.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function hs({children:e,className:t=""}){return s.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${t}`,children:e})}function Ds({icon:e,title:t,subtitle:r,children:n}){return s.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[s.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function jr({item:e,type:t,getAvatarText:r,onOpenConversation:n}){const a=t==="needs_attention"||t==="task_complete",i=t==="working",c=t==="earlier",l=t==="task_complete",{isReconnecting:u,isConnecting:f}=Ms(e.conversation),d=tt(e.conversation),h=us(e.conversation),m=mc(e.conversation,{requiresAction:t==="needs_attention"}),w=a?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":i?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",S=a?"bg-accent-primary shadow-glow":i?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":c?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",p=c?"text-text-secondary":"text-text-primary",x=c?"text-text-muted":"text-text-secondary",j=c?"text-text-secondary opacity-80":"text-text-muted",b=c?"text-text-muted opacity-80":"text-text-muted",N="text-[color:var(--status-warning)]";return s.jsxs("button",{className:`group flex items-start gap-3.5 px-4 py-3.5 w-full text-left relative overflow-hidden transition-colors active:scale-[0.995] ${w}`,onClick:()=>n(e.conversation),type:"button",children:[a||i?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${S}`,style:a?{color:"var(--accent-on-primary)"}:void 0,children:r(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:Ei(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] ${j}`,children:e.preview})]}),a&&!l&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),l&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Done"}),i&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Live"})]},e.conversation.tabKey)}function qo({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 bh({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:w,onSectionChange:S,wsStatus:p="connected",isStandalone:x=!1}){const j=p==="disconnected"||p==="reconnecting"||p==="offline"||p==="auth_failed",b=c.length>0,N=t.length>0||r.length>0||n.length>0||a.length>0,T=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",C=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:T}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||r.length>0)&&s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[s.jsx(Xr,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:w,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:s.jsx(Yr,{size:18})})]})]})}),s.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${C}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:j?s.jsx(Ds,{icon:s.jsx(qo,{label:"Reconnecting…"}),title:"Connecting to server",subtitle:p==="offline"?"Your device appears to be offline. Waiting for network…":p==="auth_failed"?"Session expired. Please log in again.":"Establishing connection to the server. This usually takes a moment."}):c.length===0?s.jsx(Ds,{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(Gc,{})})}):s.jsx(hs,{children:c.map((k,v)=>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] ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>m(k.id),type:"button",children:[s.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:l(k.label)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:k.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:k.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[k.unread," new"]}):k.total>0?`${k.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:k.subtitle}),k.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[k.total," chat",k.total!==1?"s":"",k.unread>0?` · ${k.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},k.id))})}),e==="chats"&&t.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(wr,{title:"Needs attention",className:"mb-0"}),s.jsx(hs,{children:t.map((k,v)=>s.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"needs_attention",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))})]}),e==="chats"&&r.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(wr,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(hs,{children:r.map((k,v)=>s.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"task_complete",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))})]}),e==="chats"&&n.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(wr,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(hs,{children:n.map((k,v)=>s.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"working",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&s.jsx(wr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(hs,{children:a.map((k,v)=>s.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"earlier",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))}):N?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):j?s.jsx(Ds,{icon:s.jsx(qo,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):b?s.jsx(Ds,{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:hc,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":$t,title:$t,children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s.jsx("span",{children:$t})]})}):s.jsx(Ds,{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((k,v)=>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 ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(k),type:"button",children:[s.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-bg-primary border border-border-subtle text-text-secondary",children:l(tt(k))}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:tt(k)}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:us(k)}),s.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},k.tabKey))})]})]}),e==="chats"&&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":$t,title:$t,children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),s.jsx(qc,{section:e,onSectionChange:S})]})}function gh(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 Yc(e){const t=[e.workspace||"Workspace unknown"],r=ds(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=gh(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function an({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:u,onConfirm:f}){const[d,h]=o.useState(r);o.useEffect(()=>{h(r)},[r]);const m=eh(r),w=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(wt,{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(xa,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:d,onChange:S=>h(S.target.value),onKeyDown:S=>{S.key!=="Enter"||!w||a||(S.preventDefault(),u(w))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!w||a||u(w)},disabled:!w||a,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):i?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):n.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:n.map(S=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>u(S.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Ss,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:S.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:S.path})]})]},S.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>f(w||r),disabled:!w&&!r||a,children:c})]})]})})}function za({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:w,onModelChange:S,historyProviderNode:p,onConfirm:x,onCancel:j}){const b=n==null?void 0:n.find(N=>N.key===a);return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:j,"aria-label":"Close launch confirmation",children:s.jsx(wt,{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&&S&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),s.jsx("input",{type:"text",value:w||"",onChange:N=>S(N.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled: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:j,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(ya,{size:14}),u?l:c]})]})]})})}function Yo(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function os(e){const{machine:t,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,i=[];a&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const u of t.workspaces||[])i.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${Yo(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:Yo(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 yh(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function vh(e){return[yh(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function wh(e){return e.lastLaunchedAt?Jr(e.lastLaunchedAt):""}function Xc(e){return{metaText:vh(e),updatedLabel:wh(e)}}function Mn(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function jh({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var ut,mt,Xe,rt;const c=nr(),[l,u]=o.useState(!1),f=(((ut=e.detectedIdes)==null?void 0:ut.length)||0)>0,d=o.useMemo(()=>(e.workspaces||[]).map(je=>({id:je.id,path:je.path,label:je.label})),[e]),h=e.defaultWorkspaceId||null,[m,w]=o.useState(h||((mt=d[0])==null?void 0:mt.id)||""),[S,p]=o.useState(""),[x,j]=o.useState(""),[b,N]=o.useState([]),[T,y]=o.useState(!1),[C,k]=o.useState(""),[v,g]=o.useState(!1),[D,M]=o.useState(Mn(f,t.length,r.length)),I=o.useRef(null),[P,K]=o.useState(null),V=o.useRef("__home__"),[L,R]=o.useState("__home__"),[G,B]=o.useState(""),[E,W]=o.useState(""),[J,be]=o.useState(""),[he,de]=o.useState([]),[ye,ge]=o.useState(()=>ht().textQuery),[ve,z]=o.useState(()=>ht().workspaceQuery),[F,Q]=o.useState(()=>ht().modelQuery),[ue,te]=o.useState(()=>ht().resumableOnly),[fe,ne]=o.useState(()=>ht().sortMode),[xe,re]=o.useState(!1),[le,oe]=o.useState(!1),Y=o.useRef(null),X=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const ae=m==="__custom__"?S.trim():((Xe=d.find(je=>je.id===m))==null?void 0:Xe.path)||"",A=m==="__custom__"&&!!ae&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),H=m!=="__custom__"&&((rt=d.find(je=>je.id===m))==null?void 0:rt.path)||"",ce=o.useMemo(()=>(e.recentLaunches||[]).map(je=>je.workspace),[e]),me=o.useCallback(async je=>{y(!0),k("");try{const Ee=await a(je);j(Ee.path),p(Ee.path),N(Ee.directories)}catch(Ee){k(Ee instanceof Error?Ee.message:"Could not load folder")}finally{y(!1)}},[a]),we=o.useCallback(()=>{var Ee;w("__custom__"),g(!0);const je=sn(e.platform,tn(S.trim(),H,ce,e.defaultWorkspacePath,(Ee=d.find(Be=>Be.id===h))==null?void 0:Ee.path,d.map(Be=>Be.path)));me(je)},[S,h,me,ce,H,e.platform,d]),_e=o.useCallback(je=>{if(je!=null&&je.workspaceId){w(je.workspaceId),p("");return}if(je!=null&&je.workspacePath){w("__custom__"),p(je.workspacePath);return}w(""),p("")},[]),Ae=o.useCallback(je=>{if(w(je),je==="__custom__"){we();return}p("")},[we]),Ke=o.useCallback(je=>{w("__custom__"),p(je)},[]),Fe=o.useCallback((je,Ee)=>{I.current=Ee,V.current=je.selectedWorkspaceKey||"__home__",R(je.selectedWorkspaceKey||"__home__"),B(je.initialArgs||""),W(je.initialModel||""),be(""),de([]);const Be=je.providerType?`${e.id}:${je.providerType}`:null;if(lf(X.current,Be)){const nt=ht();ge(nt.textQuery),z(nt.workspaceQuery),Q(nt.modelQuery),te(nt.resumableOnly),ne(nt.sortMode)}X.current=Be,K(je),je.providerType&&i&&(re(!0),i(je.providerType).then(nt=>de(nt||[])).catch(nt=>console.warn("Failed to load saved sessions",nt)).finally(()=>re(!1)))},[i,e.id]),ze=o.useMemo(()=>xc(he,{textQuery:ye,workspaceQuery:ve,modelQuery:F,resumableOnly:ue,sortMode:fe}),[F,ue,he,fe,ye,ve]);o.useEffect(()=>{J&&(ze.some(je=>je.providerSessionId===J)||be(""))},[ze,J]);const ot=o.useCallback(()=>{I.current&&(oe(!0),I.current().finally(()=>{I.current=null,oe(!1),K(null)}))},[]),it=o.useCallback(()=>{I.current=null,K(null)},[]),dt=o.useCallback(je=>{V.current=je,R(je)},[]);return o.useEffect(()=>{var je;Y.current!==e.id&&(Y.current=e.id,w(h||((je=d[0])==null?void 0:je.id)||"__custom__"),p(""),j(""),N([]),k(""),g(!1),ge(ht().textQuery),z(ht().workspaceQuery),Q(ht().modelQuery),te(ht().resumableOnly),ne(ht().sortMode),X.current=null,M(Mn(f,t.length,r.length)))},[r.length,t.length,h,f,e.id,d]),o.useEffect(()=>{var je;m!=="__custom__"&&(m&&d.some(Ee=>Ee.id===m)||w(h||((je=d[0])==null?void 0:je.id)||"__custom__"))},[h,m,d]),o.useEffect(()=>{D==="ide"&&f||D==="cli"&&t.length>0||D==="acp"&&r.length>0||M(Mn(f,t.length,r.length))},[D,r.length,t.length,f]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:f,workspaceRows:d,defaultWorkspaceId:h,workspaceChoice:m,customWorkspacePath:S,browseCurrentPath:x,browseDirectories:b,browseBusy:T,browseError:C,browseDialogOpen:v,activeLauncherKind:D,launchConfirm:P,launchConfirmWorkspaceKeyRef:V,launchConfirmWorkspaceKey:L,launchConfirmArgs:G,launchConfirmModel:E,launchConfirmResumeId:J,launchConfirmSavedSessions:he,launchConfirmTextFilter:ye,launchConfirmWorkspaceFilter:ve,launchConfirmModelFilter:F,launchConfirmResumableOnly:ue,launchConfirmSortMode:fe,filteredLaunchConfirmSavedSessions:ze,launchConfirmSessionsLoading:xe,launchConfirmBusy:le,resolvedWorkspacePath:ae,canCreateMissingWorkspace:A,openBrowseDialog:we,loadBrowsePath:me,handleWorkspaceChoiceChange:Ae,chooseCustomWorkspacePath:Ke,setCustomWorkspacePath:p,setBrowseDialogOpen:g,setActiveLauncherKind:M,openLaunchConfirm:Fe,handleConfirmLaunch:ot,closeLaunchConfirm:it,setWorkspaceSelectionFromOption:_e,setLaunchConfirmWorkspaceKeyAndSync:dt,setLaunchConfirmArgs:B,setLaunchConfirmModel:W,setLaunchConfirmResumeId:be,setLaunchConfirmTextFilter:ge,setLaunchConfirmWorkspaceFilter:z,setLaunchConfirmModelFilter:Q,setLaunchConfirmResumableOnly:te,setLaunchConfirmSortMode:ne}}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:w,onOpenRecent:S,onOpenMachineDetails:p,onMachineUpgrade:x,onLaunchDetectedIde:j,onAddWorkspace:b,onBrowseDirectory:N,onLaunchWorkspaceProvider:T,onListSavedSessions:y}){const C=L=>L==="ide"?"IDE":L==="cli"?"CLI":"ACP",k=r.slice(0,4),v=t.slice(0,3),g=jh({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:N,onListSavedSessions:y}),D=o.useMemo(()=>k.map(L=>{const{metaText:R,updatedLabel:G}=Xc(L);return{key:`recent-launch:${L.id}`,primary:L.label,secondary:R,updatedLabel:G,onClick:()=>{const{options:B,selectedKey:E}=os({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspacePath:L.workspace});g.openLaunchConfirm({title:L.kind==="ide"?ss("restart-ide",L.label):L.providerSessionId?Pa(L.label):ss("start-fresh",L.label),description:L.kind==="ide"?rs("restart-ide"):L.providerSessionId?_a():rs("start-fresh"),confirmLabel:L.kind==="ide"?Cs("restart-ide"):L.providerSessionId?Ur(!0):Cs("start-fresh"),busyLabel:L.kind==="ide"?Is("restart-ide"):L.providerSessionId?La(!0):Is("start-fresh"),workspaceOptions:B,selectedWorkspaceKey:E,details:[{label:"Mode",value:C(L.kind)},...L.providerType?[{label:"Provider",value:L.providerType}]:[]]},async()=>{const W=B.find(J=>J.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(W),await S({...L,workspace:(W==null?void 0:W.workspacePath)??null})})}}}),[g,S,k]),M=o.useMemo(()=>v.map(L=>({key:`recent-chat:${L.conversation.tabKey}`,primary:tt(L.conversation),secondary:Jm(L.conversation,{timestampLabel:L.timestamp?Ei(L.timestamp):null}),unread:L.unread,onClick:()=>w(L.conversation)})),[w,v]),I=g.showAllRecent?D:D.slice(0,4),P=D.length>0,K=M.length>0,V=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 ${V} 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(xa,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children: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:[K&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:M.map(L=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${L.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:L.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:L.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:L.secondary})]},L.key))})]}),P&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:I.map(L=>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:L.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:L.primary}),L.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:L.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:L.secondary})]},L.key))}),D.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(L=>!L),children:g.showAllRecent?"Show fewer":`Show ${D.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:L=>g.handleWorkspaceChoiceChange(L.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(L=>s.jsxs("option",{value:L.id,children:[L.id===g.defaultWorkspaceId?"⭐ ":"",Zr(L.path,L.label)||L.path]},L.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(Ss,{size:17})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),s.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children: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(L=>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:R,selectedKey:G}=os({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspaceId:g.workspaceChoice!=="__custom__"?g.workspaceChoice:null,currentWorkspacePath:g.resolvedWorkspacePath});g.openLaunchConfirm({title:`Launch ${L.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:R,selectedWorkspaceKey:G,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:L.name}]},async()=>{const B=R.find(E=>E.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(B),j(L.type,{workspacePath:(B==null?void 0:B.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:L.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:g.resolvedWorkspacePath||"Use selected workspace"})]},L.type)):(g.activeLauncherKind==="cli"?n:a).map(L=>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 R=g.activeLauncherKind==="cli"?"cli":"acp",{options:G,selectedKey:B}=os({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspaceId:g.workspaceChoice!=="__custom__"?g.workspaceChoice:null,currentWorkspacePath:g.resolvedWorkspacePath});g.openLaunchConfirm({title:`Launch ${L.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${R.toUpperCase()}`,workspaceOptions:G,selectedWorkspaceKey:B,details:[{label:"Mode",value:R.toUpperCase()},{label:"Provider",value:L.displayName}],showArgsInput:!0,showModelInput:R==="acp",initialArgs:"",initialModel:"",providerType:L.type},async()=>{const E=G.find(W=>W.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(E),T(R,L.type,{workspaceId:(E==null?void 0:E.workspaceId)??null,workspacePath:(E==null?void 0:E.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:[L.icon?`${L.icon} `:"",L.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:g.resolvedWorkspacePath||"Use selected workspace"})]},L.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(an,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:g.browseCurrentPath,directories:g.browseDirectories,busy:g.browseBusy,error:g.browseError,confirmLabel:"Use this folder",onClose:()=>g.setBrowseDialogOpen(!1),onNavigate:L=>{g.loadBrowsePath(L)},onConfirm:L=>{g.chooseCustomWorkspacePath(L),g.setBrowseDialogOpen(!1)}}),g.launchConfirm&&s.jsx(za,{title:g.launchConfirm.title,description:g.launchConfirm.description,details:g.launchConfirm.details,workspaceOptions:g.launchConfirm.workspaceOptions,selectedWorkspaceKey:g.launchConfirmWorkspaceKey,onWorkspaceChange:g.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:g.launchConfirm.providerType?Ur(!!g.launchConfirmResumeId):g.launchConfirm.confirmLabel,busyLabel:g.launchConfirm.providerType?void 0:g.launchConfirm.busyLabel,busy:g.launchConfirmBusy,showArgsInput:g.launchConfirm.showArgsInput,argsValue:g.launchConfirmArgs,onArgsChange:g.setLaunchConfirmArgs,showModelInput:g.launchConfirm.showModelInput,modelValue:g.launchConfirmModel,onModelChange:g.setLaunchConfirmModel,historyProviderNode:g.launchConfirm.providerType&&(g.launchConfirmSessionsLoading||g.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),g.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:Ra()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:g.launchConfirmTextFilter,onChange:L=>g.setLaunchConfirmTextFilter(L.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:L=>g.setLaunchConfirmWorkspaceFilter(L.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:L=>g.setLaunchConfirmModelFilter(L.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:L=>g.setLaunchConfirmSortMode(L.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:L=>g.setLaunchConfirmResumableOnly(L.target.checked),disabled:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:g.launchConfirmResumeId,onChange:L=>g.setLaunchConfirmResumeId(L.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(L=>s.jsxs("option",{value:L.providerSessionId,disabled:!L.canResume,children:[L.title||L.providerSessionId," ",L.canResume?"":"(workspace missing)"]},L.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 L=g.filteredLaunchConfirmSavedSessions.find(G=>G.providerSessionId===g.launchConfirmResumeId);if(!L)return null;const R=Yc(L);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:R.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:R.providerSessionId}),s.jsx("div",{className:"mt-1",children:R.metaLine}),R.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:R.updatedLabel}),R.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:R.preview})]})})()]}),onConfirm:g.handleConfirmLaunch,onCancel:g.closeLaunchConfirm}),d&&s.jsx(qc,{section:f,onSectionChange:m})]})}function Sh(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 Nh(e,t){if(!e)return[];const r=e.recentLaunches||[];return r.length>0?r.map(n=>({id:n.id,label:n.title||n.providerName||n.providerType,kind:n.kind,providerType:n.providerType,providerSessionId:n.providerSessionId,subtitle:ds(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):t.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var c,l,u,f,d;const a=Xs(n)?"cli":ys(n)?"acp":"ide",i=ds(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(Xs(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 Ch(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=Jn(n),u=a.filter(h=>h.unread||h.requiresAction).length,f=Sh(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?Qm(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 Ih(e){return e==="chat"}function kr(e,t){var r;if(!(typeof window>"u"))try{if(!(!!((r=import.meta.env)!=null&&r.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,t)}catch{}}function Ah({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:w,setSelectedTabKey:S,setScreen:p,setSelectedMachineId:x,setSection:j,setMachineBackTarget:b,resetMachineAction:N}){const T=o.useRef(null),y=o.useCallback(C=>{if(!(C!=null&&C.sessionId))return;const k=Or(C,c),v=Math.max(Date.now(),es(C),k.lastUpdated||0);kr("mark_read:start",{tabKey:C.tabKey,sessionId:C.sessionId,displayPrimary:tt(C),inboxBucket:k.inboxBucket,unread:k.unread,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,activityAt:es(C),readAt:v}),l(fs(C)||C.routeId,"mark_session_seen",{sessionId:C.sessionId,seenAt:v}).then(g=>{kr("mark_read:result",{tabKey:C.tabKey,sessionId:C.sessionId,result:g})}).catch(g=>{kr("mark_read:error",{tabKey:C.tabKey,sessionId:C.sessionId,error:g instanceof Error?g.message:String(g)})})},[c,l]);return o.useEffect(()=>{var k;if(!n){Ih(i)&&p("inbox"),S(((k=e[0])==null?void 0:k.tabKey)||null),T.current=null;return}if(i!=="chat"){T.current=null;return}const C=`${n.tabKey}:${n.sessionId||""}`;T.current!==C&&(T.current=C,y(n))},[e,y,i,n,p,S]),o.useEffect(()=>{if(!u)return;const C=e.find(k=>k.tabKey===u);C&&(S(C.tabKey),p("chat"),f==null||f())},[e,f,u,p,S]),o.useEffect(()=>{if(!d)return;const C=t.find(k=>k.id===d);C&&(x(C.id),N(),j("machines"),b("inbox"),p("machine"),h==null||h())},[t,h,d,N,b,p,j,x]),o.useEffect(()=>{m&&(j(m),p("inbox"),w==null||w())},[w,m,p,j]),o.useEffect(()=>{const C=r.filter(k=>k.inboxBucket==="task_complete"||k.unread);C.length!==0&&kr("inbox_state",{screen:i,selectedTabKey:a,items:C.map(k=>{const v=Or(k.conversation,c);return{liveState:v,tabKey:k.conversation.tabKey,sessionId:k.conversation.sessionId,displayPrimary:tt(k.conversation),serverBucket:v.inboxBucket,computedBucket:k.inboxBucket,serverUnread:v.unread,computedUnread:k.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,activityAt:es(k.conversation)}})})},[r,c,i,a]),{markConversationRead:y}}function Mh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Xo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Th(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Lh({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,T)=>{var y;try{i("loading"),l(`Launching ${N}…`);const C={ideType:N,enableCdp:!0};(y=T==null?void 0:T.workspacePath)!=null&&y.trim()&&(C.workspace=T.workspacePath.trim()),await e(b,"launch_ide",C),i("done"),l(`${N} launch requested`)}catch(C){i("error"),l(C instanceof Error?C.message:"Launch IDE failed"),console.error("Launch IDE failed",C)}},[e]),m=o.useCallback(async(b,N,T)=>{if(N.trim())try{i("loading"),l(T!=null&&T.createIfMissing?"Creating folder…":"Saving workspace…");const y=await e(b,"workspace_add",{path:N.trim(),createIfMissing:(T==null?void 0:T.createIfMissing)===!0});if(y!=null&&y.success){i("done"),l(T!=null&&T.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]),w=o.useCallback(async b=>{var N,T,y,C,k,v;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${((T=g==null?void 0:g.result)==null?void 0:T.version)||"latest"}.`);return}if((y=g==null?void 0:g.result)!=null&&y.upgraded||(C=g==null?void 0:g.result)!=null&&C.success){i("done"),l(`Upgrade to v${((k=g==null?void 0:g.result)==null?void 0:k.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((v=g==null?void 0:g.result)==null?void 0:v.error)||"Upgrade failed")}catch(g){i("error"),l(g instanceof Error?g.message:"Upgrade failed")}},[e]),S=o.useCallback(async(b,N,T,y)=>{var v,g,D;const C=Date.now(),k={machineId:b,kind:N,providerType:T,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:C};try{i("loading"),l(`Launching ${T}…`),f(k);const M={cliType:T};(v=y==null?void 0:y.workspacePath)!=null&&v.trim()?M.dir=y.workspacePath.trim():y!=null&&y.workspaceId&&(M.workspaceId=y.workspaceId),y!=null&&y.resumeSessionId&&(M.resumeSessionId=y.resumeSessionId),(g=y==null?void 0:y.args)!=null&&g.trim()&&(M.cliArgs=y.args.trim().split(/\s+/).filter(Boolean)),(D=y==null?void 0:y.model)!=null&&D.trim()&&(M.initialModel=y.model.trim());const I=await e(b,"launch_cli",M),P=(I==null?void 0:I.result)||I,K=(P==null?void 0:P.sessionId)||(P==null?void 0:P.id);if(I!=null&&I.success&&K){f(null),i("done"),l(`${T} launched`),t(Gt(K));return}if(I!=null&&I.success){i("loading"),l(`${T} launch requested — waiting for session…`);return}f(null),i("error"),l((I==null?void 0:I.error)||(P==null?void 0:P.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(M){if(Th(M)){i("loading"),l(`${T} launch requested — waiting for session…`);return}f(null),i("error"),l(M instanceof Error?M.message:`Could not launch ${N.toUpperCase()} workspace`)}},[t,e]),p=o.useCallback(async(b,N)=>{try{const T=await e(b,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),y=(T==null?void 0:T.result)??T;return Array.isArray(y==null?void 0:y.sessions)?y.sessions:[]}catch(T){return console.error("Failed to list saved sessions on mobile:",T),[]}},[e]),x=o.useCallback(async(b,N)=>rn(e,b,N),[e]);o.useEffect(()=>{if(!u)return;const b=Xo(u.workspacePath),N=r.find(y=>{var M,I,P,K;if(!y||y.type==="adhdev-daemon"||Mh(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 V=Xo(y.workspace||y.runtimeWorkspaceLabel);return V?V===b:!1}return Number(y.lastUpdated||y._lastUpdate||y.timestamp||((K=(P=(I=(M=y.activeChat)==null?void 0:M.messages)==null?void 0:I.at)==null?void 0:P.call(I,-1))==null?void 0:K.timestamp)||0)>=u.startedAt-5e3});if(!N)return;const T=sc({entrySessionId:N.sessionId,entryInstanceId:N.instanceId,entryRouteId:N.id,conversations:n});T&&(f(null),i("done"),l(`${u.providerType} launched`),t(Gt(T)))},[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 j=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 S(b,N.kind,N.providerType,{workspacePath:N.workspace||null,resumeSessionId:N.providerSessionId||null})},[h,S]);return{machineAction:{state:a,message:c},resetMachineAction:d,handleLaunchDetectedIde:h,handleAddWorkspace:m,handleMachineUpgrade:w,handleLaunchWorkspaceProvider:S,handleListSavedSessions:p,handleBrowseDirectory:x,handleOpenRecent:j}}function Rh({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:f}){const d=o.useCallback(j=>{i(j.tabKey),c("chat"),n(j)},[n,c,i]),h=o.useCallback(j=>{const b=e.find(N=>N.routeId===j.routeId&&N.streamSource==="native");b&&(i(b.tabKey),c("chat"),n(b))},[e,n,c,i]),m=o.useCallback(()=>{n(t),c("inbox")},[n,t,c]),w=o.useCallback((j,b="inbox")=>{l(j),a(),u("machines"),f(b),c("machine")},[a,f,c,u,l]),S=o.useCallback(j=>{const b=fs(j);b&&w(b,"chat")},[w]),p=o.useCallback(()=>{a(),c(r)},[r,a,c]),x=o.useCallback(j=>{u(j),c("inbox")},[c,u]);return{openConversation:d,openNativeConversation:h,backFromConversation:m,openMachine:w,openConversationMachine:S,backFromMachine:p,changeMachineSection:x}}function Ph(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function Sr(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function _h({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:w,onOpenHistory:S,onOpenRemote:p,onStopCli:x,wsStatus:j,isConnected:b,onShowHiddenConversation:N,onShowAllHiddenConversations:T,onHideConversation:y,onOpenNewSession:C,liveSessionInboxState:k,setCliViewModeOverrides:v}){const[g,D]=o.useState(()=>{var H;return((H=e[0])==null?void 0:H.tabKey)||null}),[M,I]=o.useState(()=>e[0]?"chat":"inbox"),[P,K]=o.useState("chats"),[V,L]=o.useState(null),[R,G]=o.useState("inbox"),B=As(),E="0.9.23",W=o.useMemo(()=>e.find(H=>H.tabKey===g)||e[0]||null,[e,g]),J=o.useMemo(()=>W?r.find(H=>H.id===W.routeId):void 0,[r,W]),be=o.useMemo(()=>!W||qe(W)||!Je(W)?null:Ts(W),[W]),he=o.useMemo(()=>r.filter(H=>H.type==="adhdev-daemon").sort(wa),[r]),de=o.useMemo(()=>he.find(H=>H.id===V)||null,[he,V]),ye=nn({sendDaemonCommand:a,activeConv:W||void 0,setActionLogs:i,isStandalone:c}),ge=Lh({sendDaemonCommand:a,navigate:B,ides:r,conversations:e}),ve=o.useMemo(()=>e.map(H=>{const ce=M==="chat"&&(W==null?void 0:W.tabKey)===H.tabKey,me=Qr(H,k,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ce}),we=es(H),_e=uc(H);return{conversation:H,timestamp:we,preview:_e,unread:me.unread,requiresAction:me.requiresAction,isWorking:me.isWorking,inboxBucket:me.inboxBucket}}),[e,k,M,W]),{markConversationRead:z}=Ah({conversations:e,machineEntries:he,items:ve,selectedConversation:W,selectedTabKey:g,screen:M,liveSessionInboxState:k,sendDaemonCommand:a,requestedActiveTabKey:u,onRequestedActiveTabConsumed:f,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:m,onRequestedMobileSectionConsumed:w,setSelectedTabKey:D,setScreen:I,setSelectedMachineId:L,setSection:K,setMachineBackTarget:G,resetMachineAction:ge.resetMachineAction}),F=Rh({conversations:e,selectedConversation:W,machineBackTarget:R,markConversationRead:z,resetMachineAction:ge.resetMachineAction,setSelectedTabKey:D,setScreen:I,setSelectedMachineId:L,setSection:K,setMachineBackTarget:G}),Q=o.useMemo(()=>Sr(ve.filter(H=>H.requiresAction)),[ve]),ue=o.useMemo(()=>Sr(ve.filter(H=>H.unread&&!H.requiresAction)),[ve]),te=o.useMemo(()=>Sr(ve.filter(H=>!H.unread&&!H.requiresAction&&H.isWorking)),[ve]),fe=o.useMemo(()=>Sr(ve.filter(H=>!H.unread&&!H.requiresAction&&!H.isWorking)),[ve]),ne=o.useMemo(()=>de?ve.filter(H=>fs(H.conversation)===de.id):[],[ve,de]),xe=o.useMemo(()=>Nh(de,r),[r,de]),re=(de==null?void 0:de.version)||null,le=!!de&&!!re&&!0&&re!==E,oe=o.useMemo(()=>(de==null?void 0:de.availableProviders)||[],[de]),Y=o.useMemo(()=>oe.filter(H=>H.category==="cli"&&H.installed!==!1).map(H=>({type:H.type,displayName:H.displayName||H.type,icon:H.icon})),[oe]),X=o.useMemo(()=>oe.filter(H=>H.category==="acp"&&H.installed!==!1).map(H=>({type:H.type,displayName:H.displayName||H.type,icon:H.icon})),[oe]),ae=o.useMemo(()=>Ch(he,ve),[ve,he]),A=o.useCallback(async H=>{de&&await ge.handleOpenRecent(de.id,H)},[ge,de]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:M==="chat"&&W?s.jsx(hh,{selectedConversation:W,isAcp:qe(W),isStandalone:c,selectedIdeEntry:J,actionLogs:n,userName:l,isSendingChat:ye.isSendingChat,sendFeedbackMessage:ye.sendFeedbackMessage,isFocusingAgent:ye.isFocusingAgent,handleModalButton:ye.handleModalButton,handleRelaunch:ye.handleRelaunch,onBack:F.backFromConversation,onOpenNativeConversation:F.openNativeConversation,onOpenMachine:F.openConversationMachine,onHideConversation:y,onOpenHistory:S,onOpenRemote:p,onStopCli:x,cliViewMode:be,onSetCliViewMode:async H=>{await Kc({conversation:W,mode:H,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:v})},handleSendChat:ye.handleSendChat,handleFocusAgent:ye.handleFocusAgent}):M==="machine"&&de?s.jsx(kh,{selectedMachineEntry:de,selectedMachineConversations:ne,selectedMachineRecentLaunches:xe,cliProviders:Y,acpProviders:X,selectedMachineNeedsUpgrade:le,appVersion:E,machineAction:ge.machineAction,isStandalone:c,section:P,showBottomNav:R==="inbox",onBack:F.backFromMachine,onSectionChange:F.changeMachineSection,onOpenConversation:F.openConversation,onOpenRecent:A,onOpenMachineDetails:()=>B(`/machines/${de.id}`),onMachineUpgrade:()=>ge.handleMachineUpgrade(de.id),onLaunchDetectedIde:(H,ce)=>ge.handleLaunchDetectedIde(de.id,H,ce),onAddWorkspace:(H,ce)=>ge.handleAddWorkspace(de.id,H,ce),onBrowseDirectory:H=>ge.handleBrowseDirectory(de.id,H),onLaunchWorkspaceProvider:(H,ce,me)=>ge.handleLaunchWorkspaceProvider(de.id,H,ce,me),onListSavedSessions:H=>ge.handleListSavedSessions(de.id,H)}):s.jsx(bh,{section:P,attentionItems:Q,unreadItems:ue,workingItems:te,completedItems:fe,hiddenConversations:t,machineCards:ae,getAvatarText:Ph,onOpenConversation:F.openConversation,onShowConversation:N,onShowAllHidden:T,onOpenNewSession:C,onOpenMachine:F.openMachine,onOpenSettings:()=>B("/settings"),onSectionChange:K,wsStatus:j,isConnected:b,isStandalone:c})})}function Tn(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function Dh({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))},[]),w=o.useCallback(x=>{if(!x.dataTransfer.types.includes("text/tab-key"))return;if(x.preventDefault(),!Tn(t,r)){d("merge");return}const j=x.currentTarget.getBoundingClientRect(),b=x.clientX-j.left,N=j.width/3;b<N?d("split-left"):b>N*2?d("split-right"):d("merge")},[t,r]),S=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 j=x.dataTransfer.getData("text/tab-key"),b=j?e.some(T=>T.tabKey===j):!1,N=f;if(d(null),i(),!!j){if(x.preventDefault(),N==="split-left"&&Tn(t,r)){r==null||r(j,"split-left");return}if(N==="split-right"&&Tn(t,r)){r==null||r(j,"split-right");return}if(b){a(j);return}n==null||n(j)}},[e,f,t,r,n,a,i]);return{dragOver:l,dropAction:f,resetDragState:h,handleDragEnter:m,handleDragOver:w,handleDragLeave:S,handleDrop:p}}function Eh(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 $h({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),w=o.useRef(n),S=o.useRef(a);o.useEffect(()=>{w.current=n},[n]),o.useEffect(()=>{S.current=a},[a]),o.useEffect(()=>{t&&t!==i&&c(t)},[t,i]),o.useEffect(()=>{u(k=>{const v=Eh(k,e);return v.length===k.length&&v.every((g,D)=>g===k[D])?k:v})},[e]);const p=o.useMemo(()=>{const k=f??l;if(k.length===0)return e;const v=new Map(k.map((g,D)=>[g,D]));return[...e].sort((g,D)=>{const M=v.get(g.tabKey)??999,I=v.get(D.tabKey)??999;return M-I})},[e,f,l]);o.useEffect(()=>{var v,g;if(p.length===0){i!==null&&(c(null),(v=w.current)==null||v.call(w,null));return}if(i&&p.some(D=>D.tabKey===i))return;const k=p[0].tabKey;k!==i&&(c(k),(g=w.current)==null||g.call(w,k))},[p,i]);const x=o.useMemo(()=>p.find(k=>k.tabKey===i),[p,i]),j=o.useCallback(k=>{var v;c(k),(v=w.current)==null||v.call(w,k)},[]),b=o.useCallback((k,v,g)=>{u(D=>{var K;const M=D.filter(V=>V!==k),I=M.indexOf(v);if(I<0)return D;const P=g==="left"?I:I+1;return M.splice(P,0,k),(K=S.current)==null||K.call(S,M),M}),d(null)},[]),N=o.useCallback((k,v,g)=>{const M=(l.length>0?l:e.map(K=>K.tabKey)).filter(K=>K!==k),I=M.indexOf(v);if(I<0)return;const P=g==="left"?I:I+1;M.splice(P,0,k),h.current=M,d(M)},[l,e]),T=o.useCallback(()=>{var v;const k=h.current;k&&(u(k),(v=S.current)==null||v.call(S,k))},[]),y=o.useCallback(()=>{h.current=null,d(null)},[]),C=o.useCallback(k=>{u(v=>{var D;const g=v.filter(M=>M!==k);return g.push(k),(D=S.current)==null||D.call(S,g),g})},[]);return{activeTabId:i,activeConv:x,sortedConversations:p,previewOrderRef:h,draggingTabRef:m,selectTab:j,handleTabReorder:b,updatePreviewOrder:N,commitPreviewOrder:T,clearPreviewOrder:y,moveTabToEnd:C,setDraggingTabKey:k=>{m.current=k}}}function Bh({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 Va({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?hc: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:$t,"aria-label":$t,children:[s.jsx(Ti,{size:14}),s.jsx("span",{children:$t})]})}),c&&s.jsx(Gc,{}),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 Jc="adhdev-tab-shortcuts";function Qc(){try{return JSON.parse(localStorage.getItem(Jc)||"{}")}catch{return{}}}function Zc({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>Qc()),[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(Jc,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 w=f(m);if(!w)return;const S={...i};for(const[p,x]of Object.entries(S))x===w&&delete S[p];S[l]=w,d(S),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[w,S]of Object.entries(i))if(t.includes(w)&&f(m)===S){m.preventDefault(),r(),n(w);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 Kh=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:w,onClearPreviewOrder:S,onDragStateReset:p,onDragTabKeyChange:x,onReceiveTab:j,onOpenContextMenu:b,longPressTimer:N,isGroupActive:T}){const y=Ms(t),C=y.isGenerating?"agent-tab-generating":y.isWaiting?"agent-tab-waiting":"",k=y.isReconnecting,v=o.useCallback(R=>{l.current=t.tabKey,x(t.tabKey),R.dataTransfer.setData("text/tab-key",t.tabKey),R.dataTransfer.effectAllowed="move"},[t.tabKey,l,x]),g=o.useCallback(()=>{l.current=null,x(null),w(),S(),p()},[l,x,w,S,p]),D=o.useCallback(R=>{const G=l.current;if(!(!G||G===t.tabKey)&&R.dataTransfer.types.includes("text/tab-key")){R.preventDefault(),R.stopPropagation();const B=R.currentTarget.getBoundingClientRect(),E=R.clientX<B.left+B.width/2?"left":"right";h(G,t.tabKey,E)}},[t.tabKey,l,h]),M=o.useCallback(R=>{R.preventDefault(),R.stopPropagation();const G=R.dataTransfer.getData("text/tab-key");if(G&&G!==t.tabKey){const B=R.currentTarget.getBoundingClientRect(),E=R.clientX<B.left+B.width/2?"left":"right";c.includes(G)?m(G,t.tabKey,E):j&&j(G)}S()},[t.tabKey,c,m,j,S]),I=o.useCallback(R=>{R.stopPropagation(),u(),f(t.tabKey),d(t)},[t,d,u,f]),P=o.useCallback(R=>{R.preventDefault(),b(R.clientX,R.clientY,t.tabKey)},[t.tabKey,b]),K=o.useCallback(R=>{const G=R.touches[0];N.current=setTimeout(()=>{b(G.clientX,G.clientY,t.tabKey)},600)},[t.tabKey,N,b]),V=o.useCallback(()=>{N.current&&clearTimeout(N.current)},[N]),L=["adhdev-dockview-tab",C,r&&"is-active",T&&"is-group-active",k&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:L,draggable:!0,onDragStart:v,onDragEnd:g,onDragOver:D,onDrop:M,onClick:I,onContextMenu:P,onTouchStart:K,onTouchEnd:V,onTouchMove:V,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:y.isGenerating?s.jsx("div",{className:"tab-spinner"}):y.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):k?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):y.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:tt(t),children:tt(t)}),s.jsx("span",{className:"adhdev-dockview-tab-meta",children:k?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ts(t)}):y.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[ts(t),s.jsx("span",{className:"connecting-dots"})]}):ts(t)})]}),i&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${i}`,children:i})]})},(e,t)=>e.conv===t.conv&&e.isActive===t.isActive&&e.isDraggedTab===t.isDraggedTab&&e.isTaskCompleteUnread===t.isTaskCompleteUnread&&e.shortcut===t.shortcut&&e.conversationKeys===t.conversationKeys&&e.isGroupActive===t.isGroupActive);function Oh({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:w,onReceiveTab:S,onHideTab:p,isGroupActive:x,allowTabShortcuts:j=!0}){const[b,N]=o.useState(null),T=o.useRef(null),y=o.useRef(null),C=o.useMemo(()=>e.map(P=>P.tabKey),[e]);tr("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(b==null?void 0:b.tabKey)||null});const{isMac:k,tabShortcuts:v,shortcutListening:g,setShortcutListening:D,saveShortcuts:M}=Zc({enabled:j,sortedTabKeys:e.map(P=>P.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!b)return;const P=K=>{const V=document.querySelector("[data-pane-context-menu]");V&&V.contains(K.target)||N(null)};return window.addEventListener("mousedown",P,!0),()=>window.removeEventListener("mousedown",P,!0)},[b]),o.useEffect(()=>{const P=y.current;if(!P)return;const K=V=>{Math.abs(V.deltaY)<=Math.abs(V.deltaX)||(V.preventDefault(),P.scrollLeft+=V.deltaY)};return P.addEventListener("wheel",K,{passive:!1}),()=>P.removeEventListener("wheel",K)},[]);const I=o.useCallback((P,K,V)=>{N({x:P,y:K,tabKey:V})},[]);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(P=>s.jsx(Kh,{conv:P,isActive:t===P.tabKey,isDraggedTab:a.current===P.tabKey,isTaskCompleteUnread:n.has(P.tabKey),shortcut:j?v[P.tabKey]:void 0,conversationKeys:C,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:f,onCommitPreviewOrder:d,onClearPreviewOrder:h,onDragStateReset:m,onDragTabKeyChange:w,onReceiveTab:S,onOpenContextMenu:I,longPressTimer:T,isGroupActive:x},P.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),b&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:b.x,top:b.y},children:[j&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:P=>{P.stopPropagation(),D(b.tabKey),N(null)},children:["⌨ ",v[b.tabKey]?`Change shortcut (${v[b.tabKey]})`:"Set shortcut"]}),v[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 P={...v};delete P[b.tabKey],M(P),N(null)},children:"✕ Remove shortcut"})]}),p&&s.jsxs(s.Fragment,{children:[j&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onClick:()=>{p(b.tabKey),N(null)},children:"🚫 Hide from Dashboard"})]})]}),j&&g&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>D(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:P=>P.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",k?"⌘+1":"Ctrl+1",", ",k?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function Wh({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:w,onReceiveTab:S,style:p,onActiveTabChange:x,initialActiveTabId:j,initialTabOrder:b,onTabOrderChange:N,onHideTab:T,isFocused:y,allowTabShortcuts:C=!0,onOpenNewSession:k,liveSessionInboxState:v}){const{sendCommand:g}=jt(),D=o.useRef(null),{activeTabId:M,activeConv:I,sortedConversations:P,draggingTabRef:K,selectTab:V,handleTabReorder:L,updatePreviewOrder:R,commitPreviewOrder:G,clearPreviewOrder:B,moveTabToEnd:E,setDraggingTabKey:W}=$h({conversations:e,initialActiveTabId:j,initialTabOrder:b,onActiveTabChange:x,onTabOrderChange:N}),J=nn({sendDaemonCommand:a,activeConv:I,setActionLogs:i,isStandalone:c}),{dragOver:be,dropAction:he,resetDragState:de,handleDragEnter:ye,handleDragOver:ge,handleDragLeave:ve,handleDrop:z}=Dh({conversations:e,numGroups:m,onMoveTab:w,onReceiveTab:S,onOwnTabDrop:E,onClearPreviewOrder:B}),F=I&&!qe(I)&&Ts(I)==="terminal",Q=o.useMemo(()=>I?t.find(ne=>ne.id===I.routeId):void 0,[t,I]),ue=o.useMemo(()=>I?n.filter(ne=>ne.routeId===I.tabKey):[],[n,I]),te=o.useMemo(()=>new Set(P.filter(ne=>pu(ne,v,{isOpenConversation:ne.tabKey===M})).map(ne=>ne.tabKey)),[M,v,P]);tr("PaneGroup",{groupIndex:f,conversationCount:e.length,activeTabId:M,dragOver:be});const fe=o.useCallback(ne=>{ne.streamSource==="agent-stream"&&ne.agentType&&g(ne.routeId,Vc(),{agentType:ne.agentType,...ne.sessionId&&{targetSessionId:ne.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:be?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(Oh,{conversations:P,activeTabId:M,groupIndex:f,numGroups:m,unreadTabKeys:te,draggingTabRef:K,onFocus:d,onSelectTab:V,onConversationActivated:fe,onPreviewReorder:R,onReorderTab:L,onCommitPreviewOrder:G,onClearPreviewOrder:B,onDragStateReset:de,onDragTabKeyChange:W,onMoveTab:w,onReceiveTab:S,onHideTab:T,isGroupActive:y??!1,allowTabShortcuts:C}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ye,onDragOver:ge,onDragLeave:ve,onDrop:z,children:[be&&s.jsx(Bh,{dropAction:he,canSplit:!!(m<4&&w)}),I?s.jsx(Ua,{activeConv:I,clearToken:r[I.tabKey]||0,isCliTerminal:!!F,ideEntry:Q,terminalRef:D,handleModalButton:J.handleModalButton,handleRelaunch:J.handleRelaunch,handleSendChat:J.handleSendChat,isSendingChat:J.isSendingChat,sendFeedbackMessage:J.sendFeedbackMessage,handleFocusAgent:J.handleFocusAgent,isFocusingAgent:J.isFocusingAgent,actionLogs:ue,userName:u,isInputActive:!h||!!y}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(Va,{conversationsCount:e.length,isSplitMode:h,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:k})})]})]})}function Hh({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:w,focusGroup:S,moveTabToGroup:p,splitTabRelative:x,closeGroup:j,handleResizeStart:b,groupActiveTabIds:N,setGroupActiveTab:T,groupTabOrders:y,setGroupTabOrder:C,toggleHiddenTab:k,onOpenNewSession:v,allowTabShortcuts:g=!0,liveSessionInboxState:D}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((M,I)=>{const P=t&&n.length===r?`${n[I]}%`:void 0;return s.jsxs(St.Fragment,{children:[t&&I>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:K=>b(I-1,K),onDoubleClick:()=>j(I),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(Wh,{style:t?{flexBasis:P??`${100/r}%`,flexGrow:P?0:1,flexShrink:P?0:1}:void 0,conversations:M,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setActionLogs:f,isStandalone:d,hasRegisteredMachines:h,userName:m,groupIndex:I,isFocused:t&&w===I,onFocus:()=>S(I),isSplitMode:t,numGroups:r,onMoveTab:(K,V)=>{V==="left"&&I>0?p(K,I-1):V==="right"&&I<r-1?p(K,I+1):V==="split-left"&&r<4?x(K,I,"left"):V==="split-right"&&r<4&&x(K,I,"right")},onReceiveTab:K=>p(K,I),onActiveTabChange:K=>T(I,K),initialActiveTabId:N[I],initialTabOrder:y[I],onTabOrderChange:K=>C(I,K),onHideTab:k,onOpenNewSession:v,allowTabShortcuts:g,liveSessionInboxState:D})]},I)})})}function el({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?at.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=at.onStatus)==null?void 0:d.call(at,(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?at.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?at.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 tl="adhdev-dashboard-action-shortcuts",Fh=1200,Uh={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function zh(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function Qe(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 sl(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:Qe("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:Qe("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:Qe("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:Qe("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:Qe("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:Qe("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:Qe("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:Qe("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:Qe("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:Qe("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:Qe("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:Qe("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:Qe("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:Qe("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:Qe("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:Qe("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:Qe("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:Qe("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:Qe("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:Qe("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:Qe("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:Qe("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:Qe("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:Qe("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:Qe("toggleCliView",e)}]}function la(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Gr(e){const t=Object.fromEntries(sl(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(tl)||"{}"),n={...t,...r};for(const[a,i]of Object.entries(Uh))n[a]===i&&(n[a]=t[a]);return n}catch{return t}}function rl(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Vh({enabled:e=!0,onTrigger:t}){const r=zh(),[n,a]=o.useState(()=>Gr(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(rl(p.key)),x.join("+"))},[r]),h=o.useCallback(p=>{a(p);try{localStorage.setItem(tl,JSON.stringify(p))}catch{}},[]);o.useEffect(()=>{const p=Gr(r),x=Object.entries(n),j=Object.entries(p);x.length===j.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}},[]),w=o.useCallback(()=>{typeof window>"u"||(f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current.timer=window.setTimeout(()=>{f.current={parts:[],timer:null}},Fh))},[]);o.useEffect(()=>{if(!i)return;const p=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){c(null),u([]);return}const j=d(x);if(!j)return;const N=!(x.metaKey||x.ctrlKey||x.altKey)&&/^[A-Z0-9]$/.test(j);if(l.length===0&&N){u([j]);return}const y=[...l,j].slice(0,2).join(" "),C={...n};for(const[k,v]of Object.entries(C))v===y&&delete C[k];C[i]=y,h(C),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 j=d(x);if(!j)return;const b=x.metaKey||x.ctrlKey||x.altKey;if(la(x.target)&&!b)return;const N=f.current.parts,T=b?[j]:[...N.slice(-1),j].slice(-2),y=T.join(" "),C=T[T.length-1],k=Object.entries(n).filter(([,I])=>!!I),v=k.find(([,I])=>I===y);if(v){x.preventDefault(),m(),t(v[0]);return}if(k.some(([,I])=>I.startsWith(`${y} `))){x.preventDefault(),f.current.parts=T,w();return}const D=k.find(([,I])=>I===C);if(D){x.preventDefault(),m(),t(D[0]);return}if(k.some(([,I])=>I.startsWith(`${C} `))){x.preventDefault(),f.current.parts=[C],w();return}m()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,w,e,d,t,m,i]),o.useEffect(()=>()=>m(),[m]);const S=o.useMemo(()=>sl(r),[r]);return{isMac:r,actionDefinitions:S,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:h}}function Gh({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 nl(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Jo({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!nl(n):!0}function qh({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:nl(r)}const al=o.createContext(null);function on(){const e=o.useContext(al);if(!e)throw new Error("DashboardDockviewContext missing");return e}function _r(e){return tt(e)||e.tabKey}function Yh(e){return`remote:${e}`}function Lt(e){return e.startsWith("remote:")}function Qo(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Ln(e){var r,n,a,i,c;const t=e==null?void 0:e.defaultView;if(t)try{t.focus(),(n=(r=e==null?void 0:e.body)==null?void 0:r.focus)==null||n.call(r),(i=(a=e==null?void 0:e.documentElement)==null?void 0:a.focus)==null||i.call(a),(c=t.requestAnimationFrame)==null||c.call(t,()=>{var l,u;try{t.focus(),(u=(l=e==null?void 0:e.body)==null?void 0:l.focus)==null||u.call(l)}catch{}})}catch{}}function Nr(e,t){e.classList.remove(Un.className,zn.className),e.classList.add(t==="light"?Un.className:zn.className)}function Zo(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 Xh(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 Jh(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:_r(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 ei(e,t){const r=new Set(t.map(n=>n.tabKey));for(const n of[...e.panels])Lt(n.id)||r.has(n.id)||e.removePanel(n);for(const n of t){const a=e.getPanel(n.tabKey);if(a){a.update({params:{tabKey:n.tabKey}}),a.title!==_r(n)&&a.api.setTitle(_r(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:_r(n),params:{kind:"conversation",tabKey:n.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function ti(e,t,r){var u,f;const n=r?Yh(r):null;for(const d of[...e.panels])Lt(d.id)&&(!n||d.id!==n)&&e.removePanel(d);if(!r||!n)return;const a=_t(t,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=pc(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 Qh({params:e,api:t}){var h;const r=on(),n=o.useRef(null),[a,i]=o.useState(t.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=nn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(t.isActive);const m=[t.onDidActiveChange(w=>i(w.isActive)),t.onDidActiveGroupChange(w=>{if(!t.isActive&&!w.isActive){i(!1);return}i(t.isActive)})];return()=>{for(const w of m)w.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(Va,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const d=!qe(c)&&Ts(c)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(Ua,{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 Zh({params:e}){var u;const t=on(),r=o.useMemo(()=>_t([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=o.useMemo(()=>t.ides.find(f=>f.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((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}=el({doId:a,targetSessionId:r?Qi(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(Di,{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 ex(){const e=on();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(Va,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function tx(e){var w,S;Xh(e);const t=on(),r=o.useCallback(p=>{"button"in p&&p.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const p=_t([...t.conversationsByTabKey.values()],e.params.routeId),x=((w=e.api.group.activePanel)==null?void 0:w.id)===e.api.id,j=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${x?" is-active":""}${j?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(p==null?void 0:p.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:p!=null&&p.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:p.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const n=t.conversationsByTabKey.get(e.params.tabKey);if(!n)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const a=((S=e.api.group.activePanel)==null?void 0:S.id)===e.api.id,i=e.api.isGroupActive,c=Qr(n,t.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,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:tt(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:tt(n)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ts(n)}):u?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ts(n)}):s.jsx("span",{children:ts(n)})})]}),m&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:m,children:m})]})}function sx({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:w,onOpenNewSession:S,onRequestScrollToBottom:p,requestedActiveTabKey:x,requestedRemoteIdeId:j,onRequestedActiveTabConsumed:b,scrollToBottomRequest:N,liveSessionInboxState:T,layoutProfile:y}){var ft,He,vt;const{theme:C}=$a(),{sendCommand:k}=jt(),v=o.useRef(null),g=o.useRef(null),D=o.useRef(!1),M=o.useRef(!1),I=o.useRef(!1),P=o.useRef(null),K=o.useRef([]),[V,L]=o.useState(null),[R,G]=o.useState(!1),[B,E]=o.useState(!1),[W,J]=o.useState(0),be=o.useRef(null),he=o.useRef(typeof window>"u"?{}:Rp(y)),de=o.useMemo(()=>new Map(e.map($=>[$.tabKey,$])),[e]),ye=o.useMemo(()=>{const $=v.current;return $?$.groups.some(O=>{try{const U=O.model.location.type;return U!=="floating"&&U!=="popout"?!1:O.panels.some(q=>de.has(q.id))}catch{return!1}}):!1},[de,W,e]),ge=o.useCallback(()=>{var $;($=v.current)==null||$.focus()},[]),ve=o.useCallback(($,O)=>{p==null||p($,O)},[p]),z=o.useCallback($=>{const O=document,U=$.document;for(const Ce of O.querySelectorAll('link[rel="stylesheet"]')){const se=U.createElement("link");se.rel="stylesheet",se.href=Ce.href,Ce.crossOrigin&&(se.crossOrigin=Ce.crossOrigin),U.head.appendChild(se)}for(const Ce of O.querySelectorAll("style")){const se=U.createElement("style");se.textContent=Ce.textContent,U.head.appendChild(se)}const q=[];for(const Ce of O.styleSheets)try{for(const se of Ce.cssRules)se instanceof CSSStyleRule&&(se.selectorText===":root"||se.selectorText==="html")&&q.push(se.cssText)}catch{}if(q.length>0){const Ce=U.createElement("style");Ce.textContent=q.join(`
|
|
43
43
|
`),U.head.appendChild(Ce)}const ie=O.documentElement.getAttribute("data-theme");ie&&U.documentElement.setAttribute("data-theme",ie),U.documentElement.style.colorScheme=ie==="light"?"light":"dark",U.body.className=O.body.className;const Se=O.documentElement.getAttribute("style");Se&&U.documentElement.setAttribute("style",Se);const Ie=U.getElementById("dv-popout-window");Ie instanceof HTMLElement&&(Ie.classList.add("adhdev-dockview"),Nr(Ie,C))},[C]),F=o.useCallback(()=>{var O;const $=v.current;if($)for(const U of $.groups)try{const q=(O=U.element)==null?void 0:O.ownerDocument;if(!q||q===document)continue;const ie=q.getElementById("dv-popout-window");ie instanceof HTMLElement&&(ie.classList.add("adhdev-dockview"),Nr(ie,C));const Se=document.documentElement.getAttribute("data-theme");Se&&q.documentElement.setAttribute("data-theme",Se),q.documentElement.style.colorScheme=Se==="light"?"light":"dark",q.body.className=document.body.className;const Ie=document.documentElement.getAttribute("style");Ie?q.documentElement.setAttribute("style",Ie):q.documentElement.removeAttribute("style")}catch{}},[C]),Q=o.useCallback(()=>{var O;const $=v.current;if($)for(const U of $.groups)try{const q=(O=U.element)==null?void 0:O.ownerDocument;if(!q||q===document)continue;const ie=q.getElementById("dv-popout-window");if(!(ie instanceof HTMLElement))continue;ie.classList.add("adhdev-dockview"),Nr(ie,C),ie.classList.toggle("is-showing-dockview-overlay",B),ie.classList.toggle("is-dragging-dockview",R)}catch{}},[R,B,C]),ue=o.useCallback($=>{const O=v.current;if(!O)return;const U=O.getPanel($);U&&O.addPopoutGroup(U,{popoutUrl:"/popout.html",onDidOpen:({window:q})=>{z(q),X();const ie=de.get($);q.document.title=ie?`${tt(ie)} — ADHDev`:"ADHDev — Popout"}})},[de,z]),te=o.useCallback($=>{const O=v.current,U=O==null?void 0:O.getPanel($);if(!O||!U)return;const q=O.groups.filter(ie=>{var Se;try{return((Se=ie.element)==null?void 0:Se.ownerDocument)===document}catch{return!0}});q.length>0?U.api.moveTo({group:q[0],position:"center"}):U.api.moveTo({position:"center"}),U.api.setActive()},[]),fe=o.useCallback($=>{var q;const O=v.current;if(!O)return!1;const U=O.getPanel($);if(!U)return!1;try{return((q=U.group.element)==null?void 0:q.ownerDocument)!==document}catch{return!1}},[]),ne=o.useCallback($=>{fe($)&&te($),d($)},[fe,te,d]),xe=o.useCallback($=>{const O=v.current,U=O==null?void 0:O.getPanel($);!O||!U||O.addFloatingGroup(U,{width:600,height:500})},[]),re=o.useCallback($=>{var U;const O=(U=v.current)==null?void 0:U.getPanel($);if(!O)return!1;try{return O.group.model.location.type==="floating"}catch{return!1}},[]),le=o.useCallback(()=>{var O,U;const $=(U=(O=v.current)==null?void 0:O.activePanel)==null?void 0:U.id;return!$||Lt($)?null:de.has($)?$:null},[de]),oe=o.useCallback($=>{const O=v.current,U=O==null?void 0:O.getPanel($);if(!O||!U)return;const q=O.groups.filter(ie=>{try{return ie.model.location.type==="grid"}catch{return!0}});q.length>0?U.api.moveTo({group:q[0],position:"center"}):U.api.moveTo({position:"center"}),U.api.setActive()},[]),Y=o.useCallback(()=>{var Se;const $=v.current;if(!$)return;const U=$.groups.filter(Ie=>{var Ce;try{return((Ce=Ie.element)==null?void 0:Ce.ownerDocument)===document&&Ie.model.location.type==="grid"}catch{return!1}})[0]||null,q=[...$.panels];for(const Ie of q){const Ce=(Se=Ie.group.element)==null?void 0:Se.ownerDocument,se=Ie.group.model.location.type;Ce===document&&se==="grid"||(U&&U.id!==Ie.group.id?Ie.api.moveTo({group:U,position:"center"}):Ie.api.moveTo({position:"center"}))}const ie=$.activePanel;ie&&(ie.group.model.openPanel(ie),ie.api.setActive()),Ln(document)},[]),X=o.useCallback(()=>{var O,U;const $=v.current;if($)for(const q of $.groups){const ie=(O=q.element)==null?void 0:O.ownerDocument;if(!ie||ie===document)continue;const Se=ie.getElementById("dv-popout-window");if(!(Se instanceof HTMLElement))continue;let Ie=null,Ce=ie.title||"ADHDev",se="Popout workspace";const ke=q.activePanel;if(ke)if(Ie=ke.id,Lt(ke.id)){const Pe=((U=ke.params)==null?void 0:U.routeId)||ke.id.slice(7),_=_t([...de.values()],Pe);Ce=pc(_),se=_!=null&&_.machineName?`Remote view · ${_.machineName}`:"Remote view"}else{const Pe=de.get(ke.id);Ce=Pe?tt(Pe):ke.title||ke.id,se=Pe?ts(Pe):"Dockview panel"}ie.title=`${Ce} — ADHDev`;const Oe=Array.from(ie.querySelectorAll("#adhdev-popout-header"));for(const Pe of Oe)Pe.remove();const Ue=ie.createElement("div");Ue.id="adhdev-popout-header",ie.body.appendChild(Ue),Ue.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(";")),Ue.innerHTML=`
|
|
44
44
|
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
45
45
|
<div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
|
|
@@ -68,9 +68,9 @@ This will disconnect CDP and optionally kill the process.`))try{const E=await r(
|
|
|
68
68
|
|
|
69
69
|
`)}function Hx({daemonLogs:e,trace:t,webEvents:r,daemonLogKind:n,daemonFetchError:a,traceFetchError:i,searchQuery:c}){const l=fl(e,c),u=pl(t,c),f=hl(r,c),d=l.filter(w=>w.level==="warn"||w.level==="error").map(w=>({source:"daemon",level:w.level,timestamp:w.timestamp,label:"daemon",detail:w.message})),h=u.filter(w=>w.level==="warn"||w.level==="error").map(w=>({source:"trace",level:w.level,timestamp:w.ts,label:`${w.category}.${w.stage}`,detail:Qs(w.payload,320)||`${w.category}.${w.stage}`})),m=[...d,...h].sort((w,S)=>S.timestamp-w.timestamp);return{daemonCount:l.length,traceCount:u.length,webCount:f.length,issueCount:m.length,latestIssue:m[0]||null,hasAnyData:n==="text"||l.length>0||u.length>0||f.length>0,hasBlockingError:!!(a||i)}}function ai(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function oi(e){return e==="error"?"text-red-300 border-red-500/25 bg-red-500/[0.05]":e==="warn"?"text-amber-200 border-amber-500/25 bg-amber-500/[0.05]":e==="debug"?"text-slate-300 border-slate-500/25 bg-slate-500/[0.05]":"text-text-secondary border-border-subtle bg-bg-primary"}function Dn(e){return e==="good"?"border-emerald-500/20 bg-emerald-500/[0.05]":e==="warning"?"border-amber-500/20 bg-amber-500/[0.05]":e==="danger"?"border-red-500/20 bg-red-500/[0.05]":"border-border-subtle bg-bg-secondary"}function Fx({machineId:e,sendDaemonCommand:t}){var X,ae;const[r,n]=o.useState([]),[a,i]=o.useState("empty"),[c,l]=o.useState(""),[u,f]=o.useState([]),[d,h]=o.useState([]),[m,w]=o.useState(0),[S,p]=o.useState(0),[x,j]=o.useState(null),[b,N]=o.useState(!0),[T,y]=o.useState("info"),[C,k]=o.useState("info"),[v,g]=o.useState("all"),[D,M]=o.useState(""),[I,P]=o.useState(!0),[K,V]=o.useState(!0),[L,R]=o.useState(""),[G,B]=o.useState(""),[E,W]=o.useState(0),[J,be]=o.useState({daemon:!0,trace:!1,web:!1}),he=o.useRef(null),de=o.useRef(!1),ye=o.useMemo(()=>Ex(u,v),[u,v]),ge=o.useMemo(()=>fl(r,D),[r,D]),ve=o.useMemo(()=>Kx(c,D),[c,D]),z=o.useMemo(()=>pl(ye,D),[ye,D]),F=o.useMemo(()=>hl(d,D),[d,D]),Q=o.useMemo(()=>C==="issues"?ge.filter(A=>A.level==="warn"||A.level==="error"):C==="info"?ge.filter(A=>A.level!=="debug"):ge,[ge,C]),ue=o.useMemo(()=>C==="all"?ve:[],[ve,C]),te=o.useMemo(()=>C==="issues"?z.filter(A=>A.level==="warn"||A.level==="error"):C==="info"?z.filter(A=>A.level!=="debug"):z,[z,C]),fe=o.useMemo(()=>C==="issues"?[]:F,[F,C]),ne=o.useMemo(()=>Ox({daemonLogs:ge,daemonRawLines:ve,trace:z,webEvents:F}),[ge,ve,z,F]),xe=o.useMemo(()=>Hx({daemonLogs:r,trace:ye,webEvents:d,daemonLogKind:a,daemonFetchError:L,traceFetchError:G,searchQuery:D}),[L,a,r,ye,D,G,d]),re=o.useCallback(async()=>{if(!e)return;const[A,H]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:T,since:m}),t(e,"get_debug_trace",Dx({count:120,since:S,category:v}))]);if(A.status==="fulfilled"){const ce=A.value,me=(ce==null?void 0:ce.result)||ce,we=Bx(me);if(P(!1),R((ce==null?void 0:ce.success)===!1?String((ce==null?void 0:ce.error)||"Could not load daemon logs"):""),i(we.kind),l(we.rawText),we.entries.length>0){n(Ae=>(m>0?[...Ae,...we.entries]:we.entries).slice(-300));const _e=we.entries.reduce((Ae,Ke)=>Math.max(Ae,Number(Ke.timestamp||0)),m);_e>m&&w(_e)}else we.kind!=="structured"&&m===0&&n([])}else P(!1),R(A.reason instanceof Error?A.reason.message:"Could not load daemon logs");if(H.status==="fulfilled"){const ce=H.value,me=(ce==null?void 0:ce.result)||ce;if((ce==null?void 0:ce.success)===!1)B(String((ce==null?void 0:ce.error)||"Could not load daemon trace"));else if(Array.isArray(me==null?void 0:me.trace)){B(""),f(me.trace.slice(-120));const we=me.trace.reduce((_e,Ae)=>Math.max(_e,Number(Ae.ts||0)),S);we>S&&p(we)}else B(""),f([]);V(!1)}else V(!1),B(H.reason instanceof Error?H.reason.message:"Could not load daemon trace");h(ks.list({limit:120})),j(Date.now())},[m,S,T,e,t,v]);o.useEffect(()=>{if(!e||(re(),!b))return;const A=setInterval(()=>{re()},3e3);return()=>clearInterval(A)},[b,re,e,E]),o.useEffect(()=>{if(b&&(Q.length>0||ue.length>0||te.length>0||fe.length>0)){const A=de.current?"smooth":"instant";setTimeout(()=>{var H;(H=he.current)==null||H.scrollIntoView({behavior:A}),de.current=!0},50)}},[Q.length,ue.length,te.length,fe.length,b]),o.useEffect(()=>{f([]),p(0),V(!0)},[v]);const le=((X=xe.latestIssue)==null?void 0:X.level)==="error"?"danger":((ae=xe.latestIssue)==null?void 0:ae.level)==="warn"?"warning":"good",oe=L||G?"danger":b?"good":"neutral",Y=o.useCallback(async()=>{var H;const A=Wx({daemonLogs:Q,daemonRawLines:ue,trace:te,webEvents:fe});if(!A.trim()){lt.showToast("복사할 visible logs가 없습니다.","info");return}try{await((H=navigator.clipboard)==null?void 0:H.writeText(A)),lt.showToast("Visible logs를 클립보드에 복사했습니다.","success")}catch(ce){lt.showToast(ce instanceof Error?ce.message:"Could not copy visible logs","warning")}},[Q,ue,te,fe]);return s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"Level"}),["debug","info","warn","error"].map(A=>s.jsx("button",{onClick:()=>{y(A),n([]),l(""),i("empty"),w(0),P(!0)},className:`machine-btn text-[10px] px-2 py-0.5 ${T===A?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:A.toUpperCase()},A)),s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider ml-3 mr-1",children:"Trace"}),_x.map(A=>s.jsx("button",{onClick:()=>g(A.value),className:`machine-btn text-[10px] px-2 py-0.5 ${v===A.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:A.label},A.value))]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${ne.info})`},{id:"issues",label:`Issues (${ne.issues})`},{id:"all",label:`All (${ne.all})`}].map(A=>s.jsx("button",{type:"button",onClick:()=>k(A.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${C===A.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:A.label},A.id))}),s.jsx("input",{value:D,onChange:A=>M(A.target.value),placeholder:"Search visible logs, trace, events…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"}),s.jsx("button",{onClick:()=>{Y()},className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:()=>N(A=>!A),className:`machine-btn ${b?"text-green-500 border-green-500/30":""}`,children:b?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:()=>W(A=>A+1),className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:()=>{n([]),l(""),i("empty"),f([]),h([]),w(0),p(0),j(null),R(""),B(""),P(!0),V(!0),ks.clear()},className:"machine-btn",children:"Clear"})]})]}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${Dn(xe.issueCount>0?"warning":"good")}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Visible signals"}),s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:["daemon ",Q.length+ue.length," · trace ",te.length," · web ",fe.length]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:D.trim()?`Filtered by “${D.trim()}”`:"Showing the latest buffered entries"})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Dn(le)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Attention needed"}),xe.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[xe.latestIssue.source," · ",xe.latestIssue.label]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:xe.latestIssue.detail}),s.jsxs("div",{className:"text-[10px] text-text-muted mt-2",children:[xe.issueCount," warn/error signal(s) · ",ai(xe.latestIssue.timestamp)]})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No recent warn/error signal"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use search or lower the log level if you need more context."})]})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Dn(oe)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Fetch status"}),s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:L||G?"Needs attention":b?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",ai(x)]}),(L||G)&&s.jsxs("div",{className:"text-[11px] text-red-300 mt-2 space-y-1",children:[L&&s.jsxs("div",{children:["Daemon logs: ",L]}),G&&s.jsxs("div",{children:["Daemon trace: ",G]})]})]})]}),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:()=>be(A=>({...A,daemon:!A.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:a==="text"?`${ue.length} visible raw line(s) from file fallback`:`${Q.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:J.daemon?"Hide":"Show"})]}),J.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:[I&&!xe.hasAnyData&&!L&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!I&&L&&a==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:L}),!I&&a==="empty"&&!L&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),a==="text"&&ue.length===0&&c&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:C==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),a==="structured"&&Q.length===0&&r.length>0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),a==="text"&&ue.map((A,H)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:A},`raw-${H}`)),a!=="text"&&Q.map((A,H)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${oi(A.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(A.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:A.level==="error"?"ERR":A.level==="warn"?"WRN":A.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:A.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:()=>be(A=>({...A,trace:!A.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Structured daemon trace",v==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[te.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:J.trace?"Hide":"Show"})]}),J.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:[K&&te.length===0&&!G&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!K&&G&&te.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:G}),!K&&te.length===0&&!G&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:D.trim()?"No trace entries match the current search.":v==="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."}),te.map(A=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${oi(A.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(A.ts).toLocaleTimeString()}),s.jsx("span",{children:A.level.toUpperCase()}),s.jsxs("span",{children:[A.category,".",A.stage]}),A.interactionId&&s.jsxs("span",{children:["ix=",A.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Qs(A.payload,360)||"No payload"})]},A.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:()=>be(A=>({...A,web:!A.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[fe.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:J.web?"Hide":"Show"})]}),J.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:[fe.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:D.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),fe.map(A=>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(A.ts).toLocaleTimeString()}),s.jsx("span",{children:A.kind}),A.topic&&s.jsxs("span",{children:["topic=",A.topic]}),A.interactionId&&s.jsxs("span",{children:["ix=",A.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Qs(A.payload,360)||"No payload"})]},A.id))]})]})]}),s.jsx("div",{ref:he})]})}function Ux(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 xl(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 zx(e){var a;const t=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=xl((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 Vx(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function En(e){return e==="live"?"These runtimes are live now and are the only attachable targets.":e==="recovery"?"These records were restored from session-host state and are not live attach targets until you explicitly recover or restart them.":"These inactive records are shown for reference and usually need restart before they are useful again."}function $n(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Bn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function ii(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 Gx(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function qx(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 Yx(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 Xx({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,u]=o.useState(!1),f=ip(e,{enabled:!!e,includeSessions:!0,limit:Co,intervalMs:km}),d=f.diagnostics,h=f.loading,m=f.applyDiagnostics,w=o.useMemo(()=>Ux({diagnostics:d,loading:h,refreshing:l,error:n}),[d,h,l,n]),S=o.useMemo(()=>new Map(t.map(M=>[M.sessionId||M.id,M])),[t]),p=o.useCallback(async()=>{if(e){u(!0);try{const M=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Co}),I=$n(M);if(!(I!=null&&I.success))throw new Error((I==null?void 0:I.error)||"Could not load hosted runtime diagnostics");m(I.diagnostics||I.result||null),a("")}catch(M){const I=M instanceof Error?M.message:"Could not load hosted runtime diagnostics";a(I)}finally{u(!1)}}},[m,e,r]);o.useEffect(()=>{!e||d||h||l||p()},[d,h,e,p,l]);const x=o.useCallback(async(M,I)=>{const P=`${M}:${I.sessionId}`;if(!(M==="session_host_stop_session"&&!window.confirm(`Stop ${I.displayName}?
|
|
70
70
|
This will terminate the hosted runtime.`))){c(P);try{const K=await r(e,M,{sessionId:I.sessionId}),V=$n(K);if(!(V!=null&&V.success))throw new Error((V==null?void 0:V.error)||"Session host action failed");const L=M==="session_host_resume_session"?"resumed":M==="session_host_restart_session"?"restarted":"stopped";lt.showToast(`Session host ${L}: ${I.displayName}`,"success"),await p()}catch(K){const V=K instanceof Error?K.message:"Session host action failed";lt.showToast(V,"warning"),a(V)}finally{c(K=>K===P?null:K)}}},[e,p,r]),j=o.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
71
|
-
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){c("session_host_prune_duplicate_sessions");try{const I=await r(e,"session_host_prune_duplicate_sessions",{}),P=$n(I);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Duplicate prune failed");const K=P.result||{},V=Array.isArray(K.prunedSessionIds)?K.prunedSessionIds.length:0,L=typeof K.duplicateGroupCount=="number"?K.duplicateGroupCount:0;lt.showToast(`Pruned ${V} duplicate runtime(s) across ${L} group(s)`,"success"),await p()}catch(I){const P=I instanceof Error?I.message:"Duplicate prune failed";lt.showToast(P,"warning"),a(P)}finally{c(I=>I==="session_host_prune_duplicate_sessions"?null:I)}}},[e,p,r]),b=o.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((M,I)=>(I.lastActivityAt||0)-(M.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)||[]}:zx(b),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,b]),T=N.liveRuntimes,y=N.recoverySnapshots,C=N.inactiveRecords,k=o.useMemo(()=>Yx(T),[T]),v=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(M=>M.level==="warn"||M.level==="error")||null,[d==null?void 0:d.recentLogs]),D=(M,I)=>{var W;const P=i===`session_host_resume_session:${M.sessionId}`,K=i===`session_host_restart_session:${M.sessionId}`,V=i===`session_host_stop_session:${M.sessionId}`,L=xl(M.meta),R=S.get(M.sessionId),G=M.attachedClients.length===1?"1 client":`${M.attachedClients.length} clients`,B=I==="recovery"?"Recover":"Resume",E=Vx(I);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:M.displayName||(R==null?void 0:R.cliName)||M.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${qx(M.lifecycle)}`,children:M.lifecycle}),L&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:L})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:M.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||M.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:M.runtimeKey}),M.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",M.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((W=M.writeOwner)==null?void 0:W.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Gx(M.writeOwner)}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[s.jsx(Si,{size:11})," ",G]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",ii(M.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",E]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[I==="recovery"&&(M.lifecycle==="interrupted"||M.lifecycle==="failed"||M.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{x("session_host_resume_session",M)},children:P?`${B}ing…`:B}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{x("session_host_restart_session",M)},children:K?"Restarting…":"Restart"}),I==="live"&&(M.lifecycle==="running"||M.lifecycle==="starting"||M.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!i,onClick:()=>{x("session_host_stop_session",M)},children:V?"Stopping…":"Stop"})]})]})},M.sessionId)};return s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(ls,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:ff()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[k>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{j()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${k})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${w.toneClass}`,children:w.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:h||l,children:[s.jsx(er,{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:ii(d.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Bn(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:[Bn(g.timestamp),g.sessionId?` · ${g.sessionId}`:""]})]}),s.jsxs("div",{className:"mb-4 space-y-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(ga,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:En("live")}),T.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:T.map(M=>D(M,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(ls,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:En("recovery")}),y.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:y.map(M=>D(M,"recovery"))})]}),C.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:En("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:C.map(M=>D(M,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),v.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:v.map(M=>{var P;const I=b.find(K=>K.sessionId===M.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(I==null?void 0:I.displayName)||((P=S.get(M.sessionId))==null?void 0:P.cliName)||M.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[M.action,M.lifecycle?` · ${M.lifecycle}`:"",M.detail?` · ${M.detail}`:"",M.error?` · ${M.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${M.success===!1?"text-red-300":"text-text-secondary"}`,children:Bn(M.timestamp)})]},`${M.sessionId}:${M.timestamp}:${M.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:d.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function Jx({machine:e,launchPick:t,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return s.jsx("div",{className:"fixed inset-0 z-[100] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(i=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{a(null),n({cliType:t.cliType,workspaceId:i.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),n({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:"Default workspace"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{a(null),n({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:"Home directory"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>a(null),children:"Cancel"})]})]})})}function Kn({icon:e,children:t}){return s.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,s.jsx("span",{children:t})]})}function On({children:e,className:t=""}){return s.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function Qx({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=Hs(e,"0.9.22");return s.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[l.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Kn,{icon:s.jsx(Ft,{size:13}),children:"Current Chats"}),s.jsx(On,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(h=>{const m=ea(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:tt(h)}),m>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Jr(m)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:us(h)})]},h.tabKey)})})})]}),u.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Kn,{icon:s.jsx(Mi,{size:13}),children:"Recent Launches"}),s.jsx(On,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(h=>{const{metaText:m,updatedLabel:w}=Xc(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}),w&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:w})]}),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(Kn,{icon:s.jsx(qs,{size:13}),children:"Daemon Update"}),s.jsx(On,{className:"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children: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(er,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Zx(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const eb={ide:{label:"IDE",plural:"IDEs",accent:"border-blue-500/[0.12]"},cli:{label:"CLI",plural:"CLIs",accent:"border-violet-500/[0.12]"},acp:{label:"ACP Agent",plural:"ACP agents",accent:"border-emerald-500/[0.12]"}};function Ir(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Wn({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:f}){const d=As(),{handleLaunchIde:h,handleStopCli:m,handleRestartIde:w,handleStopIde:S,handleDetectIdes:p,launchingIde:x,launchingAgentType:j,addLog:b}=c,[N,T]=o.useState(null),y=o.useCallback(_=>{_&&d(Gt(_))},[d]),C=eb[e],k=e==="ide",v=e==="acp",g=o.useMemo(()=>n.filter(_=>_.category===e&&(e==="ide"||_.installed!==!1)),[e,n]),D=o.useMemo(()=>new Map(g.map(_=>[_.type,_.displayName||_.type])),[g]),[M,I]=o.useState(""),[P,K]=o.useState(""),[V,L]=o.useState([]),[R,G]=o.useState(""),[B,E]=o.useState(""),[W,J]=o.useState([]),[be,he]=o.useState(!1),[de,ye]=o.useState(!1),[ge,ve]=o.useState(""),[z,F]=o.useState(!1),[Q,ue]=o.useState(()=>ht()),[te,fe]=o.useState(null),[ne,xe]=o.useState(f?"__custom__":u||t.defaultWorkspaceId||""),[re,le]=o.useState(f||""),[oe,Y]=o.useState([]),[X,ae]=o.useState(!1),[A,H]=o.useState(""),[ce,me]=o.useState([]),[we,_e]=o.useState(!1),[Ae,Ke]=o.useState(""),Fe=o.useRef(null),[ze,ot]=o.useState(null),it=o.useRef("__home__"),[dt,ut]=o.useState("__home__"),[mt,Xe]=o.useState(!1),rt=o.useRef(0),je=oe.filter(_=>!a.some(ee=>ee.type===_&&bt(ee.status)!=="stopped")),Ee=o.useRef({});o.useEffect(()=>{t.defaultWorkspaceId&&!ne&&xe(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),o.useEffect(()=>{if(f){xe("__custom__"),le(f);return}u&&(xe(u),le(""))},[u,f]),o.useEffect(()=>{k||M&&(g.some(_=>_.type===M)||(I(""),E("")))},[g,k,M]);const Be=(()=>{if(ne==="__custom__")return re.trim();if(!ne)return"";const _=(t.workspaces||[]).find(ee=>ee.id===ne);return(_==null?void 0:_.path)||""})(),nt=o.useCallback(_=>{const ee=Ee.current[_];ee&&(clearTimeout(ee),delete Ee.current[_]),Y(pe=>pe.includes(_)?pe.filter(Re=>Re!==_):pe)},[]),st=o.useRef(new Set),yt=o.useCallback(async _=>{if(l){_e(!0),Ke("");try{const ee=await rn(l,r,_);H(ee.path),le(ee.path),me(ee.directories)}catch(ee){Ke(ee instanceof Error?ee.message:"Could not load folder")}finally{_e(!1)}}},[r,l]),Z=o.useCallback(()=>{if(!l)return;xe("__custom__"),ae(!0);const _=a.map(pe=>pe.workspace),ee=sn(t.platform,tn(re.trim(),Be,f,_,t.defaultWorkspacePath,(t.workspaces||[]).map(pe=>pe.path)));yt(ee)},[re,f,yt,t.defaultWorkspacePath,t.platform,t.workspaces,a,Be,l]),Le=o.useCallback(_=>{const ee=String(_.workspace||"").trim();if(!ee)return;const pe=(t.workspaces||[]).find(Re=>Ir(Re.path)===Ir(ee));if(pe){xe(pe.id),le("");return}xe("__custom__"),le(ee)},[t.workspaces]),De=o.useCallback(_=>{const ee=String(_.workspace||"").trim();if(!ee)return{workspaceId:null,workspacePath:"",useHome:!0};const pe=(t.workspaces||[]).find(Re=>Ir(Re.path)===Ir(ee));return pe?{workspaceId:pe.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:ee,useHome:!1}},[t.workspaces]),et=o.useCallback(async _=>{if(!l||!_||e!=="cli"){J([]),he(!1),ye(!1),ve("");return}const ee=rt.current+1;rt.current=ee,he(!0),ve("");try{const pe=await l(r,"list_saved_sessions",{providerType:_,kind:"cli",limit:30});if(rt.current!==ee)return;const Re=(pe==null?void 0:pe.result)??pe;J(Array.isArray(Re==null?void 0:Re.sessions)?Re.sessions:[])}catch(pe){if(rt.current!==ee)return;J([]),ve(pe instanceof Error?pe.message:"Could not load saved sessions")}finally{rt.current===ee&&(he(!1),ye(!0))}},[e,r,l]),Tt=o.useMemo(()=>{if(e!=="cli"||!M)return null;const _=D.get(M)||M;return{routeId:r,daemonId:r,providerSessionId:B||void 0,transport:"pty",mode:"chat",agentName:_,agentType:M,status:"idle",title:_,messages:[],ideType:M,workspaceName:Be,displayPrimary:_,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${M}`}},[e,r,D,Be,B,M]),ft=o.useCallback(_=>{if(e==="ide"||!_){L([]);return}L(ll(r,_))},[e,r]);o.useEffect(()=>{rt.current+=1,E(""),ft(M),ye(!1),J([]),ve(""),he(!1)},[e,ft,et,M]);const He=o.useMemo(()=>W.find(_=>_.providerSessionId===B)||null,[W,B]);o.useEffect(()=>{if(!B)return;const _=W.find(ee=>ee.providerSessionId===B);_!=null&&_.canResume||E("")},[W,B]);const vt=o.useCallback((_,ee)=>{Fe.current=ee,it.current=_.selectedWorkspaceKey||"__home__",ut(_.selectedWorkspaceKey||"__home__"),ot(_)},[]),$=o.useCallback(()=>{Fe.current&&(Xe(!0),Fe.current().finally(()=>{Fe.current=null,Xe(!1),ot(null)}))},[]),O=o.useCallback(_=>{if(!_)return;Y(pe=>pe.includes(_)?pe:[...pe,_]);const ee=Ee.current[_];ee&&clearTimeout(ee),Ee.current[_]=setTimeout(()=>{Y(pe=>pe.includes(_)?pe.filter(Re=>Re!==_):pe),delete Ee.current[_]},2e4)},[]);o.useEffect(()=>{for(const ee of a)bt(ee.status)!=="stopped"&&(oe.includes(ee.type)&&!st.current.has(ee.type)&&(st.current.add(ee.type),b("info",`${D.get(ee.type)||ee.type} launched`,!0)),nt(ee.type));const _=new Set(a.filter(ee=>bt(ee.status)!=="stopped").map(ee=>ee.type));st.current.forEach(ee=>{!oe.includes(ee)&&!_.has(ee)&&st.current.delete(ee)})},[b,nt,a,oe,D]),o.useEffect(()=>()=>{Object.values(Ee.current).forEach(clearTimeout),Ee.current={}},[]);const[U,q]=o.useState({}),[ie,Se]=o.useState(null);o.useEffect(()=>{if(!k||!r||!l)return;(async()=>{try{const ee=await l(r,"get_ide_extensions",{}),pe=(ee==null?void 0:ee.result)||ee;pe!=null&&pe.success&&(pe!=null&&pe.ideExtensions)&&q(pe.ideExtensions)}catch{}})()},[k,r,l]);const Ie=_=>k?Ze(_.type):e==="cli"?_.cliName:_.acpName,Ce=k?t.detectedIdes||[]:[],se=o.useCallback(async _=>{const ee=(_==null?void 0:_.type)||M,pe=(_==null?void 0:_.workspacePath)??Be;if(k){await h(ee,pe?{workspace:pe}:void 0)&&O(ee);return}const Re=await c.runLaunchCliCore({cliType:ee,dir:_!=null&&_.workspaceId?void 0:pe||void 0,workspaceId:(_==null?void 0:_.workspaceId)||void 0,useHome:(_==null?void 0:_.useHome)||!(_!=null&&_.workspaceId)&&!pe,argsStr:(_==null?void 0:_.argsStr)??(P||void 0),model:(_==null?void 0:_.model)??(v&&R||void 0),resumeSessionId:(_==null?void 0:_.resumeSessionId)||!v&&e==="cli"&&ee===M&&B||void 0});if(Re.success||Re.pending){const Ne=(_==null?void 0:_.argsStr)??P;!k&&(Ne!=null&&Ne.trim())&&(dl(r,ee,Ne),ft(ee)),O(ee),Re.success&&Re.sessionId&&y(Re.sessionId)}},[c,h,v,k,P,R,ft,O,r,y,Be,B,M]),ke=bc(k?"ide":v?"acp":"cli",!k&&!v&&!!B),Oe=gc(k?"ide":v?"acp":"cli",!k&&!v&&!!B),Ue=()=>{var Ne;const _=k?Ze(M):D.get(M)||M,ee=!k&&!v&&!!B,{options:pe,selectedKey:Re}=os({machine:t,currentWorkspaceId:ne&&ne!=="__custom__"?ne:null,currentWorkspacePath:Be});vt({title:ee?Pa(_):ss("start-fresh",_),description:ee?_a():rs("start-fresh"),confirmLabel:ke,busyLabel:Oe,workspaceOptions:pe,selectedWorkspaceKey:Re,details:[{label:"Mode",value:C.label},{label:"Provider",value:_},...!k&&e==="cli"&&B?[{label:"Resume",value:((Ne=W.find(Me=>Me.providerSessionId===B))==null?void 0:Ne.title)||B}]:[],...!k&&P.trim()?[{label:"Arguments",value:P.trim()}]:[],...v&&R.trim()?[{label:"Model",value:R.trim()}]:[]]},async()=>{const Me=pe.find(Te=>Te.key===it.current);Me!=null&&Me.workspaceId?(xe(Me.workspaceId),le("")):Me!=null&&Me.workspacePath?(xe("__custom__"),le(Me.workspacePath)):(xe(""),le("")),await se({workspaceId:(Me==null?void 0:Me.workspaceId)??null,workspacePath:(Me==null?void 0:Me.workspacePath)??"",useHome:!(Me!=null&&Me.workspaceId)&&!(Me!=null&&Me.workspacePath)})})},Ye=_=>{k?S(_):m(_.type,_.workspace,_.id)},Ve=o.useCallback(async(_,ee,pe=!1)=>{if(_.mode===ee){pe&&_.sessionId&&y(_.sessionId);return}if(!l||!_.sessionId){pe&&_.sessionId&&y(_.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:_.sessionId,cliType:_.type,mode:ee}),pe&&y(_.sessionId)}catch(Re){const Ne=Bc(Re);$c(Re)?console.warn(Ne?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Re instanceof Error?Re.message:String(Re)):console.error("Failed to switch CLI view mode:",Re)}},[r,y,l]),Pe=s.jsxs("div",{className:"mb-3",children:[s.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[s.jsx("select",{value:ne,onChange:_=>{const ee=_.target.value;if(xe(ee),ee==="__custom__"&&l){Z();return}ee!=="__custom__"&&le("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(t.workspaces||[]).length>0?s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(t.workspaces||[]).map(_=>s.jsxs("option",{value:_.id,children:[_.id===t.defaultWorkspaceId?"⭐ ":"",Zr(_.path,_.label)]},_.id)),s.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),s.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]})}),ne==="__custom__"&&(l?s.jsx("button",{type:"button",className:"px-3 py-1.5 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] hover:border-accent-primary text-text-secondary hover:text-text-primary transition-colors",onClick:Z,children:"Select workspace…"}):s.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:re,onChange:_=>le(_.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:ne==="__custom__"?Be?s.jsx("span",{className:"font-mono truncate block",title:Be,children:Be}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":Be?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:ne===t.defaultWorkspaceId?"Default workspace":"Selected workspace"}),s.jsx("span",{className:"font-mono truncate block",title:Be,children:Be})]}):"No workspace selected. This launches in the home directory."})]});return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${C.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 ",C.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:k?Ce.length>0?Ce.map(_=>{const ee=a.find(Te=>(Te.type||"").toLowerCase()===(_.type||"").toLowerCase()&&bt(Te.status)!=="stopped"),pe=_.running||!!ee,Re=!!ee&&ee.cdpConnected,Ne=oe.includes(_.type||_.id||""),Me=M===(_.type||"");return s.jsxs("button",{onClick:()=>{if(Re&&ee){const Te=ee.sessionId;Te?d(Gt(Te),{state:{openRemoteForTabKey:Te}}):d("/dashboard",{state:{openRemoteForTabKey:ee.id}});return}Ne||I(Te=>Te===(_.type||"")?"":_.type||"")},disabled:!!x||Ne,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Re?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Me?"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!==_.type?.4:1},children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i(_.type)}),pe&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Re?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:_.name||Ze(_.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Re?"text-green-400":Ne?"text-orange-400":Me?"text-accent-primary":"text-text-muted"}`,children:Re?"Open Session":Ne?"Starting...":Me?"Configure":"Select"})]})]},_.type)}):s.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",s.jsxs("button",{onClick:p,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[s.jsx(Md,{size:14})," Scan System"]})]}):g.length>0?g.map(_=>{const ee=M===_.type,pe=oe.includes(_.type),Ne=!!a.find(Me=>Me.type===_.type&&bt(Me.status)!=="stopped");return s.jsxs("button",{onClick:()=>I(Me=>Me===_.type?"":_.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:_.icon}),Ne&&s.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:_.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${pe?"text-orange-400":ee?"text-accent-primary":"text-text-muted"}`,children:pe?"Starting...":ee?"Configure":"Select"})]})]},_.type)}):s.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),M&&(k?Ce.find(_=>_.type===M):g.find(_=>_.type===M))&&s.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[s.jsx("span",{children:"Launch Settings"}),s.jsx("span",{className:"text-accent-primary font-bold",children:k?Ze(M):D.get(M)||M})]}),Pe,!k&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!v&&e==="cli"&&s.jsx(ml,{busy:!!j||!!x||oe.includes(M),savedSessionsLoading:be,savedSessionsError:ge,selectedSession:He,onRefresh:()=>void et(M),onOpenHistory:()=>{M&&(F(!0),ul({hasLoadedInitialResults:de,isLoading:be})&&et(M))},onClearSelection:()=>E("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[v&&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:R,onChange:_=>G(_.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:P,onChange:_=>K(_.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),V.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:V.map(_=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>K(_),title:_,children:_},_))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:Ue,disabled:!!j||!!x||oe.includes(M),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:j===M||x===M?"⏳ 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(_=>!a.some(ee=>ee.type===_&&bt(ee.status)!=="stopped")).length,")"]}),a.length===0&&je.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 ",C.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[je.map(_=>s.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:i(_)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:k?Ze(_):D.get(_)||_}),s.jsx("div",{className:"text-[11px] text-text-muted",children:j===_?"Launching process...":"Waiting for process and session to register..."})]})]}),s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:"var(--status-warning)"},children:"starting"})]})},`pending:${_}`)),a.map(_=>{const ee=k?_:null,pe=!k&&!v?_:null,Re=bt(_.status);return s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:i(_.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Ie(_),(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:_.workspace||"—"}),(pe==null?void 0:pe.mode)&&s.jsx("span",{className:pe.mode==="chat"?"text-violet-400":"text-text-secondary",children:pe.mode==="chat"?"Chat view":"Terminal view"})]}),pe&&(pe.runtimeKey||pe.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[pe.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 ",pe.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 Ne;(Ne=navigator.clipboard)==null||Ne.writeText(`adhdev attach ${pe.runtimeKey}`),T(pe.runtimeKey||null),window.setTimeout(()=>{T(Me=>Me===pe.runtimeKey?null:Me)},1200)},children:N===pe.runtimeKey?"Copied":"Copy"})]}),pe.runtimeWriteOwner&&s.jsx("span",{style:{color:pe.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:pe.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Zx(pe.runtimeWriteOwner)})]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Re==="stopped"?"bg-red-500/[0.08] text-red-500":Re==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Re}),k&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const Ne=_.sessionId;if(Ne){d(Gt(Ne),{state:{openRemoteForTabKey:Ne}});return}d("/dashboard",{state:{openRemoteForTabKey:_.id}})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-primary transition-colors cursor-pointer",title:"Open remote control",children:s.jsx(Ct,{size:13})}),s.jsx("button",{onClick:()=>{const Ne=_.workspace||"",{options:Me,selectedKey:Te}=os({machine:t,currentWorkspacePath:Ne});vt({title:ss("restart-ide",Ze(_.type)),description:rs("restart-ide"),confirmLabel:Cs("restart-ide"),busyLabel:Is("restart-ide"),workspaceOptions:Me,selectedWorkspaceKey:Te,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:Ze(_.type)}]},async()=>{const pt=Me.find(Ut=>Ut.key===it.current),ct=(pt==null?void 0:pt.workspacePath)??"";if(ct&&ct!==Ne){await se({type:_.type,workspacePath:ct});return}await w(_)})},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(er,{size:14})})]}),v&&s.jsx("button",{onClick:()=>{const Ne=_.sessionId;Ne&&y(Ne)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"View chat",disabled:!_.sessionId,children:s.jsx(Ft,{size:14})}),pe&&Re!=="stopped"&&s.jsxs(s.Fragment,{children:[pe.mode&&s.jsx(Ta,{mode:pe.mode,onChange:Ne=>void Ve(pe,Ne,!1),compact:!0}),s.jsx("button",{onClick:()=>{const Ne=_.sessionId;Ne&&y(Ne)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"Open current view in dashboard",disabled:!_.sessionId,children:pe.mode==="chat"?s.jsx(Ft,{size:14}):s.jsx(Ct,{size:13})})]}),Re==="stopped"?s.jsx("button",{onClick:()=>{const Ne=_.workspace||"",Me=k?Ze(_.type):Ie(_),{options:Te,selectedKey:pt}=os({machine:t,currentWorkspacePath:Ne});vt({title:ss("restart-stopped",Me),description:rs("restart-stopped"),confirmLabel:Cs("restart-stopped"),busyLabel:Is("restart-stopped"),workspaceOptions:Te,selectedWorkspaceKey:pt,details:[{label:"Mode",value:C.label},{label:"Provider",value:Me}]},async()=>{const ct=Te.find(Ut=>Ut.key===it.current);await se({type:_.type,workspaceId:(ct==null?void 0:ct.workspaceId)??null,workspacePath:(ct==null?void 0:ct.workspacePath)??"",useHome:!(ct!=null&&ct.workspaceId)&&!(ct!=null&&ct.workspacePath)})})},disabled:oe.includes(_.type),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-green-500/20 text-green-400 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",title:"Restart",children:oe.includes(_.type)?"⏳":s.jsx(ya,{size:14})}):s.jsx("button",{onClick:()=>Ye(_),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-red-500/20 text-red-400 transition-colors cursor-pointer",title:"Stop",children:s.jsx(wt,{size:14})})]})]}),ee&&ee.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:ee.aiAgents.map(Ne=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Ki(Ne.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Ne.name," · ",bt(Ne.status)]},Ne.id))}),ee&&(U[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:(U[ee.type]||[]).map(Ne=>s.jsxs("button",{disabled:ie===`${ee.type}.${Ne.type}`,onClick:async()=>{const Me=`${ee.type}.${Ne.type}`;Se(Me);try{await l(r,"set_ide_extension",{ideType:ee.type,extensionType:Ne.type,enabled:!Ne.enabled}),q(Te=>({...Te,[ee.type]:(Te[ee.type]||[]).map(pt=>pt.type===Ne.type?{...pt,enabled:!pt.enabled}:pt)}))}catch(Te){console.error("Extension toggle failed:",Te)}finally{Se(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 ${Ne.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 ${Ne.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Ne.name,s.jsx("span",{className:"text-[9px] font-normal",children:Ne.enabled?"ON":"OFF"})]},Ne.type))})]})]},_.id)})]}),X&&l&&s.jsx(an,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:A,directories:ce,busy:we,error:Ae,confirmLabel:"Use this folder",onClose:()=>ae(!1),onNavigate:_=>{yt(_)},onConfirm:_=>{le(_),xe("__custom__"),ae(!1)}}),ze&&s.jsx(za,{title:ze.title,description:ze.description,details:ze.details,workspaceOptions:ze.workspaceOptions,selectedWorkspaceKey:dt,onWorkspaceChange:_=>{it.current=_,ut(_)},confirmLabel:ze.confirmLabel,busyLabel:ze.busyLabel,busy:mt,onConfirm:$,onCancel:()=>{Fe.current=null,ot(null)}}),z&&Tt&&s.jsx(Da,{activeConv:Tt,ides:[],isCreatingChat:!1,isRefreshingHistory:be,savedSessions:W,isSavedSessionsLoading:be,isResumingSavedSessionId:te,savedHistoryFilters:Q,onSavedHistoryFiltersChange:ue,onClose:()=>F(!1),onNewChat:()=>{E(""),F(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{et(M)},onResumeSavedSession:_=>{if(!_.canResume||te)return;const ee=De(_);E(_.providerSessionId),Le(_),fe(_.providerSessionId),F(!1),se({type:_.providerType,workspaceId:ee.workspaceId,workspacePath:ee.workspacePath,useHome:ee.useHome,resumeSessionId:_.providerSessionId}).finally(()=>{fe(pe=>pe===_.providerSessionId?null:pe)})}})]})}const ci=[{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 tb({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,w]=o.useState(u);o.useEffect(()=>{w(u)},[u]);const S=o.useMemo(()=>({ide:n.length,cli:a.length,acp:i.length}),[n.length,a.length,i.length]);return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),s.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[s.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:ci.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:()=>w(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:S[x.id]})]},x.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(p=ci.find(x=>x.id===m))==null?void 0:p.helper})]}),m==="ide"&&s.jsx(Wn,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:d}),m==="cli"&&s.jsx(Wn,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:d}),m==="acp"&&s.jsx(Wn,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:d})]})}function sb({onNicknameSynced:e}={}){var fe,ne,xe,re,le,oe,Y,X,ae;const{id:t}=Zl(),r=As(),n=pa(),{sendCommand:a}=jt(),i=nr(),c=Pc(),l=lc(),u=l.ides||[],f=l.initialLoaded??!0,d=u.find(A=>A.id===t&&A.type==="adhdev-daemon"),h=u.some(A=>A.type==="adhdev-daemon"),[m,w]=o.useState("workspace"),[S,p]=o.useState("ide"),x=o.useRef(null),[j,b]=o.useState(null),N=o.useRef("__home__"),[T,y]=o.useState("__home__"),[C,k]=o.useState(!1),v=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 A=d.machine;(typeof(A==null?void 0:A.cpus)!="number"||typeof(A==null?void 0:A.totalMem)!="number"||typeof(A==null?void 0:A.arch)!="string"||typeof(A==null?void 0:A.release)!="string")&&c(t,{minFreshMs:3e4}).catch(()=>{})},[m,c,d,t]),op(t&&m==="overview"?[t]:[],{enabled:m==="overview",intervalMs:ym});const g=()=>{if(h){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},D=Nx({machineId:t,registeredMachineId:(d==null?void 0:d.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:v});o.useEffect(()=>lt.onToast(H=>{l.setToasts(me=>{if(me.some(Ae=>Ae.message===H.message&&H.timestamp-Ae.timestamp<3e3))return me;const _e={id:H.id,message:H.message,type:H.type,timestamp:H.timestamp,targetKey:H.targetKey,actions:H.actions};return[...me.slice(-4),_e]});const ce=H.duration||5e3;setTimeout(()=>l.setToasts(me=>me.filter(we=>we.id!==H.id)),ce)}),[l]);const M=(d==null?void 0:d.availableProviders)||[],I={};for(const A of M)I[A.type]=A.icon;const P=A=>I[A]||"",K=d?{id:d.id,hostname:Oi(d,{fallbackId:d.id}),platform:((fe=d.machine)==null?void 0:fe.platform)||"unknown",arch:((ne=d.machine)==null?void 0:ne.arch)||"",cpus:((xe=d.machine)==null?void 0:xe.cpus)||0,totalMem:((re=d.machine)==null?void 0:re.totalMem)||0,freeMem:(le=d.machine)==null?void 0:le.freeMem,availableMem:(oe=d.machine)==null?void 0:oe.availableMem,loadavg:(Y=d.machine)==null?void 0:Y.loadavg,uptime:(X=d.machine)==null?void 0:X.uptime,release:((ae=d.machine)==null?void 0:ae.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,V=u.filter(A=>A.daemonId===t&&A.type!=="adhdev-daemon").filter(A=>!Xs(A)&&!ys(A)).map(A=>({id:A.id,sessionId:A.sessionId,type:A.type,version:A.version||"",instanceId:A.instanceId||"",status:A.status,workspace:A.workspace||null,terminals:A.terminals||0,aiAgents:Su(A.aiAgents||(A.agents||[]).map(H=>({id:H.name,name:H.name,status:H.status,version:H.version}))),activeChat:A.activeChat||null,chats:A.chats||[],childSessions:A.childSessions||[],cdpConnected:A.cdpConnected||!1,daemonId:t})),L=u.filter(A=>A.daemonId===t&&Xs(A)).map(A=>({id:A.id,sessionId:A.sessionId,type:A.type,cliName:A.cliName||A.type,status:A.status,workspace:A.workspace||"",activeChat:A.activeChat||null,providerSessionId:A.providerSessionId,mode:A.mode,runtimeKey:A.runtimeKey,runtimeDisplayName:A.runtimeDisplayName,runtimeWorkspaceLabel:A.runtimeWorkspaceLabel,runtimeWriteOwner:A.runtimeWriteOwner||null,runtimeAttachedClients:A.runtimeAttachedClients||[],daemonId:t})),R=u.filter(A=>A.daemonId===t&&ys(A)).map(A=>({id:A.id,sessionId:A.sessionId,type:A.type,acpName:A.cliName||A.type,status:A.status,workspace:A.workspace||"",activeChat:A.activeChat||null,providerSessionId:A.providerSessionId,daemonId:t})),G=d?Mt(d,{fallbackId:t}):"",B="workspace",E=n.state,W=E==null?void 0:E.initialMachineTab,J=E==null?void 0:E.initialWorkspaceCategory,be=E==null?void 0:E.initialWorkspaceId,he=E==null?void 0:E.initialWorkspacePath,de=W==="ides"||W==="clis"||W==="acps"?"workspace":W||B,ye=W==="ides"?"ide":W==="clis"?"cli":W==="acps"?"acp":J,ge=[...V.map(A=>{var H,ce,me,we,_e;return{id:`ide:${A.type}:${A.workspace||""}`,label:((H=A.activeChat)==null?void 0:H.title)||A.type,kind:"ide",providerType:A.type,subtitle:A.workspace||void 0,workspace:A.workspace||void 0,lastLaunchedAt:((_e=(we=(me=(ce=A.activeChat)==null?void 0:ce.messages)==null?void 0:me.at)==null?void 0:we.call(me,-1))==null?void 0:_e.timestamp)||0}}),...L.map(A=>{var H,ce,me,we,_e;return{id:`cli:${A.type}:${A.workspace||""}`,label:((H=A.activeChat)==null?void 0:H.title)||A.cliName,kind:"cli",providerType:A.type,providerSessionId:A.providerSessionId,subtitle:A.workspace||void 0,workspace:A.workspace||void 0,lastLaunchedAt:((_e=(we=(me=(ce=A.activeChat)==null?void 0:ce.messages)==null?void 0:me.at)==null?void 0:we.call(me,-1))==null?void 0:_e.timestamp)||0}}),...R.map(A=>{var H,ce,me,we,_e;return{id:`acp:${A.type}:${A.workspace||""}`,label:((H=A.activeChat)==null?void 0:H.title)||A.acpName,kind:"acp",providerType:A.type,providerSessionId:A.providerSessionId,subtitle:ds(A.summaryMetadata)||A.workspace||void 0,workspace:A.workspace||void 0,lastLaunchedAt:((_e=(we=(me=(ce=A.activeChat)==null?void 0:ce.messages)==null?void 0:me.at)==null?void 0:we.call(me,-1))==null?void 0:_e.timestamp)||0}})].sort((A,H)=>(H.lastLaunchedAt||0)-(A.lastLaunchedAt||0)),ve=((d==null?void 0:d.recentLaunches)||[]).length>0?((d==null?void 0:d.recentLaunches)||[]).map(A=>({id:A.id,label:A.title||A.providerName||A.providerType,kind:A.kind,providerType:A.providerType,providerSessionId:A.providerSessionId,subtitle:ds(A.summaryMetadata)||A.workspace||void 0,workspace:A.workspace,summaryMetadata:A.summaryMetadata,lastLaunchedAt:A.lastLaunchedAt})):ge,z=o.useMemo(()=>{var H;const A=((H=l.connectionStates)==null?void 0:H[t||""])||void 0;return u.filter(ce=>ce.daemonId===t&&ce.type!=="adhdev-daemon").flatMap(ce=>Ea(ce,{connectionStates:t&&A?{[t]:A}:void 0,defaultConnectionState:A})).filter(ce=>!(ce.transport==="pty"&&ce.mode==="terminal")).sort((ce,me)=>ea(me)-ea(ce))},[u,l.connectionStates,t]),F=o.useCallback(A=>{const H=Ia(A);H&&r(Gt(H))},[r]),Q=o.useCallback(()=>{x.current&&(k(!0),x.current().finally(()=>{x.current=null,k(!1),b(null)}))},[]),ue=o.useCallback(A=>{if(!K)return;const{options:H,selectedKey:ce}=os({machine:K,currentWorkspacePath:A.workspace}),me=async()=>{p(A.kind),w("workspace")};x.current=async()=>{const we=H.find(Ke=>Ke.key===N.current),_e=(we==null?void 0:we.workspacePath)??null,Ae=(we==null?void 0:we.workspaceId)??null;if(A.kind==="ide"&&A.providerType){await D.handleLaunchIde(A.providerType,_e?{workspace:_e}:void 0);return}if((A.kind==="cli"||A.kind==="acp")&&A.providerType){await D.runLaunchCliCore({cliType:A.providerType,dir:Ae?void 0:_e||"",workspaceId:Ae||void 0,model:A.kind==="acp"&&Hi(A.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:A.providerSessionId});return}await me()},N.current=ce,y(ce),b({title:A.kind==="ide"?ss("restart-ide",A.label):A.providerSessionId?Pa(A.label):ss("start-fresh",A.label),description:A.kind==="ide"?rs("restart-ide"):A.providerSessionId?_a():rs("start-fresh"),confirmLabel:A.kind==="ide"?Cs("restart-ide"):A.providerSessionId?Ur(!0):Cs("start-fresh"),busyLabel:A.kind==="ide"?Is("restart-ide"):A.providerSessionId?La(!0):Is("start-fresh"),workspaceOptions:H,details:[{label:"Mode",value:A.kind.toUpperCase()},...A.providerType?[{label:"Provider",value:A.providerType}]:[]]})},[D,K]);if(o.useEffect(()=>{w(de)},[B,de,t]),o.useEffect(()=>{ye&&p(ye)},[ye,t]),!K)return f?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),s.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),s.jsx("button",{onClick:g,className:"machine-btn-back",children:"← Back"})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:"⏳ Loading machine..."})});const te=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ct,{size:14})," Workspace"]}),count:V.length+L.length+R.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ls,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Yr,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Td,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Id,{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:[D.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:D.nicknameInput,onChange:A=>D.setNicknameInput(A.target.value),onKeyDown:A=>{A.key==="Enter"&&D.handleSaveNickname(),A.key==="Escape"&&D.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:D.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),s.jsx("button",{onClick:()=>D.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{D.setEditingNickname(!0),D.setNicknameInput(K.machineNickname||"")},title:"Click to set nickname",children:G}),s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[K.platform," · ",K.arch]}),s.jsxs("span",{children:[K.cpus," cores"]}),(d==null?void 0:d.version)&&s.jsxs("span",{children:["v",d.version]}),K.p2p.available&&s.jsxs("span",{children:["P2P ",K.p2p.state==="connected"?"connected":K.p2p.state]}),K.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:K.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:te.map(A=>s.jsxs("button",{onClick:()=>w(A.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${m===A.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[A.label,A.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${m===A.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:A.count})]},A.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(Qx,{machineEntry:d,providers:M,recentLaunches:ve,currentConversations:z,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",{})}catch{}},onOpenRecent:ue,onOpenConversation:F}),s.jsx(tb,{machine:K,machineId:t,providers:M,ideSessions:V,cliSessions:L,acpSessions:R,actions:D,getIcon:P,initialCategory:S,initialWorkspaceId:be,initialWorkspacePath:he,sendDaemonCommand:a})]}),m==="providers"&&s.jsx(Px,{machineId:t,providers:M,sendDaemonCommand:a}),m==="overview"&&s.jsx(Cx,{machineId:t,machine:K,ideSessions:V,cliSessions:L,acpSessions:R,actions:D,sendDaemonCommand:a}),m==="session-host"&&s.jsx(Xx,{machineId:t,cliSessions:L,sendDaemonCommand:a}),m==="logs"&&s.jsx(Fx,{machineId:t,sendDaemonCommand:a})]})})}),D.launchPick&&K&&s.jsx(Jx,{machine:K,launchPick:D.launchPick,actions:D}),j&&s.jsx(za,{title:j.title,description:j.description,details:j.details,workspaceOptions:j.workspaceOptions,selectedWorkspaceKey:T,onWorkspaceChange:A=>{N.current=A,y(A)},confirmLabel:j.confirmLabel,busyLabel:j.busyLabel,busy:C,onConfirm:Q,onCancel:()=>{x.current=null,b(null)}}),s.jsx(yc,{toasts:l.toasts||[],onDismiss:A=>l.setToasts(H=>H.filter(ce=>ce.id!==A)),onClickToast:A=>{A.targetKey&&r(Gt(A.targetKey))}}),s.jsx("style",{children:`
|
|
71
|
+
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){c("session_host_prune_duplicate_sessions");try{const I=await r(e,"session_host_prune_duplicate_sessions",{}),P=$n(I);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Duplicate prune failed");const K=P.result||{},V=Array.isArray(K.prunedSessionIds)?K.prunedSessionIds.length:0,L=typeof K.duplicateGroupCount=="number"?K.duplicateGroupCount:0;lt.showToast(`Pruned ${V} duplicate runtime(s) across ${L} group(s)`,"success"),await p()}catch(I){const P=I instanceof Error?I.message:"Duplicate prune failed";lt.showToast(P,"warning"),a(P)}finally{c(I=>I==="session_host_prune_duplicate_sessions"?null:I)}}},[e,p,r]),b=o.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((M,I)=>(I.lastActivityAt||0)-(M.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)||[]}:zx(b),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,b]),T=N.liveRuntimes,y=N.recoverySnapshots,C=N.inactiveRecords,k=o.useMemo(()=>Yx(T),[T]),v=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(M=>M.level==="warn"||M.level==="error")||null,[d==null?void 0:d.recentLogs]),D=(M,I)=>{var W;const P=i===`session_host_resume_session:${M.sessionId}`,K=i===`session_host_restart_session:${M.sessionId}`,V=i===`session_host_stop_session:${M.sessionId}`,L=xl(M.meta),R=S.get(M.sessionId),G=M.attachedClients.length===1?"1 client":`${M.attachedClients.length} clients`,B=I==="recovery"?"Recover":"Resume",E=Vx(I);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:M.displayName||(R==null?void 0:R.cliName)||M.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${qx(M.lifecycle)}`,children:M.lifecycle}),L&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:L})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:M.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||M.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:M.runtimeKey}),M.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",M.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((W=M.writeOwner)==null?void 0:W.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Gx(M.writeOwner)}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[s.jsx(Si,{size:11})," ",G]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",ii(M.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",E]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[I==="recovery"&&(M.lifecycle==="interrupted"||M.lifecycle==="failed"||M.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{x("session_host_resume_session",M)},children:P?`${B}ing…`:B}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{x("session_host_restart_session",M)},children:K?"Restarting…":"Restart"}),I==="live"&&(M.lifecycle==="running"||M.lifecycle==="starting"||M.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!i,onClick:()=>{x("session_host_stop_session",M)},children:V?"Stopping…":"Stop"})]})]})},M.sessionId)};return s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(ls,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:ff()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[k>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{j()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${k})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${w.toneClass}`,children:w.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:h||l,children:[s.jsx(er,{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:ii(d.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Bn(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:[Bn(g.timestamp),g.sessionId?` · ${g.sessionId}`:""]})]}),s.jsxs("div",{className:"mb-4 space-y-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(ga,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:En("live")}),T.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:T.map(M=>D(M,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(ls,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:En("recovery")}),y.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:y.map(M=>D(M,"recovery"))})]}),C.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:En("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:C.map(M=>D(M,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),v.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:v.map(M=>{var P;const I=b.find(K=>K.sessionId===M.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(I==null?void 0:I.displayName)||((P=S.get(M.sessionId))==null?void 0:P.cliName)||M.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[M.action,M.lifecycle?` · ${M.lifecycle}`:"",M.detail?` · ${M.detail}`:"",M.error?` · ${M.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${M.success===!1?"text-red-300":"text-text-secondary"}`,children:Bn(M.timestamp)})]},`${M.sessionId}:${M.timestamp}:${M.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:d.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function Jx({machine:e,launchPick:t,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return s.jsx("div",{className:"fixed inset-0 z-[100] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(i=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{a(null),n({cliType:t.cliType,workspaceId:i.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),n({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:"Default workspace"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{a(null),n({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:"Home directory"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>a(null),children:"Cancel"})]})]})})}function Kn({icon:e,children:t}){return s.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,s.jsx("span",{children:t})]})}function On({children:e,className:t=""}){return s.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function Qx({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=Hs(e,"0.9.23");return s.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[l.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Kn,{icon:s.jsx(Ft,{size:13}),children:"Current Chats"}),s.jsx(On,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(h=>{const m=ea(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:tt(h)}),m>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Jr(m)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:us(h)})]},h.tabKey)})})})]}),u.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Kn,{icon:s.jsx(Mi,{size:13}),children:"Recent Launches"}),s.jsx(On,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(h=>{const{metaText:m,updatedLabel:w}=Xc(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}),w&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:w})]}),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(Kn,{icon:s.jsx(qs,{size:13}),children:"Daemon Update"}),s.jsx(On,{className:"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children: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(er,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Zx(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const eb={ide:{label:"IDE",plural:"IDEs",accent:"border-blue-500/[0.12]"},cli:{label:"CLI",plural:"CLIs",accent:"border-violet-500/[0.12]"},acp:{label:"ACP Agent",plural:"ACP agents",accent:"border-emerald-500/[0.12]"}};function Ir(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Wn({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:f}){const d=As(),{handleLaunchIde:h,handleStopCli:m,handleRestartIde:w,handleStopIde:S,handleDetectIdes:p,launchingIde:x,launchingAgentType:j,addLog:b}=c,[N,T]=o.useState(null),y=o.useCallback(_=>{_&&d(Gt(_))},[d]),C=eb[e],k=e==="ide",v=e==="acp",g=o.useMemo(()=>n.filter(_=>_.category===e&&(e==="ide"||_.installed!==!1)),[e,n]),D=o.useMemo(()=>new Map(g.map(_=>[_.type,_.displayName||_.type])),[g]),[M,I]=o.useState(""),[P,K]=o.useState(""),[V,L]=o.useState([]),[R,G]=o.useState(""),[B,E]=o.useState(""),[W,J]=o.useState([]),[be,he]=o.useState(!1),[de,ye]=o.useState(!1),[ge,ve]=o.useState(""),[z,F]=o.useState(!1),[Q,ue]=o.useState(()=>ht()),[te,fe]=o.useState(null),[ne,xe]=o.useState(f?"__custom__":u||t.defaultWorkspaceId||""),[re,le]=o.useState(f||""),[oe,Y]=o.useState([]),[X,ae]=o.useState(!1),[A,H]=o.useState(""),[ce,me]=o.useState([]),[we,_e]=o.useState(!1),[Ae,Ke]=o.useState(""),Fe=o.useRef(null),[ze,ot]=o.useState(null),it=o.useRef("__home__"),[dt,ut]=o.useState("__home__"),[mt,Xe]=o.useState(!1),rt=o.useRef(0),je=oe.filter(_=>!a.some(ee=>ee.type===_&&bt(ee.status)!=="stopped")),Ee=o.useRef({});o.useEffect(()=>{t.defaultWorkspaceId&&!ne&&xe(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),o.useEffect(()=>{if(f){xe("__custom__"),le(f);return}u&&(xe(u),le(""))},[u,f]),o.useEffect(()=>{k||M&&(g.some(_=>_.type===M)||(I(""),E("")))},[g,k,M]);const Be=(()=>{if(ne==="__custom__")return re.trim();if(!ne)return"";const _=(t.workspaces||[]).find(ee=>ee.id===ne);return(_==null?void 0:_.path)||""})(),nt=o.useCallback(_=>{const ee=Ee.current[_];ee&&(clearTimeout(ee),delete Ee.current[_]),Y(pe=>pe.includes(_)?pe.filter(Re=>Re!==_):pe)},[]),st=o.useRef(new Set),yt=o.useCallback(async _=>{if(l){_e(!0),Ke("");try{const ee=await rn(l,r,_);H(ee.path),le(ee.path),me(ee.directories)}catch(ee){Ke(ee instanceof Error?ee.message:"Could not load folder")}finally{_e(!1)}}},[r,l]),Z=o.useCallback(()=>{if(!l)return;xe("__custom__"),ae(!0);const _=a.map(pe=>pe.workspace),ee=sn(t.platform,tn(re.trim(),Be,f,_,t.defaultWorkspacePath,(t.workspaces||[]).map(pe=>pe.path)));yt(ee)},[re,f,yt,t.defaultWorkspacePath,t.platform,t.workspaces,a,Be,l]),Le=o.useCallback(_=>{const ee=String(_.workspace||"").trim();if(!ee)return;const pe=(t.workspaces||[]).find(Re=>Ir(Re.path)===Ir(ee));if(pe){xe(pe.id),le("");return}xe("__custom__"),le(ee)},[t.workspaces]),De=o.useCallback(_=>{const ee=String(_.workspace||"").trim();if(!ee)return{workspaceId:null,workspacePath:"",useHome:!0};const pe=(t.workspaces||[]).find(Re=>Ir(Re.path)===Ir(ee));return pe?{workspaceId:pe.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:ee,useHome:!1}},[t.workspaces]),et=o.useCallback(async _=>{if(!l||!_||e!=="cli"){J([]),he(!1),ye(!1),ve("");return}const ee=rt.current+1;rt.current=ee,he(!0),ve("");try{const pe=await l(r,"list_saved_sessions",{providerType:_,kind:"cli",limit:30});if(rt.current!==ee)return;const Re=(pe==null?void 0:pe.result)??pe;J(Array.isArray(Re==null?void 0:Re.sessions)?Re.sessions:[])}catch(pe){if(rt.current!==ee)return;J([]),ve(pe instanceof Error?pe.message:"Could not load saved sessions")}finally{rt.current===ee&&(he(!1),ye(!0))}},[e,r,l]),Tt=o.useMemo(()=>{if(e!=="cli"||!M)return null;const _=D.get(M)||M;return{routeId:r,daemonId:r,providerSessionId:B||void 0,transport:"pty",mode:"chat",agentName:_,agentType:M,status:"idle",title:_,messages:[],ideType:M,workspaceName:Be,displayPrimary:_,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${M}`}},[e,r,D,Be,B,M]),ft=o.useCallback(_=>{if(e==="ide"||!_){L([]);return}L(ll(r,_))},[e,r]);o.useEffect(()=>{rt.current+=1,E(""),ft(M),ye(!1),J([]),ve(""),he(!1)},[e,ft,et,M]);const He=o.useMemo(()=>W.find(_=>_.providerSessionId===B)||null,[W,B]);o.useEffect(()=>{if(!B)return;const _=W.find(ee=>ee.providerSessionId===B);_!=null&&_.canResume||E("")},[W,B]);const vt=o.useCallback((_,ee)=>{Fe.current=ee,it.current=_.selectedWorkspaceKey||"__home__",ut(_.selectedWorkspaceKey||"__home__"),ot(_)},[]),$=o.useCallback(()=>{Fe.current&&(Xe(!0),Fe.current().finally(()=>{Fe.current=null,Xe(!1),ot(null)}))},[]),O=o.useCallback(_=>{if(!_)return;Y(pe=>pe.includes(_)?pe:[...pe,_]);const ee=Ee.current[_];ee&&clearTimeout(ee),Ee.current[_]=setTimeout(()=>{Y(pe=>pe.includes(_)?pe.filter(Re=>Re!==_):pe),delete Ee.current[_]},2e4)},[]);o.useEffect(()=>{for(const ee of a)bt(ee.status)!=="stopped"&&(oe.includes(ee.type)&&!st.current.has(ee.type)&&(st.current.add(ee.type),b("info",`${D.get(ee.type)||ee.type} launched`,!0)),nt(ee.type));const _=new Set(a.filter(ee=>bt(ee.status)!=="stopped").map(ee=>ee.type));st.current.forEach(ee=>{!oe.includes(ee)&&!_.has(ee)&&st.current.delete(ee)})},[b,nt,a,oe,D]),o.useEffect(()=>()=>{Object.values(Ee.current).forEach(clearTimeout),Ee.current={}},[]);const[U,q]=o.useState({}),[ie,Se]=o.useState(null);o.useEffect(()=>{if(!k||!r||!l)return;(async()=>{try{const ee=await l(r,"get_ide_extensions",{}),pe=(ee==null?void 0:ee.result)||ee;pe!=null&&pe.success&&(pe!=null&&pe.ideExtensions)&&q(pe.ideExtensions)}catch{}})()},[k,r,l]);const Ie=_=>k?Ze(_.type):e==="cli"?_.cliName:_.acpName,Ce=k?t.detectedIdes||[]:[],se=o.useCallback(async _=>{const ee=(_==null?void 0:_.type)||M,pe=(_==null?void 0:_.workspacePath)??Be;if(k){await h(ee,pe?{workspace:pe}:void 0)&&O(ee);return}const Re=await c.runLaunchCliCore({cliType:ee,dir:_!=null&&_.workspaceId?void 0:pe||void 0,workspaceId:(_==null?void 0:_.workspaceId)||void 0,useHome:(_==null?void 0:_.useHome)||!(_!=null&&_.workspaceId)&&!pe,argsStr:(_==null?void 0:_.argsStr)??(P||void 0),model:(_==null?void 0:_.model)??(v&&R||void 0),resumeSessionId:(_==null?void 0:_.resumeSessionId)||!v&&e==="cli"&&ee===M&&B||void 0});if(Re.success||Re.pending){const Ne=(_==null?void 0:_.argsStr)??P;!k&&(Ne!=null&&Ne.trim())&&(dl(r,ee,Ne),ft(ee)),O(ee),Re.success&&Re.sessionId&&y(Re.sessionId)}},[c,h,v,k,P,R,ft,O,r,y,Be,B,M]),ke=bc(k?"ide":v?"acp":"cli",!k&&!v&&!!B),Oe=gc(k?"ide":v?"acp":"cli",!k&&!v&&!!B),Ue=()=>{var Ne;const _=k?Ze(M):D.get(M)||M,ee=!k&&!v&&!!B,{options:pe,selectedKey:Re}=os({machine:t,currentWorkspaceId:ne&&ne!=="__custom__"?ne:null,currentWorkspacePath:Be});vt({title:ee?Pa(_):ss("start-fresh",_),description:ee?_a():rs("start-fresh"),confirmLabel:ke,busyLabel:Oe,workspaceOptions:pe,selectedWorkspaceKey:Re,details:[{label:"Mode",value:C.label},{label:"Provider",value:_},...!k&&e==="cli"&&B?[{label:"Resume",value:((Ne=W.find(Me=>Me.providerSessionId===B))==null?void 0:Ne.title)||B}]:[],...!k&&P.trim()?[{label:"Arguments",value:P.trim()}]:[],...v&&R.trim()?[{label:"Model",value:R.trim()}]:[]]},async()=>{const Me=pe.find(Te=>Te.key===it.current);Me!=null&&Me.workspaceId?(xe(Me.workspaceId),le("")):Me!=null&&Me.workspacePath?(xe("__custom__"),le(Me.workspacePath)):(xe(""),le("")),await se({workspaceId:(Me==null?void 0:Me.workspaceId)??null,workspacePath:(Me==null?void 0:Me.workspacePath)??"",useHome:!(Me!=null&&Me.workspaceId)&&!(Me!=null&&Me.workspacePath)})})},Ye=_=>{k?S(_):m(_.type,_.workspace,_.id)},Ve=o.useCallback(async(_,ee,pe=!1)=>{if(_.mode===ee){pe&&_.sessionId&&y(_.sessionId);return}if(!l||!_.sessionId){pe&&_.sessionId&&y(_.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:_.sessionId,cliType:_.type,mode:ee}),pe&&y(_.sessionId)}catch(Re){const Ne=Bc(Re);$c(Re)?console.warn(Ne?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Re instanceof Error?Re.message:String(Re)):console.error("Failed to switch CLI view mode:",Re)}},[r,y,l]),Pe=s.jsxs("div",{className:"mb-3",children:[s.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[s.jsx("select",{value:ne,onChange:_=>{const ee=_.target.value;if(xe(ee),ee==="__custom__"&&l){Z();return}ee!=="__custom__"&&le("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(t.workspaces||[]).length>0?s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(t.workspaces||[]).map(_=>s.jsxs("option",{value:_.id,children:[_.id===t.defaultWorkspaceId?"⭐ ":"",Zr(_.path,_.label)]},_.id)),s.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),s.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]})}),ne==="__custom__"&&(l?s.jsx("button",{type:"button",className:"px-3 py-1.5 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] hover:border-accent-primary text-text-secondary hover:text-text-primary transition-colors",onClick:Z,children:"Select workspace…"}):s.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:re,onChange:_=>le(_.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:ne==="__custom__"?Be?s.jsx("span",{className:"font-mono truncate block",title:Be,children:Be}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":Be?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:ne===t.defaultWorkspaceId?"Default workspace":"Selected workspace"}),s.jsx("span",{className:"font-mono truncate block",title:Be,children:Be})]}):"No workspace selected. This launches in the home directory."})]});return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${C.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 ",C.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:k?Ce.length>0?Ce.map(_=>{const ee=a.find(Te=>(Te.type||"").toLowerCase()===(_.type||"").toLowerCase()&&bt(Te.status)!=="stopped"),pe=_.running||!!ee,Re=!!ee&&ee.cdpConnected,Ne=oe.includes(_.type||_.id||""),Me=M===(_.type||"");return s.jsxs("button",{onClick:()=>{if(Re&&ee){const Te=ee.sessionId;Te?d(Gt(Te),{state:{openRemoteForTabKey:Te}}):d("/dashboard",{state:{openRemoteForTabKey:ee.id}});return}Ne||I(Te=>Te===(_.type||"")?"":_.type||"")},disabled:!!x||Ne,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Re?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Me?"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!==_.type?.4:1},children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i(_.type)}),pe&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Re?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:_.name||Ze(_.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Re?"text-green-400":Ne?"text-orange-400":Me?"text-accent-primary":"text-text-muted"}`,children:Re?"Open Session":Ne?"Starting...":Me?"Configure":"Select"})]})]},_.type)}):s.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",s.jsxs("button",{onClick:p,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[s.jsx(Md,{size:14})," Scan System"]})]}):g.length>0?g.map(_=>{const ee=M===_.type,pe=oe.includes(_.type),Ne=!!a.find(Me=>Me.type===_.type&&bt(Me.status)!=="stopped");return s.jsxs("button",{onClick:()=>I(Me=>Me===_.type?"":_.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:_.icon}),Ne&&s.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:_.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${pe?"text-orange-400":ee?"text-accent-primary":"text-text-muted"}`,children:pe?"Starting...":ee?"Configure":"Select"})]})]},_.type)}):s.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),M&&(k?Ce.find(_=>_.type===M):g.find(_=>_.type===M))&&s.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[s.jsx("span",{children:"Launch Settings"}),s.jsx("span",{className:"text-accent-primary font-bold",children:k?Ze(M):D.get(M)||M})]}),Pe,!k&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!v&&e==="cli"&&s.jsx(ml,{busy:!!j||!!x||oe.includes(M),savedSessionsLoading:be,savedSessionsError:ge,selectedSession:He,onRefresh:()=>void et(M),onOpenHistory:()=>{M&&(F(!0),ul({hasLoadedInitialResults:de,isLoading:be})&&et(M))},onClearSelection:()=>E("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[v&&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:R,onChange:_=>G(_.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:P,onChange:_=>K(_.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),V.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:V.map(_=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>K(_),title:_,children:_},_))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:Ue,disabled:!!j||!!x||oe.includes(M),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:j===M||x===M?"⏳ 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(_=>!a.some(ee=>ee.type===_&&bt(ee.status)!=="stopped")).length,")"]}),a.length===0&&je.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 ",C.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[je.map(_=>s.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:i(_)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:k?Ze(_):D.get(_)||_}),s.jsx("div",{className:"text-[11px] text-text-muted",children:j===_?"Launching process...":"Waiting for process and session to register..."})]})]}),s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:"var(--status-warning)"},children:"starting"})]})},`pending:${_}`)),a.map(_=>{const ee=k?_:null,pe=!k&&!v?_:null,Re=bt(_.status);return s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:i(_.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Ie(_),(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:_.workspace||"—"}),(pe==null?void 0:pe.mode)&&s.jsx("span",{className:pe.mode==="chat"?"text-violet-400":"text-text-secondary",children:pe.mode==="chat"?"Chat view":"Terminal view"})]}),pe&&(pe.runtimeKey||pe.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[pe.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 ",pe.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 Ne;(Ne=navigator.clipboard)==null||Ne.writeText(`adhdev attach ${pe.runtimeKey}`),T(pe.runtimeKey||null),window.setTimeout(()=>{T(Me=>Me===pe.runtimeKey?null:Me)},1200)},children:N===pe.runtimeKey?"Copied":"Copy"})]}),pe.runtimeWriteOwner&&s.jsx("span",{style:{color:pe.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:pe.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Zx(pe.runtimeWriteOwner)})]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Re==="stopped"?"bg-red-500/[0.08] text-red-500":Re==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Re}),k&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const Ne=_.sessionId;if(Ne){d(Gt(Ne),{state:{openRemoteForTabKey:Ne}});return}d("/dashboard",{state:{openRemoteForTabKey:_.id}})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-primary transition-colors cursor-pointer",title:"Open remote control",children:s.jsx(Ct,{size:13})}),s.jsx("button",{onClick:()=>{const Ne=_.workspace||"",{options:Me,selectedKey:Te}=os({machine:t,currentWorkspacePath:Ne});vt({title:ss("restart-ide",Ze(_.type)),description:rs("restart-ide"),confirmLabel:Cs("restart-ide"),busyLabel:Is("restart-ide"),workspaceOptions:Me,selectedWorkspaceKey:Te,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:Ze(_.type)}]},async()=>{const pt=Me.find(Ut=>Ut.key===it.current),ct=(pt==null?void 0:pt.workspacePath)??"";if(ct&&ct!==Ne){await se({type:_.type,workspacePath:ct});return}await w(_)})},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(er,{size:14})})]}),v&&s.jsx("button",{onClick:()=>{const Ne=_.sessionId;Ne&&y(Ne)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"View chat",disabled:!_.sessionId,children:s.jsx(Ft,{size:14})}),pe&&Re!=="stopped"&&s.jsxs(s.Fragment,{children:[pe.mode&&s.jsx(Ta,{mode:pe.mode,onChange:Ne=>void Ve(pe,Ne,!1),compact:!0}),s.jsx("button",{onClick:()=>{const Ne=_.sessionId;Ne&&y(Ne)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"Open current view in dashboard",disabled:!_.sessionId,children:pe.mode==="chat"?s.jsx(Ft,{size:14}):s.jsx(Ct,{size:13})})]}),Re==="stopped"?s.jsx("button",{onClick:()=>{const Ne=_.workspace||"",Me=k?Ze(_.type):Ie(_),{options:Te,selectedKey:pt}=os({machine:t,currentWorkspacePath:Ne});vt({title:ss("restart-stopped",Me),description:rs("restart-stopped"),confirmLabel:Cs("restart-stopped"),busyLabel:Is("restart-stopped"),workspaceOptions:Te,selectedWorkspaceKey:pt,details:[{label:"Mode",value:C.label},{label:"Provider",value:Me}]},async()=>{const ct=Te.find(Ut=>Ut.key===it.current);await se({type:_.type,workspaceId:(ct==null?void 0:ct.workspaceId)??null,workspacePath:(ct==null?void 0:ct.workspacePath)??"",useHome:!(ct!=null&&ct.workspaceId)&&!(ct!=null&&ct.workspacePath)})})},disabled:oe.includes(_.type),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-green-500/20 text-green-400 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",title:"Restart",children:oe.includes(_.type)?"⏳":s.jsx(ya,{size:14})}):s.jsx("button",{onClick:()=>Ye(_),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-red-500/20 text-red-400 transition-colors cursor-pointer",title:"Stop",children:s.jsx(wt,{size:14})})]})]}),ee&&ee.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:ee.aiAgents.map(Ne=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Ki(Ne.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Ne.name," · ",bt(Ne.status)]},Ne.id))}),ee&&(U[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:(U[ee.type]||[]).map(Ne=>s.jsxs("button",{disabled:ie===`${ee.type}.${Ne.type}`,onClick:async()=>{const Me=`${ee.type}.${Ne.type}`;Se(Me);try{await l(r,"set_ide_extension",{ideType:ee.type,extensionType:Ne.type,enabled:!Ne.enabled}),q(Te=>({...Te,[ee.type]:(Te[ee.type]||[]).map(pt=>pt.type===Ne.type?{...pt,enabled:!pt.enabled}:pt)}))}catch(Te){console.error("Extension toggle failed:",Te)}finally{Se(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 ${Ne.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 ${Ne.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Ne.name,s.jsx("span",{className:"text-[9px] font-normal",children:Ne.enabled?"ON":"OFF"})]},Ne.type))})]})]},_.id)})]}),X&&l&&s.jsx(an,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:A,directories:ce,busy:we,error:Ae,confirmLabel:"Use this folder",onClose:()=>ae(!1),onNavigate:_=>{yt(_)},onConfirm:_=>{le(_),xe("__custom__"),ae(!1)}}),ze&&s.jsx(za,{title:ze.title,description:ze.description,details:ze.details,workspaceOptions:ze.workspaceOptions,selectedWorkspaceKey:dt,onWorkspaceChange:_=>{it.current=_,ut(_)},confirmLabel:ze.confirmLabel,busyLabel:ze.busyLabel,busy:mt,onConfirm:$,onCancel:()=>{Fe.current=null,ot(null)}}),z&&Tt&&s.jsx(Da,{activeConv:Tt,ides:[],isCreatingChat:!1,isRefreshingHistory:be,savedSessions:W,isSavedSessionsLoading:be,isResumingSavedSessionId:te,savedHistoryFilters:Q,onSavedHistoryFiltersChange:ue,onClose:()=>F(!1),onNewChat:()=>{E(""),F(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{et(M)},onResumeSavedSession:_=>{if(!_.canResume||te)return;const ee=De(_);E(_.providerSessionId),Le(_),fe(_.providerSessionId),F(!1),se({type:_.providerType,workspaceId:ee.workspaceId,workspacePath:ee.workspacePath,useHome:ee.useHome,resumeSessionId:_.providerSessionId}).finally(()=>{fe(pe=>pe===_.providerSessionId?null:pe)})}})]})}const ci=[{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 tb({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,w]=o.useState(u);o.useEffect(()=>{w(u)},[u]);const S=o.useMemo(()=>({ide:n.length,cli:a.length,acp:i.length}),[n.length,a.length,i.length]);return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),s.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[s.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:ci.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:()=>w(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:S[x.id]})]},x.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(p=ci.find(x=>x.id===m))==null?void 0:p.helper})]}),m==="ide"&&s.jsx(Wn,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:d}),m==="cli"&&s.jsx(Wn,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:d}),m==="acp"&&s.jsx(Wn,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:d})]})}function sb({onNicknameSynced:e}={}){var fe,ne,xe,re,le,oe,Y,X,ae;const{id:t}=Zl(),r=As(),n=pa(),{sendCommand:a}=jt(),i=nr(),c=Pc(),l=lc(),u=l.ides||[],f=l.initialLoaded??!0,d=u.find(A=>A.id===t&&A.type==="adhdev-daemon"),h=u.some(A=>A.type==="adhdev-daemon"),[m,w]=o.useState("workspace"),[S,p]=o.useState("ide"),x=o.useRef(null),[j,b]=o.useState(null),N=o.useRef("__home__"),[T,y]=o.useState("__home__"),[C,k]=o.useState(!1),v=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 A=d.machine;(typeof(A==null?void 0:A.cpus)!="number"||typeof(A==null?void 0:A.totalMem)!="number"||typeof(A==null?void 0:A.arch)!="string"||typeof(A==null?void 0:A.release)!="string")&&c(t,{minFreshMs:3e4}).catch(()=>{})},[m,c,d,t]),op(t&&m==="overview"?[t]:[],{enabled:m==="overview",intervalMs:ym});const g=()=>{if(h){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},D=Nx({machineId:t,registeredMachineId:(d==null?void 0:d.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:v});o.useEffect(()=>lt.onToast(H=>{l.setToasts(me=>{if(me.some(Ae=>Ae.message===H.message&&H.timestamp-Ae.timestamp<3e3))return me;const _e={id:H.id,message:H.message,type:H.type,timestamp:H.timestamp,targetKey:H.targetKey,actions:H.actions};return[...me.slice(-4),_e]});const ce=H.duration||5e3;setTimeout(()=>l.setToasts(me=>me.filter(we=>we.id!==H.id)),ce)}),[l]);const M=(d==null?void 0:d.availableProviders)||[],I={};for(const A of M)I[A.type]=A.icon;const P=A=>I[A]||"",K=d?{id:d.id,hostname:Oi(d,{fallbackId:d.id}),platform:((fe=d.machine)==null?void 0:fe.platform)||"unknown",arch:((ne=d.machine)==null?void 0:ne.arch)||"",cpus:((xe=d.machine)==null?void 0:xe.cpus)||0,totalMem:((re=d.machine)==null?void 0:re.totalMem)||0,freeMem:(le=d.machine)==null?void 0:le.freeMem,availableMem:(oe=d.machine)==null?void 0:oe.availableMem,loadavg:(Y=d.machine)==null?void 0:Y.loadavg,uptime:(X=d.machine)==null?void 0:X.uptime,release:((ae=d.machine)==null?void 0:ae.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,V=u.filter(A=>A.daemonId===t&&A.type!=="adhdev-daemon").filter(A=>!Xs(A)&&!ys(A)).map(A=>({id:A.id,sessionId:A.sessionId,type:A.type,version:A.version||"",instanceId:A.instanceId||"",status:A.status,workspace:A.workspace||null,terminals:A.terminals||0,aiAgents:Su(A.aiAgents||(A.agents||[]).map(H=>({id:H.name,name:H.name,status:H.status,version:H.version}))),activeChat:A.activeChat||null,chats:A.chats||[],childSessions:A.childSessions||[],cdpConnected:A.cdpConnected||!1,daemonId:t})),L=u.filter(A=>A.daemonId===t&&Xs(A)).map(A=>({id:A.id,sessionId:A.sessionId,type:A.type,cliName:A.cliName||A.type,status:A.status,workspace:A.workspace||"",activeChat:A.activeChat||null,providerSessionId:A.providerSessionId,mode:A.mode,runtimeKey:A.runtimeKey,runtimeDisplayName:A.runtimeDisplayName,runtimeWorkspaceLabel:A.runtimeWorkspaceLabel,runtimeWriteOwner:A.runtimeWriteOwner||null,runtimeAttachedClients:A.runtimeAttachedClients||[],daemonId:t})),R=u.filter(A=>A.daemonId===t&&ys(A)).map(A=>({id:A.id,sessionId:A.sessionId,type:A.type,acpName:A.cliName||A.type,status:A.status,workspace:A.workspace||"",activeChat:A.activeChat||null,providerSessionId:A.providerSessionId,daemonId:t})),G=d?Mt(d,{fallbackId:t}):"",B="workspace",E=n.state,W=E==null?void 0:E.initialMachineTab,J=E==null?void 0:E.initialWorkspaceCategory,be=E==null?void 0:E.initialWorkspaceId,he=E==null?void 0:E.initialWorkspacePath,de=W==="ides"||W==="clis"||W==="acps"?"workspace":W||B,ye=W==="ides"?"ide":W==="clis"?"cli":W==="acps"?"acp":J,ge=[...V.map(A=>{var H,ce,me,we,_e;return{id:`ide:${A.type}:${A.workspace||""}`,label:((H=A.activeChat)==null?void 0:H.title)||A.type,kind:"ide",providerType:A.type,subtitle:A.workspace||void 0,workspace:A.workspace||void 0,lastLaunchedAt:((_e=(we=(me=(ce=A.activeChat)==null?void 0:ce.messages)==null?void 0:me.at)==null?void 0:we.call(me,-1))==null?void 0:_e.timestamp)||0}}),...L.map(A=>{var H,ce,me,we,_e;return{id:`cli:${A.type}:${A.workspace||""}`,label:((H=A.activeChat)==null?void 0:H.title)||A.cliName,kind:"cli",providerType:A.type,providerSessionId:A.providerSessionId,subtitle:A.workspace||void 0,workspace:A.workspace||void 0,lastLaunchedAt:((_e=(we=(me=(ce=A.activeChat)==null?void 0:ce.messages)==null?void 0:me.at)==null?void 0:we.call(me,-1))==null?void 0:_e.timestamp)||0}}),...R.map(A=>{var H,ce,me,we,_e;return{id:`acp:${A.type}:${A.workspace||""}`,label:((H=A.activeChat)==null?void 0:H.title)||A.acpName,kind:"acp",providerType:A.type,providerSessionId:A.providerSessionId,subtitle:ds(A.summaryMetadata)||A.workspace||void 0,workspace:A.workspace||void 0,lastLaunchedAt:((_e=(we=(me=(ce=A.activeChat)==null?void 0:ce.messages)==null?void 0:me.at)==null?void 0:we.call(me,-1))==null?void 0:_e.timestamp)||0}})].sort((A,H)=>(H.lastLaunchedAt||0)-(A.lastLaunchedAt||0)),ve=((d==null?void 0:d.recentLaunches)||[]).length>0?((d==null?void 0:d.recentLaunches)||[]).map(A=>({id:A.id,label:A.title||A.providerName||A.providerType,kind:A.kind,providerType:A.providerType,providerSessionId:A.providerSessionId,subtitle:ds(A.summaryMetadata)||A.workspace||void 0,workspace:A.workspace,summaryMetadata:A.summaryMetadata,lastLaunchedAt:A.lastLaunchedAt})):ge,z=o.useMemo(()=>{var H;const A=((H=l.connectionStates)==null?void 0:H[t||""])||void 0;return u.filter(ce=>ce.daemonId===t&&ce.type!=="adhdev-daemon").flatMap(ce=>Ea(ce,{connectionStates:t&&A?{[t]:A}:void 0,defaultConnectionState:A})).filter(ce=>!(ce.transport==="pty"&&ce.mode==="terminal")).sort((ce,me)=>ea(me)-ea(ce))},[u,l.connectionStates,t]),F=o.useCallback(A=>{const H=Ia(A);H&&r(Gt(H))},[r]),Q=o.useCallback(()=>{x.current&&(k(!0),x.current().finally(()=>{x.current=null,k(!1),b(null)}))},[]),ue=o.useCallback(A=>{if(!K)return;const{options:H,selectedKey:ce}=os({machine:K,currentWorkspacePath:A.workspace}),me=async()=>{p(A.kind),w("workspace")};x.current=async()=>{const we=H.find(Ke=>Ke.key===N.current),_e=(we==null?void 0:we.workspacePath)??null,Ae=(we==null?void 0:we.workspaceId)??null;if(A.kind==="ide"&&A.providerType){await D.handleLaunchIde(A.providerType,_e?{workspace:_e}:void 0);return}if((A.kind==="cli"||A.kind==="acp")&&A.providerType){await D.runLaunchCliCore({cliType:A.providerType,dir:Ae?void 0:_e||"",workspaceId:Ae||void 0,model:A.kind==="acp"&&Hi(A.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:A.providerSessionId});return}await me()},N.current=ce,y(ce),b({title:A.kind==="ide"?ss("restart-ide",A.label):A.providerSessionId?Pa(A.label):ss("start-fresh",A.label),description:A.kind==="ide"?rs("restart-ide"):A.providerSessionId?_a():rs("start-fresh"),confirmLabel:A.kind==="ide"?Cs("restart-ide"):A.providerSessionId?Ur(!0):Cs("start-fresh"),busyLabel:A.kind==="ide"?Is("restart-ide"):A.providerSessionId?La(!0):Is("start-fresh"),workspaceOptions:H,details:[{label:"Mode",value:A.kind.toUpperCase()},...A.providerType?[{label:"Provider",value:A.providerType}]:[]]})},[D,K]);if(o.useEffect(()=>{w(de)},[B,de,t]),o.useEffect(()=>{ye&&p(ye)},[ye,t]),!K)return f?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),s.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),s.jsx("button",{onClick:g,className:"machine-btn-back",children:"← Back"})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:"⏳ Loading machine..."})});const te=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ct,{size:14})," Workspace"]}),count:V.length+L.length+R.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ls,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Yr,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Td,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Id,{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:[D.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:D.nicknameInput,onChange:A=>D.setNicknameInput(A.target.value),onKeyDown:A=>{A.key==="Enter"&&D.handleSaveNickname(),A.key==="Escape"&&D.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:D.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),s.jsx("button",{onClick:()=>D.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{D.setEditingNickname(!0),D.setNicknameInput(K.machineNickname||"")},title:"Click to set nickname",children:G}),s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[K.platform," · ",K.arch]}),s.jsxs("span",{children:[K.cpus," cores"]}),(d==null?void 0:d.version)&&s.jsxs("span",{children:["v",d.version]}),K.p2p.available&&s.jsxs("span",{children:["P2P ",K.p2p.state==="connected"?"connected":K.p2p.state]}),K.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:K.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:te.map(A=>s.jsxs("button",{onClick:()=>w(A.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${m===A.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[A.label,A.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${m===A.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:A.count})]},A.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(Qx,{machineEntry:d,providers:M,recentLaunches:ve,currentConversations:z,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",{})}catch{}},onOpenRecent:ue,onOpenConversation:F}),s.jsx(tb,{machine:K,machineId:t,providers:M,ideSessions:V,cliSessions:L,acpSessions:R,actions:D,getIcon:P,initialCategory:S,initialWorkspaceId:be,initialWorkspacePath:he,sendDaemonCommand:a})]}),m==="providers"&&s.jsx(Px,{machineId:t,providers:M,sendDaemonCommand:a}),m==="overview"&&s.jsx(Cx,{machineId:t,machine:K,ideSessions:V,cliSessions:L,acpSessions:R,actions:D,sendDaemonCommand:a}),m==="session-host"&&s.jsx(Xx,{machineId:t,cliSessions:L,sendDaemonCommand:a}),m==="logs"&&s.jsx(Fx,{machineId:t,sendDaemonCommand:a})]})})}),D.launchPick&&K&&s.jsx(Jx,{machine:K,launchPick:D.launchPick,actions:D}),j&&s.jsx(za,{title:j.title,description:j.description,details:j.details,workspaceOptions:j.workspaceOptions,selectedWorkspaceKey:T,onWorkspaceChange:A=>{N.current=A,y(A)},confirmLabel:j.confirmLabel,busyLabel:j.busyLabel,busy:C,onConfirm:Q,onCancel:()=>{x.current=null,b(null)}}),s.jsx(yc,{toasts:l.toasts||[],onDismiss:A=>l.setToasts(H=>H.filter(ce=>ce.id!==A)),onClickToast:A=>{A.targetKey&&r(Gt(A.targetKey))}}),s.jsx("style",{children:`
|
|
72
72
|
@keyframes toast-in {
|
|
73
73
|
from { opacity: 0; transform: translateX(40px); }
|
|
74
74
|
to { opacity: 1; transform: translateX(0); }
|
|
75
75
|
}
|
|
76
|
-
`})]})}function qa(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function rb(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=qa();return r&&!t.searchParams.has("token")&&t.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function Et(e,t){return await fetch(rb(e),{credentials:"same-origin",...t})}function bl(){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 nb{constructor(){Ge(this,"adapters",new Map);Ge(this,"states",new Map);Ge(this,"runtimeListeners",new Map);Ge(this,"screenshotCallbacks",new Map);Ge(this,"statusCallbacks",new Set)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(t,r){this.adapters.set(t,r),this.states.set(t,r.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,r){this.states.set(t,r)}retryConnection(t){}get(t){const r=this.resolveDaemonId(t);return r?this.adapters.get(r):void 0}getState(t){const r=this.resolveDaemonId(t);return r&&this.states.get(r)||"disconnected"}sendData(t,r){return!1}sendPtyInput(t,r,n){return!1}onScreenshot(t,r){return this.screenshotCallbacks.set(t,r),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,r){this.screenshotCallbacks.forEach(n=>n(t,r))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,r){this.statusCallbacks.forEach(n=>n(t,r))}emitRuntimeSnapshot(t,r,n=0,a=!1,i,c){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:i,rows:c})}emitSessionOutput(t,r,n){!t||typeof r!="string"||!r||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(t,r){const n=this.runtimeListeners.get(t)||new Set;return n.add(r),this.runtimeListeners.set(t,n),()=>{const a=this.runtimeListeners.get(t);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,r){if(!r)return{success:!1,error:"sessionId is required"};const n=await Et(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`);if(!n.ok){let i=`Runtime snapshot unavailable (${n.status})`;try{const c=await n.json();c!=null&&c.error&&(i=c.error)}catch{}return{success:!1,error:i}}const a=await n.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof a.seq=="number"?a.seq:0,text:typeof a.text=="string"?a.text:"",truncated:!!a.truncated,cols:typeof a.cols=="number"?a.cols:void 0,rows:typeof a.rows=="number"?a.rows:void 0}),{success:!0}}emitRuntimeEvent(t,r){var n;(n=this.runtimeListeners.get(t))==null||n.forEach(a=>a(r))}}const Ot=new nb;function ab(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=qa();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Ar=ab(),li=3e3,ob=3e4;let Rt=null,ib=0;const qr=new Map;let Jt=null,Us=null;function di(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Es(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function cb(e){return e==="connected"?"connected":e}async function Er(e,t,r){const n=jc(e,r||{}),a=Rt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++ib}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{qr.delete(i),l(new Error(`WS command timeout: ${t}`))},3e4);qr.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 da(e,t){const r=Rt;if(!r||r.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(t)),!0}catch{return!1}}function lb(e,t,r){const n=Rt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=jc(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 db{constructor(t){Ge(this,"daemonId");Ge(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN}get connectionState(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return Er(this.daemonId,t,r)}async sendInput(t,r){return Er(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Jt&&(clearInterval(Jt),Jt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Er(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const a=await fetch(`data:image/jpeg;base64,${n.base64}`).then(i=>i.blob());Ot.emitScreenshot(this.daemonId,a)}}catch{}};r(),Jt=setInterval(r,2e3)}stopScreenshots(t){Jt&&(clearInterval(Jt),Jt=null)}}let At=null;function ub(e){return(!At||At.daemonId!==e)&&(At=new db(e)),At}function mb({children:e}){const t=o.useRef(Gs()),r=Gs();t.current=r;const{setUserName:n}=cs(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),u=o.useCallback((p,x)=>{l(p),Us==null||Us(p,x)},[]),f=o.useRef(null),d=o.useRef(),h=o.useRef(li),m=o.useRef(!0),w=o.useRef(!1),S=o.useRef("initial_connect");return o.useEffect(()=>{m.current=!0,w.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}...`),Es("connect_attempt",{url:Ar,reason:S.current,delayMs:h.current});let j;try{j=new WebSocket(Ar)}catch(T){console.error("[Standalone WS] Failed to create WebSocket:",T),x();return}f.current=j,j.onopen=()=>{if(!m.current){j.close();return}u("connected"),h.current=li,Es("open",{url:Ar,reason:S.current}),qt.resubscribeAll({sendData:da}),console.log("[Standalone WS] Connected")},Rt=j,j.onmessage=T=>{var y,C;try{const k=JSON.parse(T.data);if((k.type==="command_result"||k.type==="error")&&k.requestId){const v=qr.get(k.requestId);v&&(qr.delete(k.requestId),k.type==="error"?v.reject(new Error(((y=k.data)==null?void 0:y.message)||"Command failed")):v.resolve(k.data));return}if(k.type==="session_output"){const v=k.sessionId||k.cliId||k.cliType;v&&Ot.emitSessionOutput(v,typeof k.data=="string"?k.data:"",typeof k.seq=="number"?k.seq:void 0);return}if(k.type==="runtime_snapshot"){Ot.emitRuntimeSnapshot(k.sessionId,typeof k.text=="string"?k.text:"",typeof k.seq=="number"?k.seq:0,!!k.truncated,typeof k.cols=="number"?k.cols:void 0,typeof k.rows=="number"?k.rows:void 0);return}if(k.type==="topic_update"){const v=k.update;v&&qt.publish(v);return}if(k.type==="status"||k.type==="initial_state"){const v=k.data;if(!v)return;const{injectEntries:g,markLoaded:D,getIdes:M}=t.current,I=v.instanceId||"standalone",P=M().find(L=>L.id===I),K=ub(I);Ot.register(I,K),Ot.setState(I,"connected"),u("connected",I),Ot.emitStatus(I,v);const V=Fr(v,{daemonId:I,existingDaemon:P,existingEntries:M()});di("ws_status",{type:k.type,daemonId:I,sessions:(v.sessions||[]).map(L=>({id:L.id,parentId:L.parentId,providerType:L.providerType,kind:L.kind,transport:L.transport,unread:L.unread,inboxBucket:L.inboxBucket,lastSeenAt:L.lastSeenAt,lastUpdated:L.lastUpdated,title:L.title})),recentLaunches:(v.recentLaunches||[]).map(L=>({id:L.id,providerType:L.providerType,kind:L.kind,workspace:L.workspace,lastLaunchedAt:L.lastLaunchedAt}))}),di("entries",{daemonId:I,entries:V.filter(L=>L.type!=="adhdev-daemon").map(L=>({id:L.id,type:L.type,unread:L.unread,inboxBucket:L.inboxBucket,lastSeenAt:L.lastSeenAt,lastUpdated:L.lastUpdated,sessionId:L.sessionId}))}),V.length>0&&g(V,{authoritativeDaemonIds:[I]}),D(),c.current!==I&&((C=i.current)==null||C.call(i),c.current=I,i.current=qt.subscribe({sendData:da},I,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${I}`,params:{includeSessions:!0}},L=>{if(L.topic!=="daemon.metadata")return;const R=t.current.getIdes(),G=R.find(E=>E.id===I),B=Fr(L.status,{daemonId:I,existingDaemon:G,existingEntries:R,timestamp:L.timestamp});B.length>0&&t.current.injectEntries(B,{authoritativeDaemonIds:[I]}),L.userName&&a.current&&a.current(L.userName)}))}}catch(k){console.error("[Standalone WS] Parse error:",k)}},j.onclose=T=>{m.current&&(At==null||At.stopScreenshots(),At&&Ot.setState(At.daemonId,"disconnected"),u("disconnected"),f.current=null,S.current=`close:${T.code}${T.wasClean?":clean":":unclean"}`,Es("close",{code:T.code,reason:T.reason||"",wasClean:T.wasClean}),x())},j.onerror=T=>{w.current||!m.current||(S.current="error",Es("error",{message:T instanceof Event?"event":String(T),readyState:j.readyState}),console.warn("[Standalone WS] Error, will reconnect:",T))}}function x(){if(!m.current)return;clearTimeout(d.current);const j=h.current;console.log(`[Standalone WS] Reconnecting in ${j}ms...`),Es("schedule_reconnect",{reason:S.current,delayMs:j}),d.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,ob),p()},j)}return p(),()=>{var j;m.current=!1,w.current=!0,(j=i.current)==null||j.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),At&&(At.stopScreenshots(),Ot.unregister(At.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function fb({children:e}){const[t,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(Us=(c,l)=>{r(c),l&&a(l)},()=>{Us=null}),[]);const i=o.useMemo(()=>{const c=t==="connected",l=cb(t),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:t,isConnected:c,connectionStates:u}},[t,n]);return s.jsx(bd,{connectionOverrides:i,children:s.jsx(mb,{children:e})})}const gl="adhdev_standalone_font_preferences",is={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},ln=[{id:"default",label:"Default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS font-family stack"}],Zs=[{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"}],pb=new Set(ln.map(e=>e.id)),hb=new Set(Zs.map(e=>e.id));function Bt(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:$r("chat",t.chat),code:$r("code",t.code),terminal:$r("terminal",t.terminal)}}function $r(e,t){const r=is[e],n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof n.preset=="string"?n.preset.trim():"",i=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?pb:hb).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:a}:r}function Br(e,t){var a;const r=$r(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?ln:Zs;return((a=n.find(i=>i.id===r.preset))==null?void 0:a.family)||n[0].family}function xb(e){const t=Bt(e),r=Br("chat",t.chat),n=Br("code",t.code),a=Br("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Zt(e,t=document.documentElement){const r=Bt(e),n=xb(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))t.style.setProperty(a,i);return r}function ua(e){const t=Bt(e);try{localStorage.setItem(gl,JSON.stringify(t))}catch{}return t}function bb(){try{const e=localStorage.getItem(gl);if(e)return Bt(JSON.parse(e))}catch{}return is}function gb(){return Zt(bb())}function $s(e,t){var n;const r=e==="chat"?ln:Zs;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const yb=[{id:"dashboard",path:"/dashboard",icon:s.jsx(ki,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(ls,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:s.jsx(Yr,{}),label:"Settings"}];function vb({children:e}){const t=As(),r=pa(),n=o.useMemo(()=>yb.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(Ni,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Ci,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(Rf,{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.22"]}),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 wb=[{icon:s.jsx(ls,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Ft,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Ii,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(Ct,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Ys,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Ni,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],jb=[{icon:s.jsx(Rd,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(ki,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Xr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Cd,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Si,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Ad,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],kb=[{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 Sb(){return s.jsxs(Cc,{icon:s.jsx(Ci,{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.22"]}),children:[s.jsx(Nt,{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(Nt,{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:wb.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(Nt,{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:kc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Nc.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Sc.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(Nt,{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:jb.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(Nt,{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:kb.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(Ac,{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(Hd,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Hn(e,t,r){return{...e,[t]:r}}function Fn({surface:e,title:t,description:r,value:n,options:a,onChange:i}){return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("select",{className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",value:n.preset,onChange:c=>{const l=c.target.value;i(l==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:l})},children:a.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),n.preset==="custom"&&s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:n.customFamily||"",onChange:c=>i({preset:"custom",customFamily:c.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",s.jsx("span",{className:"font-mono break-all",children:Br(e,n)})]})]})]})}function Nb({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(Fn,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:ln,onChange:d=>i(Hn(e,"chat",d))}),s.jsx(Fn,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:Zs,onChange:d=>i(Hn(e,"code",d))}),s.jsx(Fn,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:Zs,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: ",$s("chat",e.chat.preset)," · Code: ",$s("code",e.code.preset)," · Terminal: ",$s("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",$s("chat",is.chat.preset)," / ",$s("code",is.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:c,disabled:r||!f,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),s.jsx("button",{type:"button",onClick:l,disabled:r||!f,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert to saved"}),s.jsx("button",{type:"button",onClick: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 Cb(){const{ides:e}=cs(),t=e.find(z=>z.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=jt(),{userName:a}=cs(),[i,c]=o.useState(a||""),[l,u]=o.useState(null),[f,d]=o.useState(null),[h,m]=o.useState(is),[w,S]=o.useState(!1),[p,x]=o.useState(""),[j,b]=o.useState(""),[N,T]=o.useState("127.0.0.1"),[y,C]=o.useState(""),[k,v]=o.useState(""),[g,D]=o.useState(""),[M,I]=o.useState(""),[P,K]=o.useState(""),[V,L]=o.useState(!1),R=async()=>{const F=await(await Et("/auth/session")).json();u(F)},G=async()=>{const F=await(await Et("/api/v1/standalone/preferences")).json();d(F),T(F.standaloneBindHost);const Q=Bt(F.standaloneFontPreferences);m(Q),Zt(Q),ua(Q)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([R(),G()]).catch(z=>{I(z instanceof Error?z.message:String(z))})},[]),o.useEffect(()=>{Zt(h)},[h]);const B=z=>{const F=z.target.value.trim();t!=null&&t.id&&F!==a&&n(t.id,"set_user_name",{userName:F}).catch(console.error)},[E,W]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),J=z=>{W(z);try{localStorage.setItem("adhdev_sound",z?"1":"0")}catch{}},be=async()=>{x(""),b(""),S(!0);try{const z=Bt(h),F=await Et("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:z})}),Q=await F.json();if(!F.ok)throw new Error((Q==null?void 0:Q.error)||"Failed to save standalone font preferences");const ue=Bt(Q.standaloneFontPreferences);d(Q),m(ue),Zt(ue),ua(ue),b("Standalone chat fonts saved for this self-hosted dashboard.")}catch(z){x(z instanceof Error?z.message:String(z))}finally{S(!1)}},he=()=>{const z=Bt(f==null?void 0:f.standaloneFontPreferences);x(""),b(""),m(z),Zt(z)},de=()=>{x(""),b(""),m(is),Zt(is)},ye=async()=>{I(""),K(""),L(!0);try{const z=await Et("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:N})}),F=await z.json();if(!z.ok)throw new Error((F==null?void 0:F.error)||"Failed to save standalone network preference");d(F),T(F.standaloneBindHost),K(F.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(z){I(z instanceof Error?z.message:String(z))}finally{L(!1)}},ge=async()=>{if(I(""),K(""),k.trim().length<4){I("Password must be at least 4 characters.");return}if(k!==g){I("New password and confirmation do not match.");return}L(!0);try{const z=await Et("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,newPassword:k})}),F=await z.json();if(!z.ok)throw new Error((F==null?void 0:F.error)||"Failed to save password");u(F),await G(),C(""),v(""),D(""),K(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),bl()}catch(z){I(z instanceof Error?z.message:String(z))}finally{L(!1)}},ve=async()=>{I(""),K(""),L(!0);try{const z=await Et("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,clear:!0})}),F=await z.json();if(!z.ok)throw new Error((F==null?void 0:F.error)||"Failed to clear password");u(F),await G(),C(""),v(""),D(""),K("Standalone password disabled.")}catch(z){I(z instanceof Error?z.message:String(z))}finally{L(!1)}};return s.jsxs(Cc,{icon:s.jsx(Yr,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(gr,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint."}),(l==null?void 0:l.publicHostWarning)&&s.jsx(gr,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),s.jsx(Nt,{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.22"]}),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(Nt,{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:()=>T("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:()=>T("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:()=>{ye()},disabled:V,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:V?"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(Nt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:l!=null&&l.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),M&&s.jsx(gr,{variant:"error",children:M}),P&&s.jsx(gr,{variant:"success",children:P}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:y,onChange:z=>C(z.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"New password":"New standalone password",value:k,onChange:z=>v(z.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:z=>D(z.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{ge()},disabled:V,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:V?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{ve()},disabled:V,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(Nt,{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(z=>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 ${z.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:z.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:z.type})]},z.type))})}),s.jsx(Nt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(Wf,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(Nt,{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(zf,{})]}),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(Zf,{})]}),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(Nb,{value:h,savedValue:Bt(f==null?void 0:f.standaloneFontPreferences),saving:w,error:p,notice:j,onChange:m,onSave:()=>{be()},onResetToSaved:he,onResetToDefaults:de})]}),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(sp,{})]})]})}),s.jsx(Nt,{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(Bf,{}),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Wd,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:E,onChange:J})]})}),s.jsx(Nt,{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(Nd,{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:z=>c(z.target.value),onBlur:B,onKeyDown:z=>{z.key==="Enter"&&z.currentTarget.blur()}})]})})})]})}Tf();Jf();gb();const Ib=vi({baseUrl:"",getToken:qa});function Ab({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 S=await(await Et("/auth/session")).json();r(S)}catch(w){u(w instanceof Error?w.message:String(w))}finally{a(!1)}};o.useEffect(()=>{h()},[]),o.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let w=!1;return(async()=>{try{const S=await Et("/api/v1/standalone/preferences");if(!S.ok)return;const p=await S.json();if(w)return;const x=Bt(p.standaloneFontPreferences);Zt(x),ua(x)}catch{}})(),()=>{w=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const m=async w=>{w.preventDefault(),d(!0),u("");try{const S=await Et("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),p=await S.json();if(!S.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),c(""),bl()}catch(S){u(S instanceof Error?S.message:String(S))}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:w=>c(w.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),s.jsx("button",{type:"submit",disabled: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 ui(){const{ides:e,initialLoaded:t}=cs();if(!t)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?s.jsx(Vn,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Vn,{to:"/dashboard",replace:!0})}function Mb(){const e=o.useMemo(()=>({sendCommand:Er,sendData:da,sendPtyInput:lb}),[]);return s.jsx(ed,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(vd,{client:Ib,children:s.jsx(Ab,{children:s.jsx(fb,{children:s.jsx(jd,{value:e,children:s.jsx(vb,{children:s.jsxs(td,{children:[s.jsx(Yt,{path:"/dashboard",element:s.jsx(Sx,{})}),s.jsx(Yt,{path:"/machine",element:s.jsx(ui,{})}),s.jsx(Yt,{path:"/machines/:id",element:s.jsx(sb,{})}),s.jsx(Yt,{path:"/machines",element:s.jsx(ui,{})}),s.jsx(Yt,{path:"/about",element:s.jsx(Sb,{})}),s.jsx(Yt,{path:"/settings",element:s.jsx(Cb,{})}),s.jsx(Yt,{path:"*",element:s.jsx(Vn,{to:"/dashboard",replace:!0})})]})})})})})})})}qm({connectionManager:Ot});sd(document.getElementById("root")).render(s.jsx(Mb,{}));
|
|
76
|
+
`})]})}function qa(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function rb(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=qa();return r&&!t.searchParams.has("token")&&t.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function Et(e,t){return await fetch(rb(e),{credentials:"same-origin",...t})}function bl(){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 nb{constructor(){Ge(this,"adapters",new Map);Ge(this,"states",new Map);Ge(this,"runtimeListeners",new Map);Ge(this,"screenshotCallbacks",new Map);Ge(this,"statusCallbacks",new Set)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(t,r){this.adapters.set(t,r),this.states.set(t,r.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,r){this.states.set(t,r)}retryConnection(t){}get(t){const r=this.resolveDaemonId(t);return r?this.adapters.get(r):void 0}getState(t){const r=this.resolveDaemonId(t);return r&&this.states.get(r)||"disconnected"}sendData(t,r){return!1}sendPtyInput(t,r,n){return!1}onScreenshot(t,r){return this.screenshotCallbacks.set(t,r),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,r){this.screenshotCallbacks.forEach(n=>n(t,r))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,r){this.statusCallbacks.forEach(n=>n(t,r))}emitRuntimeSnapshot(t,r,n=0,a=!1,i,c){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:i,rows:c})}emitSessionOutput(t,r,n){!t||typeof r!="string"||!r||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(t,r){const n=this.runtimeListeners.get(t)||new Set;return n.add(r),this.runtimeListeners.set(t,n),()=>{const a=this.runtimeListeners.get(t);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,r){if(!r)return{success:!1,error:"sessionId is required"};const n=await Et(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`);if(!n.ok){let i=`Runtime snapshot unavailable (${n.status})`;try{const c=await n.json();c!=null&&c.error&&(i=c.error)}catch{}return{success:!1,error:i}}const a=await n.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof a.seq=="number"?a.seq:0,text:typeof a.text=="string"?a.text:"",truncated:!!a.truncated,cols:typeof a.cols=="number"?a.cols:void 0,rows:typeof a.rows=="number"?a.rows:void 0}),{success:!0}}emitRuntimeEvent(t,r){var n;(n=this.runtimeListeners.get(t))==null||n.forEach(a=>a(r))}}const Ot=new nb;function ab(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=qa();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Ar=ab(),li=3e3,ob=3e4;let Rt=null,ib=0;const qr=new Map;let Jt=null,Us=null;function di(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Es(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function cb(e){return e==="connected"?"connected":e}async function Er(e,t,r){const n=jc(e,r||{}),a=Rt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++ib}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{qr.delete(i),l(new Error(`WS command timeout: ${t}`))},3e4);qr.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 da(e,t){const r=Rt;if(!r||r.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(t)),!0}catch{return!1}}function lb(e,t,r){const n=Rt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=jc(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 db{constructor(t){Ge(this,"daemonId");Ge(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN}get connectionState(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return Er(this.daemonId,t,r)}async sendInput(t,r){return Er(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Jt&&(clearInterval(Jt),Jt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Er(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const a=await fetch(`data:image/jpeg;base64,${n.base64}`).then(i=>i.blob());Ot.emitScreenshot(this.daemonId,a)}}catch{}};r(),Jt=setInterval(r,2e3)}stopScreenshots(t){Jt&&(clearInterval(Jt),Jt=null)}}let At=null;function ub(e){return(!At||At.daemonId!==e)&&(At=new db(e)),At}function mb({children:e}){const t=o.useRef(Gs()),r=Gs();t.current=r;const{setUserName:n}=cs(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),u=o.useCallback((p,x)=>{l(p),Us==null||Us(p,x)},[]),f=o.useRef(null),d=o.useRef(),h=o.useRef(li),m=o.useRef(!0),w=o.useRef(!1),S=o.useRef("initial_connect");return o.useEffect(()=>{m.current=!0,w.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}...`),Es("connect_attempt",{url:Ar,reason:S.current,delayMs:h.current});let j;try{j=new WebSocket(Ar)}catch(T){console.error("[Standalone WS] Failed to create WebSocket:",T),x();return}f.current=j,j.onopen=()=>{if(!m.current){j.close();return}u("connected"),h.current=li,Es("open",{url:Ar,reason:S.current}),qt.resubscribeAll({sendData:da}),console.log("[Standalone WS] Connected")},Rt=j,j.onmessage=T=>{var y,C;try{const k=JSON.parse(T.data);if((k.type==="command_result"||k.type==="error")&&k.requestId){const v=qr.get(k.requestId);v&&(qr.delete(k.requestId),k.type==="error"?v.reject(new Error(((y=k.data)==null?void 0:y.message)||"Command failed")):v.resolve(k.data));return}if(k.type==="session_output"){const v=k.sessionId||k.cliId||k.cliType;v&&Ot.emitSessionOutput(v,typeof k.data=="string"?k.data:"",typeof k.seq=="number"?k.seq:void 0);return}if(k.type==="runtime_snapshot"){Ot.emitRuntimeSnapshot(k.sessionId,typeof k.text=="string"?k.text:"",typeof k.seq=="number"?k.seq:0,!!k.truncated,typeof k.cols=="number"?k.cols:void 0,typeof k.rows=="number"?k.rows:void 0);return}if(k.type==="topic_update"){const v=k.update;v&&qt.publish(v);return}if(k.type==="status"||k.type==="initial_state"){const v=k.data;if(!v)return;const{injectEntries:g,markLoaded:D,getIdes:M}=t.current,I=v.instanceId||"standalone",P=M().find(L=>L.id===I),K=ub(I);Ot.register(I,K),Ot.setState(I,"connected"),u("connected",I),Ot.emitStatus(I,v);const V=Fr(v,{daemonId:I,existingDaemon:P,existingEntries:M()});di("ws_status",{type:k.type,daemonId:I,sessions:(v.sessions||[]).map(L=>({id:L.id,parentId:L.parentId,providerType:L.providerType,kind:L.kind,transport:L.transport,unread:L.unread,inboxBucket:L.inboxBucket,lastSeenAt:L.lastSeenAt,lastUpdated:L.lastUpdated,title:L.title})),recentLaunches:(v.recentLaunches||[]).map(L=>({id:L.id,providerType:L.providerType,kind:L.kind,workspace:L.workspace,lastLaunchedAt:L.lastLaunchedAt}))}),di("entries",{daemonId:I,entries:V.filter(L=>L.type!=="adhdev-daemon").map(L=>({id:L.id,type:L.type,unread:L.unread,inboxBucket:L.inboxBucket,lastSeenAt:L.lastSeenAt,lastUpdated:L.lastUpdated,sessionId:L.sessionId}))}),V.length>0&&g(V,{authoritativeDaemonIds:[I]}),D(),c.current!==I&&((C=i.current)==null||C.call(i),c.current=I,i.current=qt.subscribe({sendData:da},I,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${I}`,params:{includeSessions:!0}},L=>{if(L.topic!=="daemon.metadata")return;const R=t.current.getIdes(),G=R.find(E=>E.id===I),B=Fr(L.status,{daemonId:I,existingDaemon:G,existingEntries:R,timestamp:L.timestamp});B.length>0&&t.current.injectEntries(B,{authoritativeDaemonIds:[I]}),L.userName&&a.current&&a.current(L.userName)}))}}catch(k){console.error("[Standalone WS] Parse error:",k)}},j.onclose=T=>{m.current&&(At==null||At.stopScreenshots(),At&&Ot.setState(At.daemonId,"disconnected"),u("disconnected"),f.current=null,S.current=`close:${T.code}${T.wasClean?":clean":":unclean"}`,Es("close",{code:T.code,reason:T.reason||"",wasClean:T.wasClean}),x())},j.onerror=T=>{w.current||!m.current||(S.current="error",Es("error",{message:T instanceof Event?"event":String(T),readyState:j.readyState}),console.warn("[Standalone WS] Error, will reconnect:",T))}}function x(){if(!m.current)return;clearTimeout(d.current);const j=h.current;console.log(`[Standalone WS] Reconnecting in ${j}ms...`),Es("schedule_reconnect",{reason:S.current,delayMs:j}),d.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,ob),p()},j)}return p(),()=>{var j;m.current=!1,w.current=!0,(j=i.current)==null||j.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),At&&(At.stopScreenshots(),Ot.unregister(At.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function fb({children:e}){const[t,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(Us=(c,l)=>{r(c),l&&a(l)},()=>{Us=null}),[]);const i=o.useMemo(()=>{const c=t==="connected",l=cb(t),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:t,isConnected:c,connectionStates:u}},[t,n]);return s.jsx(bd,{connectionOverrides:i,children:s.jsx(mb,{children:e})})}const gl="adhdev_standalone_font_preferences",is={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},ln=[{id:"default",label:"Default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS font-family stack"}],Zs=[{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"}],pb=new Set(ln.map(e=>e.id)),hb=new Set(Zs.map(e=>e.id));function Bt(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:$r("chat",t.chat),code:$r("code",t.code),terminal:$r("terminal",t.terminal)}}function $r(e,t){const r=is[e],n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof n.preset=="string"?n.preset.trim():"",i=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?pb:hb).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:a}:r}function Br(e,t){var a;const r=$r(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?ln:Zs;return((a=n.find(i=>i.id===r.preset))==null?void 0:a.family)||n[0].family}function xb(e){const t=Bt(e),r=Br("chat",t.chat),n=Br("code",t.code),a=Br("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Zt(e,t=document.documentElement){const r=Bt(e),n=xb(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))t.style.setProperty(a,i);return r}function ua(e){const t=Bt(e);try{localStorage.setItem(gl,JSON.stringify(t))}catch{}return t}function bb(){try{const e=localStorage.getItem(gl);if(e)return Bt(JSON.parse(e))}catch{}return is}function gb(){return Zt(bb())}function $s(e,t){var n;const r=e==="chat"?ln:Zs;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const yb=[{id:"dashboard",path:"/dashboard",icon:s.jsx(ki,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(ls,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:s.jsx(Yr,{}),label:"Settings"}];function vb({children:e}){const t=As(),r=pa(),n=o.useMemo(()=>yb.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(Ni,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Ci,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(Rf,{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.23"]}),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 wb=[{icon:s.jsx(ls,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Ft,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Ii,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(Ct,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Ys,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Ni,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],jb=[{icon:s.jsx(Rd,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(ki,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Xr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Cd,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Si,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Ad,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],kb=[{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 Sb(){return s.jsxs(Cc,{icon:s.jsx(Ci,{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.23"]}),children:[s.jsx(Nt,{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(Nt,{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:wb.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(Nt,{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:kc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Nc.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Sc.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(Nt,{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:jb.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(Nt,{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:kb.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(Ac,{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(Hd,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Hn(e,t,r){return{...e,[t]:r}}function Fn({surface:e,title:t,description:r,value:n,options:a,onChange:i}){return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("select",{className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",value:n.preset,onChange:c=>{const l=c.target.value;i(l==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:l})},children:a.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),n.preset==="custom"&&s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:n.customFamily||"",onChange:c=>i({preset:"custom",customFamily:c.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",s.jsx("span",{className:"font-mono break-all",children:Br(e,n)})]})]})]})}function Nb({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(Fn,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:ln,onChange:d=>i(Hn(e,"chat",d))}),s.jsx(Fn,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:Zs,onChange:d=>i(Hn(e,"code",d))}),s.jsx(Fn,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:Zs,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: ",$s("chat",e.chat.preset)," · Code: ",$s("code",e.code.preset)," · Terminal: ",$s("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",$s("chat",is.chat.preset)," / ",$s("code",is.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:c,disabled:r||!f,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),s.jsx("button",{type:"button",onClick:l,disabled:r||!f,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert to saved"}),s.jsx("button",{type:"button",onClick: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 Cb(){const{ides:e}=cs(),t=e.find(z=>z.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=jt(),{userName:a}=cs(),[i,c]=o.useState(a||""),[l,u]=o.useState(null),[f,d]=o.useState(null),[h,m]=o.useState(is),[w,S]=o.useState(!1),[p,x]=o.useState(""),[j,b]=o.useState(""),[N,T]=o.useState("127.0.0.1"),[y,C]=o.useState(""),[k,v]=o.useState(""),[g,D]=o.useState(""),[M,I]=o.useState(""),[P,K]=o.useState(""),[V,L]=o.useState(!1),R=async()=>{const F=await(await Et("/auth/session")).json();u(F)},G=async()=>{const F=await(await Et("/api/v1/standalone/preferences")).json();d(F),T(F.standaloneBindHost);const Q=Bt(F.standaloneFontPreferences);m(Q),Zt(Q),ua(Q)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([R(),G()]).catch(z=>{I(z instanceof Error?z.message:String(z))})},[]),o.useEffect(()=>{Zt(h)},[h]);const B=z=>{const F=z.target.value.trim();t!=null&&t.id&&F!==a&&n(t.id,"set_user_name",{userName:F}).catch(console.error)},[E,W]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),J=z=>{W(z);try{localStorage.setItem("adhdev_sound",z?"1":"0")}catch{}},be=async()=>{x(""),b(""),S(!0);try{const z=Bt(h),F=await Et("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:z})}),Q=await F.json();if(!F.ok)throw new Error((Q==null?void 0:Q.error)||"Failed to save standalone font preferences");const ue=Bt(Q.standaloneFontPreferences);d(Q),m(ue),Zt(ue),ua(ue),b("Standalone chat fonts saved for this self-hosted dashboard.")}catch(z){x(z instanceof Error?z.message:String(z))}finally{S(!1)}},he=()=>{const z=Bt(f==null?void 0:f.standaloneFontPreferences);x(""),b(""),m(z),Zt(z)},de=()=>{x(""),b(""),m(is),Zt(is)},ye=async()=>{I(""),K(""),L(!0);try{const z=await Et("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:N})}),F=await z.json();if(!z.ok)throw new Error((F==null?void 0:F.error)||"Failed to save standalone network preference");d(F),T(F.standaloneBindHost),K(F.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(z){I(z instanceof Error?z.message:String(z))}finally{L(!1)}},ge=async()=>{if(I(""),K(""),k.trim().length<4){I("Password must be at least 4 characters.");return}if(k!==g){I("New password and confirmation do not match.");return}L(!0);try{const z=await Et("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,newPassword:k})}),F=await z.json();if(!z.ok)throw new Error((F==null?void 0:F.error)||"Failed to save password");u(F),await G(),C(""),v(""),D(""),K(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),bl()}catch(z){I(z instanceof Error?z.message:String(z))}finally{L(!1)}},ve=async()=>{I(""),K(""),L(!0);try{const z=await Et("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,clear:!0})}),F=await z.json();if(!z.ok)throw new Error((F==null?void 0:F.error)||"Failed to clear password");u(F),await G(),C(""),v(""),D(""),K("Standalone password disabled.")}catch(z){I(z instanceof Error?z.message:String(z))}finally{L(!1)}};return s.jsxs(Cc,{icon:s.jsx(Yr,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(gr,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint."}),(l==null?void 0:l.publicHostWarning)&&s.jsx(gr,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),s.jsx(Nt,{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.23"]}),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(Nt,{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:()=>T("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:()=>T("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:()=>{ye()},disabled:V,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:V?"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(Nt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:l!=null&&l.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),M&&s.jsx(gr,{variant:"error",children:M}),P&&s.jsx(gr,{variant:"success",children:P}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:y,onChange:z=>C(z.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"New password":"New standalone password",value:k,onChange:z=>v(z.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:z=>D(z.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{ge()},disabled:V,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:V?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{ve()},disabled:V,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(Nt,{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(z=>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 ${z.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:z.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:z.type})]},z.type))})}),s.jsx(Nt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(Wf,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(Nt,{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(zf,{})]}),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(Zf,{})]}),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(Nb,{value:h,savedValue:Bt(f==null?void 0:f.standaloneFontPreferences),saving:w,error:p,notice:j,onChange:m,onSave:()=>{be()},onResetToSaved:he,onResetToDefaults:de})]}),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(sp,{})]})]})}),s.jsx(Nt,{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(Bf,{}),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Wd,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:E,onChange:J})]})}),s.jsx(Nt,{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(Nd,{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:z=>c(z.target.value),onBlur:B,onKeyDown:z=>{z.key==="Enter"&&z.currentTarget.blur()}})]})})})]})}Tf();Jf();gb();const Ib=vi({baseUrl:"",getToken:qa});function Ab({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 S=await(await Et("/auth/session")).json();r(S)}catch(w){u(w instanceof Error?w.message:String(w))}finally{a(!1)}};o.useEffect(()=>{h()},[]),o.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let w=!1;return(async()=>{try{const S=await Et("/api/v1/standalone/preferences");if(!S.ok)return;const p=await S.json();if(w)return;const x=Bt(p.standaloneFontPreferences);Zt(x),ua(x)}catch{}})(),()=>{w=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const m=async w=>{w.preventDefault(),d(!0),u("");try{const S=await Et("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),p=await S.json();if(!S.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),c(""),bl()}catch(S){u(S instanceof Error?S.message:String(S))}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:w=>c(w.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),s.jsx("button",{type:"submit",disabled: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 ui(){const{ides:e,initialLoaded:t}=cs();if(!t)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?s.jsx(Vn,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Vn,{to:"/dashboard",replace:!0})}function Mb(){const e=o.useMemo(()=>({sendCommand:Er,sendData:da,sendPtyInput:lb}),[]);return s.jsx(ed,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(vd,{client:Ib,children:s.jsx(Ab,{children:s.jsx(fb,{children:s.jsx(jd,{value:e,children:s.jsx(vb,{children:s.jsxs(td,{children:[s.jsx(Yt,{path:"/dashboard",element:s.jsx(Sx,{})}),s.jsx(Yt,{path:"/machine",element:s.jsx(ui,{})}),s.jsx(Yt,{path:"/machines/:id",element:s.jsx(sb,{})}),s.jsx(Yt,{path:"/machines",element:s.jsx(ui,{})}),s.jsx(Yt,{path:"/about",element:s.jsx(Sb,{})}),s.jsx(Yt,{path:"/settings",element:s.jsx(Cb,{})}),s.jsx(Yt,{path:"*",element:s.jsx(Vn,{to:"/dashboard",replace:!0})})]})})})})})})})}qm({connectionManager:Ot});sd(document.getElementById("root")).render(s.jsx(Mb,{}));
|