@adhdev/daemon-standalone 0.8.83 → 0.8.84

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.
@@ -29,7 +29,7 @@ ${n}`}function Bu(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0
29
29
 
30
30
  `)))return}const B=(c==null?void 0:c[R.id])??d[R.id];try{const S=await v(R.invokeScript),D=Tr(S);if(D&&!D.ok||Lr(S))throw new Error((D==null?void 0:D.error)||Ys(S)||`Could not run ${R.label}`);D&&x(R,B??!0,D)}catch(S){E(R,B);const D=S instanceof Error?S.message:`Could not run ${R.label}`;st.showToast(D,"warning")}};return t.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1 flex-wrap text-[10px] border-t border-border-subtle bg-surface-primary font-[var(--font)]",children:[t.jsx("span",{className:"text-[9px] font-bold tracking-wide opacity-70",style:{color:p},children:a}),t.jsx("span",{className:"text-border-subtle text-[10px]",children:"│"}),T.map(R=>{const B=String(b[R.id]||""),S=Yu(R,y,B),D=N===R.id,Y=k===R.id,q=Gr(R,y);switch(R.type){case"select":return t.jsxs("div",{className:"relative",children:[t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all bg-[var(--surface-tertiary)] whitespace-nowrap max-w-40 overflow-hidden text-ellipsis",style:{borderColor:D?`${p}55`:"transparent",border:"1px solid",color:B?"var(--text-primary)":"var(--text-muted)"},onClick:()=>L(R),children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),Y?"...":S||R.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),D&&q.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>_(null)}),t.jsxs("div",{className:"absolute bottom-full left-0 z-[60] bg-[var(--surface-primary)] border border-border-subtle rounded-lg mb-1 max-h-[220px] overflow-y-auto min-w-40 shadow-[0_-4px_16px_rgba(0,0,0,0.3)]",children:[t.jsx("div",{className:"px-3 py-1.5 text-[9px] font-bold text-text-muted tracking-wider border-b border-border-subtle",children:R.label.toUpperCase()}),q.map(H=>t.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:H.value===B?`${p}18`:"transparent",color:H.value===B?p:"var(--text-secondary)",fontWeight:H.value===B?600:400,borderLeft:H.value===B?`2px solid ${p}`:"2px solid transparent"},title:H.description||H.label,onMouseEnter:re=>{re.currentTarget.style.background=`${p}12`},onMouseLeave:re=>{re.currentTarget.style.background=H.value===B?`${p}18`:"transparent"},onClick:()=>M(R,H.value),children:H.label},H.value))]})]})]},R.id);case"cycle":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all bg-[var(--surface-tertiary)] whitespace-nowrap",style:{border:"1px solid transparent",color:B?"var(--text-primary)":"var(--text-muted)"},onClick:()=>W(R),title:`Click to cycle: ${q.map(H=>H.label).join(" → ")}`,children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),S||R.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"⟳"})]},R.id);case"toggle":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all whitespace-nowrap",style:{border:"1px solid",borderColor:B?`${p}44`:"transparent",background:B?`${p}14`:"var(--surface-tertiary)",color:B?p:"var(--text-muted)"},onClick:()=>U(R),children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),R.label]},R.id);case"action":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all hover:bg-[var(--surface-tertiary-hover)] whitespace-nowrap",style:{border:"1px solid var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>C(R),children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),R.resultDisplay==="inline"&&B?`${R.label}: ${B}`:R.label]},R.id);case"display":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium whitespace-nowrap",style:{border:"1px solid var(--border-default)",background:"var(--surface-tertiary)",color:B?"var(--text-primary)":"var(--text-muted)"},children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),B?`${R.label}: ${B}`:R.label]},R.id);default:return null}})]})}function Ju({isActive:e=!0,isCliTerminal:s=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:u}){const{isVisible:p}=Gi(),m=_a(l,{hostIdeType:a,providerType:i});return!e||s||m.length===0||!p?null:t.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:t.jsx(Qu,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:m,controlValues:u})})}function tc({hasDraft:e,isBusy:s=!1}){return!e||s}const Zu=o.memo(function({contextKey:s,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:i=null,onSend:c,isActive:l=!0,showControlsToggle:u=!1}){const p=o.useRef(null),[m,f]=o.useState(""),{isVisible:g,toggleVisibility:w}=Gi();o.useEffect(()=>{f("")},[s]),o.useEffect(()=>{var d;l&&((d=p.current)==null||d.focus())},[s,l]);const A=async()=>{const d=m.trim();if(!d||a)return;await c(d)!==!1&&f("")};return t.jsxs("div",{className:"dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden transition-all duration-200 ease-out",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:[t.jsxs("div",{className:"flex gap-2 items-center",title:l?`Send message to ${r}`:void 0,children:[u&&t.jsx("button",{type:"button",onClick:w,"aria-label":g?"Hide controls":"Show controls","aria-pressed":g,title:g?"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:t.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[t.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),t.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),t.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:p,type:"text",placeholder:i||`Send message to ${r}...`,value:m,onChange:d=>f(d.target.value),onPaste:d=>{const b=d.clipboardData.getData("text");b&&f(y=>y+b),d.preventDefault()},onKeyDown:d=>{if(d.key==="Enter"){if(d.nativeEvent.isComposing){d.preventDefault();return}d.preventDefault(),A()}},onBlur:d=>{if(window.innerWidth<768){const b=d.relatedTarget;if((b==null?void 0:b.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))"}})}),t.jsx("button",{onClick:()=>{A()},disabled:tc({hasDraft:!!m.trim(),isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${m.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:m.trim()&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:t.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:m.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),i&&t.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),tt=e=>e.transport==="pty",Bs=(e,s)=>tt(e)?e.mode||"terminal":"chat",sc=(e,s)=>tt(e)&&Bs(e)==="terminal",Ze=e=>e.transport==="acp";function rs(e){return e.streamSource!=="agent-stream"}function os(e){var s;return e.daemonId||((s=e.routeId)==null?void 0:s.split(":")[0])||e.routeId||""}function rc(e){return e.machineName||""}function gr(e){return os(e)}function Bt(e){return e.agentType||""}function sn(e){return e.hostIdeType||""}function Ra(e){return e.displayPrimary||e.agentName||"Agent"}function nc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function em(e){return e.lastMessagePreview||e.displaySecondary||""}function ac(e){return[e.displaySecondary,rc(e)].filter(Boolean)}function Ws(e){return e.agentName||ot(Bt(e))}function tm(e){var s,r;if(!rs(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return ot(sn(e)||Bt(e))}function oc(e){return rs(e)?e.sessionId:e.nativeSessionId}function Ro(e){return rs(e)?"native":e.tabKey}function sm(e){return e.sessionId}function rm(e,s){if(s)return rs(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function nm(e,s){const r=Bt(e),n=rs(e),a=tt(e)||Ze(e),i=n?a?Ws(e)||(s==null?void 0:s.cliName)||ot(sn(e)||r):s!=null&&s.type?ot(s.type):ot(sn(e)||r):Ws(e);return{isNativeConversation:n,isCli:tt(e),isAcp:Ze(e),isCliTerminal:sc(e),providerType:r,displayLabel:i,targetEntry:rm(e,s)}}function am(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Date.parse(e);if(Number.isFinite(s))return s}return 0}function us(e){const s=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1];return e.lastMessageAt||am(s==null?void 0:s.receivedAt)||0}function ia(e,s=0){return us(e)||e.lastUpdated||s||0}function ic(e){return us(e)||e.lastUpdated||0}function cc(e,s,r=ic){const n=r(s)-r(e);if(n!==0)return n;const a=(e.machineName||"").localeCompare(s.machineName||"");if(a!==0)return a;const i=e.displayPrimary.localeCompare(s.displayPrimary);if(i!==0)return i;const c=e.displaySecondary.localeCompare(s.displaySecondary);return c!==0?c:e.tabKey.localeCompare(s.tabKey)}function ca(e){var r;const s=Ct(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function om(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!ca(e)&&!e.title.trim()}function im(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(ca(r))-Number(ca(s));if(n!==0)return n;const a=r.messages.length-s.messages.length;return a!==0?a:cc(s,r)})[0]||null}function Ot(e,s){const r=e.filter(c=>c.routeId===s);if(r.length===0)return null;const n=r.find(c=>c.streamSource==="native")||null,a=r.filter(c=>c.streamSource==="agent-stream"),i=im(a);return n?i&&om(n)?i:n:i||r[0]||null}function ns(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Pa(e){return br(e)||e.tabKey||e.routeId||null}function lc(e){const s=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"";if(s)return s;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=Ot(e.conversations,n)||e.conversations.find(i=>i.routeId===n);return a?Pa(a):null}function dc({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=Us(),c=os(e),l=rc(e),u=e.transport==="cdp-page"||e.transport==="cdp-webview",p=e.streamSource==="agent-stream"&&!!e.agentName,m=!p&&(e.transport==="pty"||e.transport==="acp"),f=Ws(e),g=tm(e),w=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),A=o.useCallback(()=>{if(r){r();return}const d=Pa(e);d&&i(ns(d))},[e,i,r]);return t.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[u&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:A,title:g,children:[t.jsx(Rt,{size:12}),t.jsx("span",{children:g})]}):t.jsxs("span",{className:"conversation-meta-chip",title:g,children:[t.jsx(Rt,{size:12}),t.jsx("span",{children:g})]})),p&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[t.jsx(dr,{size:12}),t.jsx("span",{children:f})]}),m&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[t.jsx(dr,{size:12}),t.jsx("span",{children:f})]}),l&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:w,title:l,children:[t.jsx(Xt,{size:12}),t.jsx("span",{children:l})]}):t.jsxs("span",{className:"conversation-meta-chip",title:l,children:[t.jsx(Xt,{size:12}),t.jsx("span",{children:l})]}))]})}function _n(e,s){return`${e}:${s}`}function cm(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function _r(e,s){cm()&&console.debug(`[subscription-manager] ${e}`,s)}class lm{constructor(){Ye(this,"active",new Map)}subscribe(s,r,n,a){var p;const i=_n(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 m={daemonId:r,request:n,handlers:new Set([a])};this.active.set(i,m),_r("subscribe",{daemonId:r,topic:n.topic,key:n.key}),l=((p=s.sendData)==null?void 0:p.call(s,r,n))??!1}const u=()=>{var g;const m=this.active.get(i);if(!m||(m.handlers.delete(a),m.handlers.size>0))return;this.active.delete(i);const f={type:"unsubscribe",topic:n.topic,key:n.key};_r("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(g=s.sendData)==null||g.call(s,r,f)};return u.initialSendAccepted=l,u}publish(s){const r=_n(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,Ds.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.publish",topic:s.topic,payload:{key:s.key}}),n.handlers.forEach(a=>{a(s),Ds.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.handler_invoked",topic:s.topic,payload:{key:s.key}})}))}updateParams(s,r,n){const a=_n(s,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(s){var r;_r("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=s.sendData)==null||r.call(s,n.daemonId,n.request)}resubscribeForDaemon(s,r){var a;const n=Array.from(this.active.values()).filter(i=>i.daemonId===s);_r("resubscribe_daemon",{daemonId:s,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 as=new lm;function dm(e,s){const r=new Map;for(const n of e||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===s&&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 um(e){const s=[],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 s.push(n);return{topLevel:s,childrenByParent:r}}function rn(e,s){const r=[],{daemonId:n,existingDaemon:a,existingEntries:i,timestamp:c}=s,l=c||e.timestamp||Date.now(),u=e.sessions||[],{topLevel:p,childrenByParent:m}=um(u),f=dm(i,n),g=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,w=p.filter(b=>b.kind==="workspace"&&b.transport==="cdp-page"),A=p.filter(b=>b.kind==="agent"&&b.transport==="pty"),d=p.filter(b=>b.kind==="agent"&&b.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...g&&{machine:g,platform:g.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(b=>!!b.cdpConnected)});for(const b of w){const y=f.get(b.id),h=tr(b,y),N=(m.get(b.id)||[]).map(_=>tr(_,f.get(_.id)));r.push({id:`${n}:ide:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,status:h.cdpConnected?"online":"detected",daemonId:n,instanceId:b.id,workspace:h.workspace,terminals:0,childSessions:N,agents:N.map(_=>({id:_.id,name:_.providerName||_.providerType,type:_.providerType,status:_.status})),activeChat:h.activeChat,chats:[],cdpConnected:h.cdpConnected,...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},timestamp:l})}for(const b of A){const y=f.get(b.id),h=tr(b,y);r.push({id:`${n}:cli:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,agentType:h.providerType,status:h.status||"running",daemonId:n,instanceId:b.id,cliName:h.providerName||h.providerType,mode:h.mode||(y==null?void 0:y.mode)||"terminal",workspace:h.workspace||"",activeChat:h.activeChat,...h.resume!==void 0&&{resume:h.resume},...h.runtimeKey!==void 0&&{runtimeKey:h.runtimeKey},...h.runtimeDisplayName!==void 0&&{runtimeDisplayName:h.runtimeDisplayName},...h.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:h.runtimeWorkspaceLabel},...h.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:h.runtimeWriteOwner},...h.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:h.runtimeAttachedClients},...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},timestamp:l,_isCli:!0})}for(const b of d){const y=f.get(b.id),h=tr(b,y);r.push({id:`${n}:acp:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,agentType:h.providerType,status:h.status||"running",daemonId:n,instanceId:b.id,cliName:h.providerName||h.providerType,mode:"chat",workspace:h.workspace||"",activeChat:h.activeChat,...h.runtimeKey!==void 0&&{runtimeKey:h.runtimeKey},...h.runtimeDisplayName!==void 0&&{runtimeDisplayName:h.runtimeDisplayName},...h.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:h.runtimeWorkspaceLabel},...h.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:h.runtimeWriteOwner},...h.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:h.runtimeAttachedClients},...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},timestamp:l,_isAcp:!0})}return r}const Rn=new Map,Pn=new Map,Dn=new Set,nr=new Map,mm=1200;function pm(e){if(!e||typeof e!="object")return null;const s=e,r=s.status;if(r&&typeof r=="object")return r;const n=s.result;if(n&&typeof n=="object"&&"status"in n){const a=n.status;if(a&&typeof a=="object")return a}return s}function Po(e,s){const r=nr.get(e);!r||r.size===0||(nr.delete(e),r.forEach(n=>n(s)))}function fm(e,s){return new Promise(r=>{const n=nr.get(e)||new Set;nr.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&nr.delete(e),r(c)},i=setTimeout(()=>a(!1),s);n.add(a)})}function yr(){const{sendCommand:e,sendData:s}=Pt(),{injectEntries:r,getIdes:n}=en();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??6e4,l=Pn.get(a)||0;if(!(i!=null&&i.force)&&Dn.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const u=Rn.get(a);if(u)return u;const p=(async()=>{if(s&&!Dn.has(a)&&(Dn.add(a),as.subscribe({sendData:s},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},d=>{const b=n(),y=b.find(N=>N.id===a),h=rn(d.status,{daemonId:a,existingDaemon:y,existingEntries:b,timestamp:d.timestamp});h.length>0&&r(h),Pn.set(a,Date.now()),Po(a,!0)}),!(i!=null&&i.force)&&await fm(a,mm)))return;const m=await e(a,"get_status_metadata"),f=pm(m);if(!f)return;const g=n(),w=g.find(d=>d.id===a),A=rn(f,{daemonId:a,existingDaemon:w,existingEntries:g,timestamp:f.timestamp||Date.now()});A.length>0&&r(A,{authoritativeDaemonIds:[a]}),Pn.set(a,Date.now()),Po(a,!0)})().finally(()=>{Rn.delete(a)});return Rn.set(a,p),p},[n,r,e,s])}function zt(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}function Da(e,s){if(!e||!s)return!1;if(e===s||e.id&&s.id&&String(e.id)===String(s.id)||e._localId&&s._localId&&String(e._localId)===String(s._localId))return!0;const r=String(e.role||"").toLowerCase(),n=String(s.role||"").toLowerCase();if(r!==n)return!1;const a=$s(e.content),i=$s(s.content);if(!a||!i||!(a===i||pr(a,i)||pr(i,a)))return!1;const l=zt(e),u=zt(s);return l&&u?Math.abs(l-u)<=15e3:!!e._localId!=!!s._localId}function Do(e){let s=0;return e!=null&&e._localId||(s+=4),e!=null&&e.id&&(s+=3),e!=null&&e._turnKey&&(s+=2),zt(e)&&(s+=1),s}function js(e){return $s(e==null?void 0:e.content)}function pr(e,s){if(!e||!s||e.length<=s.length)return!1;const r=Math.max(12,Math.min(80,Math.floor(e.length*.4)));return s.length<r?!1:e.startsWith(s)||e.includes(s)}function hm(e,s){const r=js(e),n=js(s);return!r||!n||r===n?null:pr(r,n)?e:pr(n,r)?s:null}function xm(e,s){const r=hm(e,s);if(r)return r;const n=Do(e),a=Do(s);return a!==n?a>n?s:e:js(s).length>=js(e).length?s:e}function bm(e){return!!e&&!!(e.id||e._localId||e._turnKey)}function ar(e){if(!e)return[];const s=[],r=l=>{l&&s.push(l)};e.id&&r(`id:${String(e.id)}`),e._localId&&r(`local:${String(e._localId)}`),e._turnKey&&r(`turn:${String(e._turnKey)}`);const n=String(e.role||"").toLowerCase(),a=js(e),i=zt(e),c=i?Math.round(i/15e3):0;return n&&a&&(r(`content:${n}:${a}`),r(`preview:${n}:${a.slice(0,120)}:${c}`)),s}function ms(e,s=Da){const r=[],n=new Map,a=(c,l)=>{for(const u of ar(c)){const p=n.get(u);p?p.push(l):n.set(u,[l])}},i=(c,l)=>{for(const u of ar(c)){const p=n.get(u);if(!p)continue;const m=p.filter(f=>f!==l);m.length>0?n.set(u,m):n.delete(u)}};for(const c of e){const l=new Set;for(const m of ar(c)){const f=n.get(m);f&&f.forEach(g=>l.add(g))}const u=l.size>0?Array.from(l).sort((m,f)=>m-f).find(m=>s(r[m],c)):bm(c)?-1:r.findIndex(m=>s(m,c));if(u!==void 0&&u>=0){const m=xm(r[u],c);m!==r[u]&&(i(r[u],u),r.splice(u,1,m),a(m,u));continue}const p=r.length;r.push(c),a(c,p)}return r}function gm(e,s){const r=Array.isArray(e)?e:[],n=Array.isArray(s)?s:[];return r.length===0?n:n.length===0?r:ms([...r,...n])}function Eo(e){return[...e].sort((s,r)=>{const n=zt(s),a=zt(r);return n&&a&&n!==a?n-a:0})}function $o(e,s){const r=e.filter(n=>String((n==null?void 0:n.role)||"").toLowerCase()==="user").slice();return s.filter(n=>{const a=r.findIndex(i=>Da(i,n));return a>=0?(r.splice(a,1),!1):!0})}function ym(e,s,r=Da){const n=new Map,a=i=>{for(const c of ar(i)){const l=n.get(c);l?l.push(i):n.set(c,[i])}};return s.forEach(a),e.filter(i=>{const c=js(i),l=String((i==null?void 0:i.role)||"").toLowerCase(),u=zt(i),p=new Set;for(const f of ar(i)){const g=n.get(f);g&&g.forEach(w=>p.add(w))}return!(p.size>0?Array.from(p):s).some(f=>{if(r(i,f))return!0;const g=String((f==null?void 0:f.role)||"").toLowerCase();if(!c||!l||l!==g)return!1;const w=js(f);if(!pr(w,c)&&w!==c)return!1;const A=zt(f);return u&&A?Math.abs(u-A)<=15e3:!0})})}function Rs(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:tt(e)||Ze(e)?{agentType:Bt(e)}:e.streamSource==="agent-stream"?{agentType:Bt(e)}:s}function fr(e){return e?gr(e):""}function Xs(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function Ea(e){if(!e)return null;if(Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return"Resolve the pending approval prompt before sending another message.";switch(e.status){case"waiting_approval":case"waiting_for_user_input":return"Resolve the pending approval prompt before sending another message.";default:return null}}function vm(e){const s=e instanceof Error?e.message:String(e||""),r=s.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.":s||"Unable to send message right now."}const wm=60,jm=1e3;function uc(e={}){return e.isCliLike?jm:wm}function km(e={}){return uc(e)}const vr=60,$a=12e4,Sm=new Set(["generating","waiting_approval","starting","streaming","working"]),Ko=new Map;function mc(e,s){return`${e}::${s}`}function la(e=vr){return{liveMessages:[],cursor:fc([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function pc(e){return _i(e)}function fc(e,s=vr){return{knownMessageCount:e.length,lastMessageSignature:pc(e[e.length-1]),tailLimit:s}}function Rr(e,s){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 Nm(e,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return e;case"append":return ms([...e,...r]);case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??e.length),e.length));return ms([...e.slice(0,n),...r])}case"full":{const n=Math.max(Number(s.totalMessages||0),r.length);if(n>r.length&&e.length>r.length){const a=Math.max(0,n-r.length);return ms([...e.slice(0,a),...r])}return r}default:return r}}class Cm{constructor(s){Ye(this,"manager");Ye(this,"sendData");Ye(this,"daemonId");Ye(this,"sessionId");Ye(this,"historySessionId");Ye(this,"subscriptionKey");Ye(this,"snapshot");Ye(this,"transportSubscription",null);Ye(this,"listeners",new Set);Ye(this,"retainCount",0);Ye(this,"loadHistoryPromise",null);Ye(this,"pendingDisconnectTimer",null);this.manager=s.manager||as,this.sendData=s.sendData,this.daemonId=s.daemonId,this.sessionId=s.sessionId,this.historySessionId=s.historySessionId,this.subscriptionKey=s.subscriptionKey,this.snapshot=la(Math.max(0,s.tailLimit??vr))}updateOptions(s){if(s.manager&&(this.manager=s.manager),s.sendData&&(this.sendData=s.sendData),s.historySessionId&&(this.historySessionId=s.historySessionId),s.tailLimit!==void 0){const r=Math.max(0,s.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(s){const r=Array.isArray(s)?s:[];if(r.length===0)return;const n=ms([...r,...this.snapshot.liveMessages]);if(n.length<r.length)return;const a=fc(n,this.snapshot.cursor.tailLimit);Rr(this.snapshot.liveMessages)===Rr(n)&&this.snapshot.cursor.knownMessageCount===a.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===a.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:n,cursor:a})}subscribe(s){return this.listeners.add(s),s(this.snapshot),()=>{this.listeners.delete(s)}}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(s){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=await s(),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}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,{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}:{}}},s=>{this.handleUpdate(s)}))}disconnect(){var s;(s=this.transportSubscription)==null||s.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(s=>s(this.snapshot))}handleUpdate(s){const r=Nm(this.snapshot.liveMessages,s),n={knownMessageCount:r.length,lastMessageSignature:typeof s.lastMessageSignature=="string"?s.lastMessageSignature:pc(r[r.length-1]),tailLimit:this.snapshot.cursor.tailLimit};Rr(this.snapshot.liveMessages)===Rr(r)&&this.snapshot.cursor.knownMessageCount===n.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===n.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:r,cursor:n},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:n.knownMessageCount,lastMessageSignature:n.lastMessageSignature}),this.emit())}}function hc(e){const s=mc(e.daemonId,e.sessionId),r=Ko.get(s);if(r)return r.updateOptions(e),r;const n=new Cm(e);return Ko.set(s,n),n}function Im(e,s){return{...e,loadHistoryPage:s}}function Am(e,s){return e.subscriptionKey.localeCompare(s.subscriptionKey)||e.daemonId.localeCompare(s.daemonId)||e.sessionId.localeCompare(s.sessionId)||e.historySessionId.localeCompare(s.historySessionId)}function Mm(e,s={}){const r=String(e.status||"").trim().toLowerCase();if(Sm.has(r)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const n=s.now??Date.now(),a=Math.max(0,Number(s.recentActivityMs??$a)),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 Tm(e=$a){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Lm(e,s={}){const r=new Set,n=[];for(const a of e){if(!Mm(a,s))continue;const i=gr(a),c=a.sessionId||"";if(!i||!c)continue;const l=mc(i,c);if(r.has(l))continue;r.add(l);const u=br(a);n.push({daemonId:i,sessionId:c,historySessionId:u||c,subscriptionKey:`daemon:${i}:session:${c}`})}return n.sort(Am),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function _m(e,s){const{sendData:r,sendCommand:n}=Pt(),a=(s==null?void 0:s.enabled)!==!1,i=gr(e),c=e.sessionId||"",l=br(e)||c,u=`daemon:${i}:session:${c}`,p=Math.max(0,(s==null?void 0:s.tailLimit)??vr),m=o.useMemo(()=>!a||!i||!c?null:hc({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:u,sendData:r,tailLimit:p}),[i,a,l,r,c,u,p]),[f,g]=o.useState(()=>(m==null?void 0:m.getSnapshot())||la(p));o.useEffect(()=>{if(!m){g(la(p));return}m.retain(),g(m.getSnapshot());const A=m.subscribe(d=>{g(d)});return()=>{A(),m.release()}},[m,p]),o.useEffect(()=>{m&&(m.hydrateLiveMessages(e.messages),g(m.getSnapshot()))},[e.messages,m]);const w=o.useCallback(async()=>{!m||!i||!c||await m.loadHistoryPage(async()=>{const A=e.agentType,d=await n(i,"chat_history",{agentType:A,offset:m.getSnapshot().historyOffset,limit:30,targetSessionId:c,historySessionId:l}),b=d&&typeof d=="object"&&"result"in d?d.result||{}:d||{};return{messages:Array.isArray(b.messages)?b.messages:[],hasMore:b.hasMore===!0}})},[e.agentType,m,i,l,n,c]);return o.useMemo(()=>Im(f,w),[w,f])}function Rm(e,s){const{sendData:r}=Pt(),n=(s==null?void 0:s.enabled)!==!1,a=Math.max(0,(s==null?void 0:s.tailLimit)??vr),i=Math.max(0,Number((s==null?void 0:s.recentActivityMs)??$a)),c=Tm(i),[l,u]=o.useState(0);o.useEffect(()=>{if(!n||e.length===0)return;const m=setInterval(()=>{u(f=>f+1)},c);return()=>{clearInterval(m)}},[e.length,n,c]);const p=o.useMemo(()=>Lm(e,{recentActivityMs:i}),[e,i,l]);o.useEffect(()=>{if(!n||!r||p.descriptors.length===0)return;const m=p.descriptors.map(f=>hc({...f,sendData:r,tailLimit:a}));return m.forEach(f=>f.retain()),()=>{m.forEach(f=>f.release())}},[p.signature,n,r,a])}function Pm(e,s){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(s)}function Dm(e){return Pm(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const Em=60;function da({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:l,userName:u,showMetaChips:p=!1,scrollToBottomRequestNonce:m,isInputActive:f=!0}){var ie,Se,X,fe,we;const g=o.useRef(new Map),w=yr();xr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const A=at.useMemo(()=>zs(e),[e.status,e.connectionState]),d=o.useMemo(()=>nm(e,s),[e,s]),b=o.useMemo(()=>{var ce;return _a((ce=d.targetEntry)==null?void 0:ce.providerControls,{hostIdeType:e.hostIdeType,providerType:d.providerType})},[e.hostIdeType,d.providerType,(ie=d.targetEntry)==null?void 0:ie.providerControls]),y=uc({isCliLike:d.isCli||d.isAcp}),h=km({isCliLike:d.isCli||d.isAcp}),N=_m(e,{enabled:!!e.sessionId,tailLimit:h}),[_,k]=o.useState(y),I=e.tabKey,j=N.historyMessages,v=N.hasMoreHistory,x=N.historyError,E=gm(N.liveMessages,e.messages);o.useEffect(()=>{k(y)},[y,I]);const T=Math.max(0,E.length-_),L=Ra(e),M=gr(e),W=Dm(e),U=Ea(e),C=a||U,R=!!U,[B,S]=o.useState(!1);o.useEffect(()=>{const ce=d.targetEntry;M&&(!ce||ce.providerControls===void 0||ce.controlValues===void 0)&&w(M,{minFreshMs:3e4}).catch(()=>{})},[M,d.isAcp,(Se=d.targetEntry)==null?void 0:Se.providerControls,(X=d.targetEntry)==null?void 0:X.controlValues,w]);const D=o.useCallback(async()=>{if(!B){if(E.length>_){k(ce=>Math.min(E.length,ce+Em));return}S(!0);try{await N.loadHistoryPage()}finally{S(!1)}}},[N,B,E.length,_]),{allMessages:Y,receivedAtMap:q}=o.useMemo(()=>{const ce=T>0?E.slice(-_):E;if(j.length===0){const ge=Eo(ms(ce)),ae={};return ge.forEach((oe,ee)=>{const ue=`${e.tabKey}:${Ms(oe,ee)}`;let se=zt(oe)||g.current.get(ue)||0;se||(se=Date.now(),g.current.set(ue,se)),ae[Ms(oe,ee)]=se}),{allMessages:ge,receivedAtMap:ae}}const he=ym(j,ce),de=Eo(ms([...he,...ce])),z={};return de.forEach((ge,ae)=>{const oe=`${e.tabKey}:${Ms(ge,ae)}`;let ee=zt(ge)||g.current.get(oe)||0;ee||(ee=Date.now(),g.current.set(oe,ee)),z[Ms(ge,ae)]=ee}),{allMessages:de,receivedAtMap:z}},[e.tabKey,T,j,E,_]),H=o.useMemo(()=>l.filter(ce=>ce.routeId===e.tabKey).sort((ce,he)=>ce.timestamp-he.timestamp),[l,e.tabKey]),re=o.useMemo(()=>{if(E.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[t.jsx("div",{className:"connecting-logo-float",children:t.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:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),t.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[t.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",t.jsx("span",{className:"connecting-dots"})]}),t.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((A.isGenerating||e.status==="streaming")&&S(!1),e.status==="not_monitored"&&W)return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-3xl opacity-60",children:t.jsx(dr,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),t.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Switching...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Es,{size:14})," Open ",L," Panel"]})}),t.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&W)return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-3xl opacity-60",children:t.jsx(Ei,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),t.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Opening...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Es,{size:14})," Open ",L," Panel"]})}),t.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 t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),t.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,W,i,c,B,E.length,L,A.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[p&&t.jsx(dc,{conversation:e,className:"chat-pane-meta-row"}),t.jsx(Qd,{messages:Y,actionLogs:H,agentName:Ws(e)||L||"Agent",userName:u,isCliMode:d.isCli||d.isAcp,isWorking:A.isGenerating,contextKey:e.tabKey,receivedAtMap:q,onLoadMore:D,isLoadingMore:B,hasMoreHistory:v,hiddenLiveCount:T,loadError:x??void 0,emptyState:re,scrollToBottomRequestNonce:m}),t.jsx(Ju,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:d.providerType,displayLabel:d.displayLabel,controls:(fe=d.targetEntry)==null?void 0:fe.providerControls,controlValues:(we=d.targetEntry)==null?void 0:we.controlValues,isActive:f,isCliTerminal:d.isCliTerminal}),!d.isCliTerminal&&t.jsx(Zu,{contextKey:e.tabKey,panelLabel:L,isSending:n,isBusy:R,statusMessage:C,onSend:r,isActive:f,showControlsToggle:b.length>0})]})}let xc=ys;function bc(){return xc()}class $m{constructor(){Ye(this,"listeners",new Map)}send(s){}isConnected(){return!1}on(s,r){return this.listeners.has(s)||this.listeners.set(s,new Set),this.listeners.get(s).add(r),()=>{var n;(n=this.listeners.get(s))==null||n.delete(r)}}emit(s,...r){var n;(n=this.listeners.get(s))==null||n.forEach(a=>a(...r))}}let gc=new $m;class Km{sendPtyInput(s,r,n){return!1}retryConnection(s){}getState(s){return"disconnected"}sendData(s,r){return!1}get(s){}onScreenshot(s,r){return()=>{}}onRuntimeEvent(s,r){return()=>{}}requestRuntimeSnapshot(s,r){return Promise.resolve()}}let ft=new Km;function Bm(e){e.dashboardWS&&(gc=e.dashboardWS),e.connectionManager&&(ft=e.connectionManager),e.useDaemonsHook&&(xc=e.useDaemonsHook)}const yc=.6,Wm=1.15;function Om(e,s={}){const r=typeof s.minScale=="number"?s.minScale:yc;return!Number.isFinite(e)||e<=0?1:e<=480?r:1}function lt(e){return Ra(e)}function ks(e){return ac(e).join(" · ")}function vc(e){if(e.lastMessagePreview)return e.lastMessagePreview;const s=[...e.messages].reverse().find(n=>!(n!=null&&n._localId))||e.messages[e.messages.length-1],r=$s(s==null?void 0:s.content);return r||(e.title?e.title:ks(e)||"No messages yet")}function wc(e,s){const{isReconnecting:r,isConnecting:n}=zs(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function Hm(e,s){const r=["Chat",...ac(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function ps(e){return wc(e)||ks(e)}function Um(e){return`${lt(e)} · ${vc(e)}`}function Fm(e){const s=sn(e),r=s?ot(s):Ws(e);return`${lt(e)} — ${r||"Agent"}`}function zm(e){return Ws(e)||"CLI"}function jc(e){return nc(e)}function kc(e){return e?`Remote · ${lt(e)||e.workspaceName||"Session"}`:"Remote"}function Vm({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0}){var q;const{ides:l}=ys(),u=o.useRef(null),{sendData:p}=Pt(),[m,f]=o.useState(""),[g,w]=o.useState(!1),[A,d]=o.useState(1),b=o.useRef(!1),y=o.useRef(0),h=o.useRef(!1),N=o.useRef(""),_=o.useRef(null),k=o.useRef(!1),I=o.useRef(null),j=e.tabKey,v=e.sessionId||"",x=e.daemonId||((q=e.routeId)==null?void 0:q.split(":")[0])||e.routeId||"",E=l.find(H=>H.id===x&&H.type==="adhdev-daemon"),T=(E==null?void 0:E.terminalSizingMode)==="fit"?"fit":"measured",L=Ea(e),M=i||L,W=yc,U=Wm,C=()=>typeof window>"u"?1:Om(window.innerWidth||0,{minScale:W}),R=()=>{var H,re;y.current=0,h.current=!1,N.current="",_.current=null,k.current=!1,I.current!==null&&(cancelAnimationFrame(I.current),I.current=null),w(!1),(re=(H=r.current)==null?void 0:H.reset)==null||re.call(H)},B=()=>{var H,re;y.current=0,h.current=!1,N.current="",_.current=null,k.current=!1,I.current!==null&&(cancelAnimationFrame(I.current),I.current=null),w(!0),(re=(H=r.current)==null?void 0:H.reset)==null||re.call(H)},S=()=>{var re;if(I.current=null,!c)return;const H=N.current;H&&(N.current="",(re=r.current)==null||re.write(H))},D=H=>{H&&(N.current+=H,c&&I.current===null&&(I.current=requestAnimationFrame(S)))},Y=(H,re=0,ie,Se)=>{var X,fe,we,ce,he;re>0&&y.current>=re||re===0&&h.current||(y.current=re,w(!0),typeof ie=="number"&&typeof Se=="number"&&ie>0&&Se>0&&((fe=(X=r.current)==null?void 0:X.resize)==null||fe.call(X,ie,Se)),(ce=(we=r.current)==null?void 0:we.reset)==null||ce.call(we),H&&((he=r.current)==null||he.write(H)))};return o.useEffect(()=>{R()},[v]),o.useEffect(()=>{var re;if(!v)return;const H=((re=ft.onRuntimeEvent)==null?void 0:re.call(ft,v,ie=>{if(!(!ie||ie.sessionId!==v)){if(ie.type==="runtime_snapshot"){if(!c){_.current={text:ie.text||"",seq:ie.seq||0,cols:ie.cols,rows:ie.rows};return}Y(ie.text||"",ie.seq||0,ie.cols,ie.rows);return}if(ie.type==="session_output"){h.current=!0,typeof ie.seq=="number"&&(y.current=Math.max(y.current,ie.seq)),g||w(!0),typeof ie.data=="string"&&D(ie.data);return}if(ie.type==="session_cleared"){if(!c){k.current=!0,N.current="",_.current=null;return}B()}}}))||(()=>{});return()=>{H()}},[x,v,r,c,g]),o.useEffect(()=>{var re,ie,Se;if(!v)return;x&&((re=ft.getState)==null?void 0:re.call(ft,x))==="connected"&&(w(!0),(ie=ft.requestRuntimeSnapshot)==null||ie.call(ft,x,v).catch(()=>{}));const H=(Se=ft.onStateChange)==null?void 0:Se.call(ft,(X,fe)=>{var we;X!==x||fe!=="connected"||(w(!0),(we=ft.requestRuntimeSnapshot)==null||we.call(ft,x,v).catch(()=>{}))});return()=>{H==null||H()}},[x,v,r]),o.useEffect(()=>{s&&R()},[s,j,r]),o.useEffect(()=>{f("")},[e.tabKey]),o.useEffect(()=>{const H=()=>{b.current||d(C())};return H(),window.addEventListener("resize",H),()=>window.removeEventListener("resize",H)},[]),o.useEffect(()=>{var re;if(!c){(re=u.current)==null||re.blur();return}k.current&&(k.current=!1,B());const H=_.current;H&&(_.current=null,Y(H.text,H.seq,H.cols,H.rows)),N.current&&I.current===null&&(I.current=requestAnimationFrame(S)),requestAnimationFrame(()=>{var ie;(ie=r.current)==null||ie.bumpResize()})},[c]),o.useEffect(()=>()=>{I.current!==null&&(cancelAnimationFrame(I.current),I.current=null)},[]),o.useEffect(()=>{const H=re=>{var Se;const ie=re.detail;ie!=null&&ie.sessionId&&ie.sessionId!==v||g&&((Se=r.current)==null||Se.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",H),()=>{window.removeEventListener("adhdev:fit-cli-terminal",H)}},[g,v,r]),t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[t.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[t.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:()=>{b.current=!0,d(H=>Math.max(W,Number((H-.1).toFixed(2))))},title:"Shrink terminal viewport",children:"-"}),t.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:()=>{b.current=!0,d(H=>Math.min(U,Number((H+.1).toFixed(2))))},title:"Increase terminal viewport",children:"+"})]}),t.jsx("div",{className:"w-full h-full overflow-x-auto overflow-y-hidden rounded-lg overscroll-contain",children:t.jsx("div",{style:{width:`${100/A}%`,height:`${100/A}%`,transform:`scale(${A})`,transformOrigin:"top left"},children:t.jsx(Oi,{ref:r,readOnly:!g||!c,sizingMode:T,onInput:H=>{g&&(p==null||p(x,{type:"pty_input",sessionId:v,targetSessionId:v,data:H}))}})})}),!g&&t.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:"Runtime terminal unavailable"})]}),t.jsxs("div",{className:"px-3 py-2 bg-[var(--surface-primary)] border-t border-border-subtle shrink-0",children:[t.jsxs("div",{className:"flex gap-2.5 items-center",children:[t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:u,type:"text",placeholder:M||`Send message to ${lt(e)}...`,value:m,disabled:!g||!c,onChange:H=>f(H.target.value),onPaste:H=>{const re=H.clipboardData.getData("text");re&&f(ie=>ie+re),H.preventDefault()},onKeyDown:H=>{if(H.key!=="Enter")return;if(H.nativeEvent.isComposing){H.preventDefault();return}H.preventDefault();const re=m.trim();!g||!re||L||n(re).then(ie=>{ie!==!1&&f("")})},className:"w-full h-9 rounded-[18px] px-4 bg-bg-secondary text-[13px] text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),t.jsx("button",{onClick:()=>{const H=m.trim();!g||!H||L||n(H).then(re=>{re!==!1&&f("")})},disabled:!g||!c||tc({hasDraft:!!m.trim(),isBusy:!!L}),className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${m.trim()&&!L?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:m.trim()&&!L?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:m.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),M&&t.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:M})]})]})}function Gm({wsStatus:e,showReconnected:s,loginUrl:r}){const n=e==="disconnected"||e==="reconnecting"||e==="offline"||e==="auth_failed",a=e==="auth_failed"?"red":e==="offline"?"orange":"accent",i={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))"},c={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)"},l={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"};return t.jsxs(t.Fragment,{children:[n&&t.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5 justify-center",style:{background:i[a],borderBottom:c[a],color:l[a]},children:[t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5",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}}),e==="offline"&&"Network offline — waiting for connection...",e==="disconnected"&&"Reconnecting to server...",e==="reconnecting"&&"Reconnecting to server...",e==="auth_failed"&&(r?t.jsxs(t.Fragment,{children:["Session expired."," ",t.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — please restart the server.")]}),s&&e==="connected"&&t.jsxs("div",{className:"py-2 px-4 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-b border-green-500/15 animate-[fadeIn_0.3s_ease]",children:[t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})]})}function qm({terminalBackend:e,isStandalone:s=!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]),!s||!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 t.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:[t.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[t.jsxs("span",{children:[l," is using `xterm` fallback."]}),t.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),t.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 Ka({mode:e,onChange:s,compact:r=!1}){const n=r?14:15;return t.jsx("button",{type:"button",onClick:()=>s(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:e==="chat"?"Switch to Terminal view":"Switch to Chat view",children:e==="chat"?t.jsx(un,{size:n}):t.jsx(Qt,{size:n})})}function Bo({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Wo({notification:e,shortcutIndex:s,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=pn(e.updatedAt),l=!e.readAt;return t.jsxs("div",{className:`dashboard-header-inbox-item ${l?"is-attention":""}`.trim(),children:[t.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[s?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",s]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",c].filter(Boolean).join(" · ")]}),e.preview?t.jsx("span",{className:"dashboard-header-inbox-item-meta",children:e.preview}):null]}),t.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[l?t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),n()},children:"Mark read"}):t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),a()},children:"Mark unread"}),t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),i()},children:"Delete"})]})]})}function Ym({activeConv:e,agentCount:s,wsStatus:r,isConnected:n,conversations:a,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:u,onSetCliViewMode:p,onHideConversation:m,hiddenConversations:f=[],onShowConversation:g,onShowAllHidden:w,onResetPanelsToMain:A,inboxOpen:d,onInboxOpenChange:b,hiddenOpen:y,onHiddenOpenChange:h,onOpenNewSession:N,actionShortcuts:_,notifications:k,notificationUnreadCount:I,onOpenNotification:j,onMarkNotificationRead:v,onMarkNotificationUnread:x,onDeleteNotification:E}){const{ides:T,p2pStates:L={}}=ys(),M=!!e&&tt(e)&&!Ze(e),W=!!e&&Ze(e),U=u||(e?sc(e)?"terminal":"chat":null),[C,R]=o.useState(!1),B=o.useRef(null),S=o.useRef(null),D=n?"#22c55e":r==="connected"?"#eab308":"#ef4444",Y=n?"0 0 4px #22c55e80":r==="connected"?"0 0 4px #eab30880":"0 0 4px #ef444480",q=T.filter(z=>z.type==="adhdev-daemon"),H=Object.values(L),re=H.filter(z=>z==="connected").length,ie=H.filter(z=>z==="connecting"||z==="new"||z==="checking").length,X=r!=="connected"||q.length===0?null:ie>0&&re===0?"P2P connecting...":re>0&&s===0?"Waiting for IDE...":null,fe=o.useMemo(()=>k.filter(z=>!z.readAt),[k]),we=o.useMemo(()=>k.filter(z=>!!z.readAt),[k]),ce=o.useMemo(()=>fe.slice(0,9),[fe]),he=I;o.useEffect(()=>{if(!d)return;const z=ge=>{var ae;(ae=B.current)!=null&&ae.contains(ge.target)||b(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[d,b]),o.useEffect(()=>{if(!y)return;const z=ge=>{var ae;(ae=S.current)!=null&&ae.contains(ge.target)||h(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[y,h]),o.useEffect(()=>{if(!y&&!d)return;const z=ge=>{if(!ge.altKey)return;const ae=ge.code.match(/^Digit([1-9])$/);if(!ae)return;const oe=Number(ae[1])-1,ee=y?f[oe]:void 0,ue=d?ce[oe]:void 0;if(!(!ee&&!ue)){if(ge.preventDefault(),ge.stopPropagation(),ee){g==null||g(ee),h(!1);return}ue&&(j(ue),b(!1))}};return window.addEventListener("keydown",z,!0),()=>window.removeEventListener("keydown",z,!0)},[f,y,d,ce,h,b,j,g]);const de=z=>{if(!z)return;const ge=a.find(ae=>ae.tabKey===z);ge&&(m==null||m(ge))};return t.jsxs("div",{className:"dashboard-header",children:[t.jsx("div",{className:"flex items-center gap-3",children:t.jsx("div",{className:"header-title-block",children:t.jsxs("div",{className:"header-title-row",children:[t.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[t.jsx(Qt,{size:18}),t.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),t.jsx("span",{className:"header-title-mobile",children:e?lt(e):"Dashboard"}),t.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:t.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:D,boxShadow:Y}})})]}),t.jsxs("div",{className:"header-subtitle flex items-center",children:[t.jsx("span",{title:n?"Connected":r==="connected"?"Partial":"Disconnected",className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:D,boxShadow:Y}}),X&&t.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",X]}),N&&t.jsx("button",{type:"button",onClick:N,className:"btn btn-secondary btn-sm ml-2",title:"Start or recover a session","aria-label":"Start or recover a session",children:t.jsx(Ad,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(M||W||!Ze(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:ks(e)||lt(e),children:lt(e)}),(M||W)&&l&&t.jsxs(t.Fragment,{children:[M&&p&&U&&t.jsx(Ka,{mode:U,onChange:p,compact:!0}),t.jsx("button",{onClick:()=>l(e),className:"btn btn-secondary btn-sm",title:W?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:t.jsx(At,{size:14})})]}),!Ze(e)&&t.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:t.jsx(Sa,{size:14})}),!M&&!Ze(e)&&t.jsx("button",{onClick:c,className:"btn btn-secondary btn-sm",title:"Remote Control",children:t.jsx(Rt,{size:14})})]}),t.jsxs("div",{className:"dashboard-header-inbox",ref:B,children:[t.jsxs("div",{className:`dashboard-header-hidden${C?" is-drop-target":""}`,ref:S,onDragEnter:z=>{z.dataTransfer.types.includes("text/tab-key")&&(z.preventDefault(),R(!0))},onDragOver:z=>{z.dataTransfer.types.includes("text/tab-key")&&(z.preventDefault(),z.dataTransfer.dropEffect="move",R(!0))},onDragLeave:z=>{z.currentTarget.contains(z.relatedTarget)||R(!1)},onDrop:z=>{const ge=z.dataTransfer.getData("text/tab-key");z.preventDefault(),R(!1),de(ge)},children:[t.jsxs("button",{type:"button",onClick:()=>h(!y),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${_!=null&&_.toggleHiddenTabs?` (${_.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[t.jsx($i,{size:16}),f.length>0&&t.jsx("span",{className:"dashboard-header-hidden-badge",children:f.length})]}),y&&t.jsxs("div",{className:"dashboard-header-hidden-popover",children:[t.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[t.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),t.jsx(Bo,{value:_==null?void 0:_.toggleHiddenTabs})]}),t.jsxs("div",{className:"dashboard-header-hidden-actions",children:[A&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:A,children:"Reset panels"}),f.length>0&&w&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{w(),h(!1)},children:"Restore all"})]})]}),e&&m&&t.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>m(e),children:[t.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[t.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),t.jsx(Bo,{value:_==null?void 0:_.hideCurrentTab})]}),t.jsx("span",{className:"dashboard-header-hidden-current-title",children:lt(e)})]}),f.length>0?t.jsx("div",{className:"dashboard-header-hidden-list",children:f.map(z=>t.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{g==null||g(z),h(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:lt(z)}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[f.indexOf(z)<9?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",f.indexOf(z)+1]}):null,ks(z)]})]},z.tabKey))}):t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),t.jsxs("button",{type:"button",onClick:()=>b(!d),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[t.jsx(mn,{size:16}),he>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:he})]}),d&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[fe.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),fe.map(z=>t.jsx(Wo,{notification:z,shortcutIndex:ce.indexOf(z)>=0?ce.indexOf(z)+1:void 0,onOpen:()=>j(z),onMarkRead:()=>v(z.id),onMarkUnread:()=>x(z.id),onDelete:()=>E(z.id)},z.id))]}),we.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),we.map(z=>t.jsx(Wo,{notification:z,onOpen:()=>j(z),onMarkRead:()=>v(z.id),onMarkUnread:()=>x(z.id),onDelete:()=>E(z.id)},z.id))]}),k.length===0&&t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function jt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function Xm(e,s){return String(e||"")!==String(s||"")}function Qm(e,s={}){const r=String(s.textQuery||"").trim().toLowerCase(),n=String(s.workspaceQuery||"").trim().toLowerCase(),a=String(s.modelQuery||"").trim().toLowerCase(),i=!!s.resumableOnly;return!r&&!n&&!a&&!i?e:e.filter(c=>!(i&&!c.canResume||r&&![c.title,c.preview].map(u=>String(u||"").toLowerCase()).join(`
31
31
  `).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!Xi(c.summaryMetadata).map(u=>u.toLowerCase()).join(`
32
- `).includes(a)))}function Jm(e,s="recent"){const r=e.slice();return r.sort((n,a)=>{if(s==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(s==="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 Sc(e,s={}){return Jm(Qm(e,s),s.sortMode||"recent")}function nn(e){return e?"Resume saved history":"Start fresh"}function Ba(e){return e?"Resuming saved history…":"Starting fresh…"}function Zm(){return"Start fresh"}function Nc(e,s=!1){return e==="cli"?nn(s):e==="ide"?"Start IDE":"Start ACP session"}function Cc(e,s=!1){return e==="cli"?Ba(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function ep(){return"Recover hosted runtime"}function tp(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function sp(){return"Open saved history"}function rp(){return"Saved History"}function Wa(){return"Use saved history when you want continuity in the same provider conversation."}function np(){return"No saved history found yet."}function ap(){return"Refresh saved history"}function op(){return"Refreshing saved history…"}function fs(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function hs(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 Os(e){return e==="start-fresh"?"Start fresh":"Restart"}function Hs(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Oa(e){return`Resume saved history with ${e}?`}function Ha(){return"Review or change the target workspace before resuming saved history."}function ip(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 Ua({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:u,onClose:p,onNewChat:m,onSwitchSession:f,onRefreshHistory:g,onResumeSavedSession:w}){var v;const A=s.find(x=>x.id===e.routeId),d=(A==null?void 0:A.chats)||[],b=(v=A==null?void 0:A.activeChat)==null?void 0:v.id,y=tt(e)&&!Ze(e),[h,N]=o.useState(()=>jt()),_=l||h,k=x=>{if(u){u(x);return}N(x)},I=o.useMemo(()=>Sc(a,{textQuery:_.textQuery,workspaceQuery:_.workspaceQuery,modelQuery:_.modelQuery,resumableOnly:_.resumableOnly,sortMode:_.sortMode}),[_.modelQuery,_.resumableOnly,_.sortMode,_.textQuery,_.workspaceQuery,a]),j=t.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:[t.jsx("div",{onClick:p,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),t.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:[t.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:[t.jsxs("div",{children:[t.jsx("h3",{className:"m-0 text-lg font-extrabold",children:y?rp():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Fm(e)}),y&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Wa()})]}),t.jsx("button",{onClick:p,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:t.jsx(At,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!y&&t.jsx("button",{onClick:m,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"}),y?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[t.jsx("input",{type:"text",value:_.textQuery,onChange:x=>k({..._,textQuery:x.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"}),t.jsx("input",{type:"text",value:_.workspaceQuery,onChange:x=>k({..._,workspaceQuery:x.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"}),t.jsx("input",{type:"text",value:_.modelQuery,onChange:x=>k({..._,modelQuery:x.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"}),t.jsxs("select",{value:_.sortMode,onChange:x=>k({..._,sortMode:x.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[t.jsx("option",{value:"recent",children:"Most recent"}),t.jsx("option",{value:"oldest",children:"Oldest first"}),t.jsx("option",{value:"messages",children:"Most messages"})]})]}),t.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsx("input",{type:"checkbox",checked:_.resumableOnly,onChange:x=>k({..._,resumableOnly:x.target.checked})}),"Resume-ready only"]})]}),I.map(x=>{const E=e.providerSessionId===x.providerSessionId,T=E||!x.canResume||!!c;return t.jsxs("button",{type:"button",onClick:()=>{T||!w||w(x)},disabled:T,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${E?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${T?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:`font-bold text-sm mb-1 truncate ${E?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:x.title||"Untitled Session"}),t.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:x.providerSessionId})]}),t.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:ip(x.lastMessageAt)})]}),t.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:x.preview||"No saved preview yet"}),t.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[t.jsxs("div",{className:"truncate",children:[x.workspace||"Workspace unknown",ws(x.summaryMetadata)?` · ${ws(x.summaryMetadata)}`:"",x.messageCount>0?` · ${x.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:E?"ACTIVE":x.canResume?c===x.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},x.id)})]}):d.map(x=>t.jsxs("div",{onClick:()=>{f(e.routeId,x.id),p()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===x.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[t.jsx("div",{className:`font-bold text-sm mb-1 ${b===x.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:x.title||"Untitled Session"}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[x.id.substring(0,12),"..."]}),b===x.id&&t.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},x.id)),(y&&!i&&I.length===0||!y&&d.length===0)&&t.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[t.jsx("div",{className:"text-3xl mb-3 opacity-60",children:t.jsx(_d,{size:32})}),t.jsx("div",{className:"text-[13px]",children:y?a.length>0?"No saved history matches these filters.":np():"No recent chat sessions found."})]}),y&&i&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:op()})})]}),t.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:t.jsx("button",{onClick:g,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Fs,{size:13})," ",y?ap():"Refresh History"]})})})]})]});return typeof document>"u"?j:lr.createPortal(j,document.body)}const Oo={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 Ic({toasts:e,onDismiss:s,onClickToast:r}){return t.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=Oo[n.type]||Oo.info;return t.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:[t.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))`}}),t.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(),s(n.id)},"aria-label":"Dismiss",children:t.jsx(At,{size:14})}),t.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[t.jsx("div",{className:"flex items-center gap-2 pr-8",children:t.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})}),t.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&t.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((i,c)=>t.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(),s(n.id)},children:i.label},c))})]})]},n.id)})})}const cp=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function lp(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function dp(e){return e.sessionId||e.instanceId||e.agentType}function En(e,s){return e||s}function Ho(e,s){const r=new Set,n=[];for(const a of s)if(a)for(const i of e[a]||[]){const c=i._localId||`${i.role}:${i.timestamp}:${i.content}`;r.has(c)||(r.add(c),n.push(i))}return n.sort((a,i)=>a.timestamp-i.timestamp)}function Ac(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=_t(r,{fallbackId:r.id}));return s}function Mc(e,s={}){var n,a;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((a=s.machineNames)==null?void 0:a[e.daemonId])||void 0,connectionState:s.connectionStates?s.connectionStates[r]||s.defaultConnectionState||"new":s.defaultConnectionState}}function Fa(e,s,r={}){return up(e,s,Mc(e,r))}function up(e,s,r={}){var f,g,w,A,d,b;const n=[],a=r.machineName,i=r.connectionState,c=lp(e),l=bu(e.type,{agentName:e.cliName}),u=tt(e)||Ze(e)?l:ot(e.type),p=Array.isArray(e.childSessions)?e.childSessions.map(y=>{var h,N;return{sessionId:y.id,instanceId:y.id,providerSessionId:y.providerSessionId,transport:y.transport,sessionCapabilities:y.capabilities,agentType:y.providerType,agentName:y.providerName||ot(y.providerType),status:y.status,title:y.title,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,messages:((h=y.activeChat)==null?void 0:h.messages)||[],activeModal:((N=y.activeChat)==null?void 0:N.activeModal)||void 0,unread:y.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,inboxBucket:y.inboxBucket,surfaceHidden:y.surfaceHidden}}):[],m=cp(e);if(m){const y=e.sessionId||e.instanceId,h=l,N=(f=e.activeChat)==null?void 0:f.activeModal,_=N&&Array.isArray(N.buttons)&&N.buttons.length>0,k=Ct((g=e.activeChat)==null?void 0:g.status,{activeModal:(w=e.activeChat)==null?void 0:w.activeModal})||Ct((d=(A=e.agents)==null?void 0:A[0])==null?void 0:d.status)||"idle",I=e.activeChat||{title:"",messages:[]};let j=I.title&&String(I.title).trim()?String(I.title).trim():"";const v=(b=e.activeChat)==null?void 0:b.id,x=e.chats;if(v&&Array.isArray(x)&&x.length>0){const U=x.find(C=>C.id===v||C.id&&String(C.id)===String(v));U!=null&&U.title&&String(U.title).trim()&&(j=String(U.title).trim())}const E=(tt(e)||Ze(e),e.type),T=(tt(e)||Ze(e))&&To(j,h,E)?"":j,L=I.messages||[],M=Ho(s,[e.id,y]),W=$o(L,M);n.push({routeId:e.id,sessionId:y,providerSessionId:e.providerSessionId,nativeSessionId:y,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:tt(e)?e.mode||"terminal":"chat",agentName:h,agentType:E,status:k,title:T,messages:[...L,...W],resume:e.resume,hostIdeType:!tt(e)&&!Ze(e)?e.type:void 0,workspaceName:c,displayPrimary:T||c||(tt(e)?e.mode==="chat"?h:"Terminal":h),displaySecondary:u,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:_?N.buttons:void 0,modalMessage:_?N.message:void 0,streamSource:"native",tabKey:En(y,e.id),machineName:a,connectionState:i})}if(m&&(tt(e)||Ze(e)))return n;for(const y of p){const h=y.activeModal&&Array.isArray(y.activeModal.buttons)&&y.activeModal.buttons.length>0,N=gu(y),_=dp(y),k=`${e.id}:${_}`,I=y.title&&String(y.title).trim()||"",j=To(I,y.agentName,y.agentType)?"":I,v=y.messages||[],x=Ho(s,[k,y.sessionId,y.instanceId]),E=$o(v,x);(y.transport==="cdp-webview"||y.sessionId||y.providerSessionId||v.length>0||E.length>0||h||j||!["idle","panel_hidden","disconnected","not_monitored"].includes(N))&&n.push({routeId:e.id,sessionId:y.sessionId||y.instanceId,providerSessionId:y.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:y.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:y.sessionCapabilities,mode:"chat",agentName:y.agentName,agentType:y.agentType,status:N,title:j,messages:[...v,...E],hostIdeType:e.type,workspaceName:c,displayPrimary:j||c||y.agentName||u,displaySecondary:`${u} · ${y.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,lastUpdated:y.lastUpdated||e.lastUpdated,modalButtons:h?y.activeModal.buttons:void 0,modalMessage:h?y.activeModal.message:void 0,streamSource:"agent-stream",tabKey:En(y.sessionId||y.instanceId,k),machineName:a,connectionState:i})}return n.length===0&&n.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:l,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:c,displayPrimary:c||u,displaySecondary:u,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:En(e.sessionId||e.instanceId,e.id),connectionState:i}),n}function mp(e){const s=e.split(":");return s.length>=3&&(s[1]==="ide"||s[1]==="cli"||s[1]==="acp")?{daemonId:s[0],targetSessionId:s.slice(2).join(":")||void 0}:{daemonId:e}}function pp(e,s){const r=mp(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Tc=[{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:"🏄"}],Lc=[{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:"🧩"}],_c=[{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:"🟠"}],fp=Tc,hp=Lc,xp=_c;function Ss(...e){return Zl(ed(e))}function bp({icon:e,title:s,subtitle:r,badge:n,actions:a,className:i}){return t.jsxs("div",{className:Ss("dashboard-header",i),children:[t.jsxs("div",{children:[t.jsxs("h1",{className:"header-title flex items-center gap-2",children:[t.jsx("span",{className:"flex items-center text-lg",children:e})," ",s,n&&t.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&&t.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),a&&t.jsx("div",{className:"flex gap-2",children:a})]})}function Rc({icon:e,title:s,subtitle:r,badge:n,actions:a,widthClassName:i="max-w-6xl",contentClassName:c,children:l}){return t.jsxs("div",{className:"flex flex-col h-full",children:[t.jsx(bp,{icon:e,title:s,subtitle:r,badge:n,actions:a}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:Ss("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}function Lt({title:e,icon:s,description:r,accentColor:n,className:a,children:i}){return t.jsxs("div",{className:Ss("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)&&t.jsxs("div",{className:"mb-4",children:[e&&t.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[s&&t.jsx("span",{className:"mr-1.5",children:s}),e]}),r&&t.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),i]})}function Pc({icon:e,title:s,description:r,action:n,className:a}){return t.jsxs("div",{className:Ss("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[t.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),t.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:s}),t.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const gp={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"},yp={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Pr({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:Ss("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",gp[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:yp[e]}),t.jsx("span",{children:s})]}),r&&t.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}const vp={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"},wp={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function jp({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:Ss("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",vp[e],r),children:[t.jsx("span",{className:Ss("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",wp[e])}),n]})}const ua="adhdev:themechange";function kp(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Is(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function As(e){return e==="system"?kp():e}function Dc(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function qr(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(ua,{detail:{preference:e,theme:s}}))}function Sp(){const e=Is(),s=As(e);Dc(s),qr(e,s)}function za(){const[e,s]=o.useState(Is),[r,n]=o.useState(()=>As(Is()));o.useEffect(()=>{Dc(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=u=>{if(e==="system"){const p=u.matches?"light":"dark";n(p),qr("system",p)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=u=>{const p=u.detail||{},m=p.preference,f=p.theme;s(m==="dark"||m==="light"||m==="system"?m:Is()),n(f==="dark"||f==="light"?f:As(Is()))},l=u=>{if(u.key!=="theme")return;const p=Is(),m=As(p);s(p),n(m)};return window.addEventListener(ua,c),window.addEventListener("storage",l),()=>{window.removeEventListener(ua,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=As(c);s(c),n(l);try{localStorage.setItem("theme",c)}catch{}qr(c,l)},[]),i=o.useCallback(()=>{s(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=As(l);n(u);try{localStorage.setItem("theme",l)}catch{}return qr(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const Uo={dark:"Dark",light:"Light",system:"System"};function Np({collapsed:e}){const{preference:s,cycleTheme:r}=za(),n=s==="dark"?t.jsx(Pd,{size:16}):s==="light"?t.jsx(Rd,{size:16}):t.jsx(Dd,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Uo[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:Uo[s]})]})}function ds({label:e,description:s,checked:r,disabled:n,onChange:a,extra:i}){return t.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[t.jsxs("div",{className:"pr-4",children:[t.jsx("div",{className:"font-medium text-sm",children:e}),t.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:s})]}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,t.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:[t.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))"}}),t.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 Cp({onPrefChange:e}){const[s,r]=Au(),[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 t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(mn,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:c=>i("globalEnabled",c)}),s.globalEnabled&&t.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&t.jsx(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Rt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:c=>i("browserNotifications",c)}),s.globalEnabled&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.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"&&t.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[t.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),t.jsx("button",{onClick:()=>{Zi().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"&&t.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"&&t.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."})]}),s.globalEnabled&&s.browserNotifications&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.jsx(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ed,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:c=>i("completionAlert",c)}),t.jsx(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx($d,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:c=>i("approvalAlert",c)}),t.jsx(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(dr,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!s.globalEnabled&&t.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function an(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function Ip(e,s){const r=an(e),n=an(s);if(!r||!n)return e.localeCompare(s);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 Ec(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function or(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||Ip(r,s)>=0)return!1;const n=an(r),a=an(s);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Ap(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function $n(e,s){return e instanceof Error?e.message:s}function Mp({ides:e,emptyMessage:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?t.jsx(Pc,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:"No machines connected",description:s||"Install ADHDev on a machine and sign in to connect it here."}):t.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>t.jsx(Lp,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function Fo({title:e,message:s,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 lr.createPortal(t.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,children:t.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:[t.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),t.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:s}),t.jsxs("div",{className:"flex gap-2 justify-end",children:[t.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"}),t.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 Tp(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...fp,...hp,...xp].find(a=>a.id===s||s.includes(a.id)||a.id.includes(s));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function Lp({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var W,U;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[p,m]=o.useState(null),[f,g]=o.useState("idle"),[w,A]=o.useState(""),d=e.version||null,b=((W=e.machine)==null?void 0:W.platform)||((U=e.system)==null?void 0:U.platform)||"",y=_t(e,{fallbackId:e.id}),h=b==="win32"?"🪟":b==="darwin"?"🍎":"🐧",N=s.filter(C=>C.daemonId===e.id&&C.transport==="cdp-page"),_=s.filter(C=>C.daemonId===e.id&&C.transport==="pty"),k=s.filter(C=>C.daemonId===e.id&&C.transport==="acp"),I=e.p2p,j=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const C=Ap(await r(e.id,"daemon_upgrade",{}));C.alreadyLatest?(c("done"),u(`Already on v${C.version||"latest"}.`)):C.upgraded||C.success?(c("done"),u(`Upgrade to v${C.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(C.error||"Upgrade failed"))}catch(C){c("error"),u($n(C,"Connection lost during upgrade"))}}},v=async()=>{if(m(null),!!n){g("loading");try{await n(e.id),g("done"),A("Machine disconnected.")}catch(C){g("error"),A($n(C,"Failed to disconnect"))}}},x=async()=>{if(m(null),!!a){g("loading");try{await a(e.id),g("done"),A("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(C){g("error"),A($n(C,"Failed to revoke token"))}}},E="0.8.83",T=Ec(e,E),L=or(e,E),M=N.length+_.length+k.length;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("span",{className:"text-xl",children:h}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-sm",children:y}),t.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[t.jsxs("span",{children:[e.id.substring(0,12),"…"]}),d&&t.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${T?"":"bg-bg-secondary"}`,style:T?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",d,!T&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&T&&t.jsx("button",{onClick:j,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${E}`,children:i==="upgrading"?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${L?"↑ Update now":`↑ Update${` to v${E}`}`}`}),n&&t.jsx("button",{onClick:()=>m("disconnect"),disabled:f==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&t.jsx("button",{onClick:()=>m("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),t.jsx(jp,{status:e.status==="online"?"online":"error"})]})]}),t.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[I&&t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${I.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${I.state==="connecting"||I.state==="new"?"animate-pulse":""}`,style:I.state==="connecting"||I.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",I.state==="connected"?"connected":I.state==="connecting"||I.state==="new"?"connecting...":I.state||"off"]}),I.peers!==void 0&&I.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",I.peers," peer",I.peers!==1?"s":"",")"]})]}),I&&M>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),M>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[N.map(C=>{const R=Tp(C.type),B=C.cdpConnected;return t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:R.icon}),t.jsx("span",{children:R.name}),B!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${B?"bg-green-400":"animate-pulse"}`,style:B?void 0:{background:"var(--status-warning)"},title:B?"CDP connected":"CDP connecting..."})]},C.id)}),_.map(C=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"⌨️"}),t.jsx("span",{children:C.cliName||"CLI"})]},C.id)),k.map(C=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"🔗"}),t.jsx("span",{children:C.cliName||"ACP"})]},C.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||w)&&t.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||f==="error"?"text-red-400":i==="done"||f==="done"?"text-green-400":"text-text-muted"}`,children:w||l})]}),p==="disconnect"&&t.jsx(Fo,{title:"🔌 Disconnect Machine",message:`Disconnect "${y}" from ADHDev?
32
+ `).includes(a)))}function Jm(e,s="recent"){const r=e.slice();return r.sort((n,a)=>{if(s==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(s==="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 Sc(e,s={}){return Jm(Qm(e,s),s.sortMode||"recent")}function nn(e){return e?"Resume saved history":"Start fresh"}function Ba(e){return e?"Resuming saved history…":"Starting fresh…"}function Zm(){return"Start fresh"}function Nc(e,s=!1){return e==="cli"?nn(s):e==="ide"?"Start IDE":"Start ACP session"}function Cc(e,s=!1){return e==="cli"?Ba(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function ep(){return"Recover hosted runtime"}function tp(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function sp(){return"Open saved history"}function rp(){return"Saved History"}function Wa(){return"Use saved history when you want continuity in the same provider conversation."}function np(){return"No saved history found yet."}function ap(){return"Refresh saved history"}function op(){return"Refreshing saved history…"}function fs(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function hs(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 Os(e){return e==="start-fresh"?"Start fresh":"Restart"}function Hs(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Oa(e){return`Resume saved history with ${e}?`}function Ha(){return"Review or change the target workspace before resuming saved history."}function ip(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 Ua({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:u,onClose:p,onNewChat:m,onSwitchSession:f,onRefreshHistory:g,onResumeSavedSession:w}){var v;const A=s.find(x=>x.id===e.routeId),d=(A==null?void 0:A.chats)||[],b=(v=A==null?void 0:A.activeChat)==null?void 0:v.id,y=tt(e)&&!Ze(e),[h,N]=o.useState(()=>jt()),_=l||h,k=x=>{if(u){u(x);return}N(x)},I=o.useMemo(()=>Sc(a,{textQuery:_.textQuery,workspaceQuery:_.workspaceQuery,modelQuery:_.modelQuery,resumableOnly:_.resumableOnly,sortMode:_.sortMode}),[_.modelQuery,_.resumableOnly,_.sortMode,_.textQuery,_.workspaceQuery,a]),j=t.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:[t.jsx("div",{onClick:p,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),t.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:[t.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:[t.jsxs("div",{children:[t.jsx("h3",{className:"m-0 text-lg font-extrabold",children:y?rp():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Fm(e)}),y&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Wa()})]}),t.jsx("button",{onClick:p,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:t.jsx(At,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!y&&t.jsx("button",{onClick:m,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"}),y?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[t.jsx("input",{type:"text",value:_.textQuery,onChange:x=>k({..._,textQuery:x.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"}),t.jsx("input",{type:"text",value:_.workspaceQuery,onChange:x=>k({..._,workspaceQuery:x.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"}),t.jsx("input",{type:"text",value:_.modelQuery,onChange:x=>k({..._,modelQuery:x.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"}),t.jsxs("select",{value:_.sortMode,onChange:x=>k({..._,sortMode:x.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[t.jsx("option",{value:"recent",children:"Most recent"}),t.jsx("option",{value:"oldest",children:"Oldest first"}),t.jsx("option",{value:"messages",children:"Most messages"})]})]}),t.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsx("input",{type:"checkbox",checked:_.resumableOnly,onChange:x=>k({..._,resumableOnly:x.target.checked})}),"Resume-ready only"]})]}),I.map(x=>{const E=e.providerSessionId===x.providerSessionId,T=E||!x.canResume||!!c;return t.jsxs("button",{type:"button",onClick:()=>{T||!w||w(x)},disabled:T,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${E?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${T?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:`font-bold text-sm mb-1 truncate ${E?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:x.title||"Untitled Session"}),t.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:x.providerSessionId})]}),t.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:ip(x.lastMessageAt)})]}),t.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:x.preview||"No saved preview yet"}),t.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[t.jsxs("div",{className:"truncate",children:[x.workspace||"Workspace unknown",ws(x.summaryMetadata)?` · ${ws(x.summaryMetadata)}`:"",x.messageCount>0?` · ${x.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:E?"ACTIVE":x.canResume?c===x.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},x.id)})]}):d.map(x=>t.jsxs("div",{onClick:()=>{f(e.routeId,x.id),p()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===x.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[t.jsx("div",{className:`font-bold text-sm mb-1 ${b===x.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:x.title||"Untitled Session"}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[x.id.substring(0,12),"..."]}),b===x.id&&t.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},x.id)),(y&&!i&&I.length===0||!y&&d.length===0)&&t.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[t.jsx("div",{className:"text-3xl mb-3 opacity-60",children:t.jsx(_d,{size:32})}),t.jsx("div",{className:"text-[13px]",children:y?a.length>0?"No saved history matches these filters.":np():"No recent chat sessions found."})]}),y&&i&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:op()})})]}),t.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:t.jsx("button",{onClick:g,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Fs,{size:13})," ",y?ap():"Refresh History"]})})})]})]});return typeof document>"u"?j:lr.createPortal(j,document.body)}const Oo={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 Ic({toasts:e,onDismiss:s,onClickToast:r}){return t.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=Oo[n.type]||Oo.info;return t.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:[t.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))`}}),t.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(),s(n.id)},"aria-label":"Dismiss",children:t.jsx(At,{size:14})}),t.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[t.jsx("div",{className:"flex items-center gap-2 pr-8",children:t.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})}),t.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&t.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((i,c)=>t.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(),s(n.id)},children:i.label},c))})]})]},n.id)})})}const cp=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function lp(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function dp(e){return e.sessionId||e.instanceId||e.agentType}function En(e,s){return e||s}function Ho(e,s){const r=new Set,n=[];for(const a of s)if(a)for(const i of e[a]||[]){const c=i._localId||`${i.role}:${i.timestamp}:${i.content}`;r.has(c)||(r.add(c),n.push(i))}return n.sort((a,i)=>a.timestamp-i.timestamp)}function Ac(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=_t(r,{fallbackId:r.id}));return s}function Mc(e,s={}){var n,a;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((a=s.machineNames)==null?void 0:a[e.daemonId])||void 0,connectionState:s.connectionStates?s.connectionStates[r]||s.defaultConnectionState||"new":s.defaultConnectionState}}function Fa(e,s,r={}){return up(e,s,Mc(e,r))}function up(e,s,r={}){var f,g,w,A,d,b;const n=[],a=r.machineName,i=r.connectionState,c=lp(e),l=bu(e.type,{agentName:e.cliName}),u=tt(e)||Ze(e)?l:ot(e.type),p=Array.isArray(e.childSessions)?e.childSessions.map(y=>{var h,N;return{sessionId:y.id,instanceId:y.id,providerSessionId:y.providerSessionId,transport:y.transport,sessionCapabilities:y.capabilities,agentType:y.providerType,agentName:y.providerName||ot(y.providerType),status:y.status,title:y.title,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,messages:((h=y.activeChat)==null?void 0:h.messages)||[],activeModal:((N=y.activeChat)==null?void 0:N.activeModal)||void 0,unread:y.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,inboxBucket:y.inboxBucket,surfaceHidden:y.surfaceHidden}}):[],m=cp(e);if(m){const y=e.sessionId||e.instanceId,h=l,N=(f=e.activeChat)==null?void 0:f.activeModal,_=N&&Array.isArray(N.buttons)&&N.buttons.length>0,k=Ct((g=e.activeChat)==null?void 0:g.status,{activeModal:(w=e.activeChat)==null?void 0:w.activeModal})||Ct((d=(A=e.agents)==null?void 0:A[0])==null?void 0:d.status)||"idle",I=e.activeChat||{title:"",messages:[]};let j=I.title&&String(I.title).trim()?String(I.title).trim():"";const v=(b=e.activeChat)==null?void 0:b.id,x=e.chats;if(v&&Array.isArray(x)&&x.length>0){const U=x.find(C=>C.id===v||C.id&&String(C.id)===String(v));U!=null&&U.title&&String(U.title).trim()&&(j=String(U.title).trim())}const E=(tt(e)||Ze(e),e.type),T=(tt(e)||Ze(e))&&To(j,h,E)?"":j,L=I.messages||[],M=Ho(s,[e.id,y]),W=$o(L,M);n.push({routeId:e.id,sessionId:y,providerSessionId:e.providerSessionId,nativeSessionId:y,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:tt(e)?e.mode||"terminal":"chat",agentName:h,agentType:E,status:k,title:T,messages:[...L,...W],resume:e.resume,hostIdeType:!tt(e)&&!Ze(e)?e.type:void 0,workspaceName:c,displayPrimary:T||c||(tt(e)?e.mode==="chat"?h:"Terminal":h),displaySecondary:u,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:_?N.buttons:void 0,modalMessage:_?N.message:void 0,streamSource:"native",tabKey:En(y,e.id),machineName:a,connectionState:i})}if(m&&(tt(e)||Ze(e)))return n;for(const y of p){const h=y.activeModal&&Array.isArray(y.activeModal.buttons)&&y.activeModal.buttons.length>0,N=gu(y),_=dp(y),k=`${e.id}:${_}`,I=y.title&&String(y.title).trim()||"",j=To(I,y.agentName,y.agentType)?"":I,v=y.messages||[],x=Ho(s,[k,y.sessionId,y.instanceId]),E=$o(v,x);(y.transport==="cdp-webview"||y.sessionId||y.providerSessionId||v.length>0||E.length>0||h||j||!["idle","panel_hidden","disconnected","not_monitored"].includes(N))&&n.push({routeId:e.id,sessionId:y.sessionId||y.instanceId,providerSessionId:y.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:y.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:y.sessionCapabilities,mode:"chat",agentName:y.agentName,agentType:y.agentType,status:N,title:j,messages:[...v,...E],hostIdeType:e.type,workspaceName:c,displayPrimary:j||c||y.agentName||u,displaySecondary:`${u} · ${y.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,lastUpdated:y.lastUpdated||e.lastUpdated,modalButtons:h?y.activeModal.buttons:void 0,modalMessage:h?y.activeModal.message:void 0,streamSource:"agent-stream",tabKey:En(y.sessionId||y.instanceId,k),machineName:a,connectionState:i})}return n.length===0&&n.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:l,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:c,displayPrimary:c||u,displaySecondary:u,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:En(e.sessionId||e.instanceId,e.id),connectionState:i}),n}function mp(e){const s=e.split(":");return s.length>=3&&(s[1]==="ide"||s[1]==="cli"||s[1]==="acp")?{daemonId:s[0],targetSessionId:s.slice(2).join(":")||void 0}:{daemonId:e}}function pp(e,s){const r=mp(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Tc=[{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:"🏄"}],Lc=[{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:"🧩"}],_c=[{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:"🟠"}],fp=Tc,hp=Lc,xp=_c;function Ss(...e){return Zl(ed(e))}function bp({icon:e,title:s,subtitle:r,badge:n,actions:a,className:i}){return t.jsxs("div",{className:Ss("dashboard-header",i),children:[t.jsxs("div",{children:[t.jsxs("h1",{className:"header-title flex items-center gap-2",children:[t.jsx("span",{className:"flex items-center text-lg",children:e})," ",s,n&&t.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&&t.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),a&&t.jsx("div",{className:"flex gap-2",children:a})]})}function Rc({icon:e,title:s,subtitle:r,badge:n,actions:a,widthClassName:i="max-w-6xl",contentClassName:c,children:l}){return t.jsxs("div",{className:"flex flex-col h-full",children:[t.jsx(bp,{icon:e,title:s,subtitle:r,badge:n,actions:a}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:Ss("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}function Lt({title:e,icon:s,description:r,accentColor:n,className:a,children:i}){return t.jsxs("div",{className:Ss("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)&&t.jsxs("div",{className:"mb-4",children:[e&&t.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[s&&t.jsx("span",{className:"mr-1.5",children:s}),e]}),r&&t.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),i]})}function Pc({icon:e,title:s,description:r,action:n,className:a}){return t.jsxs("div",{className:Ss("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[t.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),t.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:s}),t.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const gp={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"},yp={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Pr({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:Ss("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",gp[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:yp[e]}),t.jsx("span",{children:s})]}),r&&t.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}const vp={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"},wp={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function jp({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:Ss("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",vp[e],r),children:[t.jsx("span",{className:Ss("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",wp[e])}),n]})}const ua="adhdev:themechange";function kp(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Is(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function As(e){return e==="system"?kp():e}function Dc(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function qr(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(ua,{detail:{preference:e,theme:s}}))}function Sp(){const e=Is(),s=As(e);Dc(s),qr(e,s)}function za(){const[e,s]=o.useState(Is),[r,n]=o.useState(()=>As(Is()));o.useEffect(()=>{Dc(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=u=>{if(e==="system"){const p=u.matches?"light":"dark";n(p),qr("system",p)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=u=>{const p=u.detail||{},m=p.preference,f=p.theme;s(m==="dark"||m==="light"||m==="system"?m:Is()),n(f==="dark"||f==="light"?f:As(Is()))},l=u=>{if(u.key!=="theme")return;const p=Is(),m=As(p);s(p),n(m)};return window.addEventListener(ua,c),window.addEventListener("storage",l),()=>{window.removeEventListener(ua,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=As(c);s(c),n(l);try{localStorage.setItem("theme",c)}catch{}qr(c,l)},[]),i=o.useCallback(()=>{s(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=As(l);n(u);try{localStorage.setItem("theme",l)}catch{}return qr(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const Uo={dark:"Dark",light:"Light",system:"System"};function Np({collapsed:e}){const{preference:s,cycleTheme:r}=za(),n=s==="dark"?t.jsx(Pd,{size:16}):s==="light"?t.jsx(Rd,{size:16}):t.jsx(Dd,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Uo[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:Uo[s]})]})}function ds({label:e,description:s,checked:r,disabled:n,onChange:a,extra:i}){return t.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[t.jsxs("div",{className:"pr-4",children:[t.jsx("div",{className:"font-medium text-sm",children:e}),t.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:s})]}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,t.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:[t.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))"}}),t.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 Cp({onPrefChange:e}){const[s,r]=Au(),[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 t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(mn,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:c=>i("globalEnabled",c)}),s.globalEnabled&&t.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&t.jsx(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Rt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:c=>i("browserNotifications",c)}),s.globalEnabled&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.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"&&t.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[t.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),t.jsx("button",{onClick:()=>{Zi().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"&&t.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"&&t.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."})]}),s.globalEnabled&&s.browserNotifications&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.jsx(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ed,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:c=>i("completionAlert",c)}),t.jsx(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx($d,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:c=>i("approvalAlert",c)}),t.jsx(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(dr,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!s.globalEnabled&&t.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function an(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function Ip(e,s){const r=an(e),n=an(s);if(!r||!n)return e.localeCompare(s);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 Ec(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function or(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||Ip(r,s)>=0)return!1;const n=an(r),a=an(s);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Ap(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function $n(e,s){return e instanceof Error?e.message:s}function Mp({ides:e,emptyMessage:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?t.jsx(Pc,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:"No machines connected",description:s||"Install ADHDev on a machine and sign in to connect it here."}):t.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>t.jsx(Lp,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function Fo({title:e,message:s,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 lr.createPortal(t.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,children:t.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:[t.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),t.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:s}),t.jsxs("div",{className:"flex gap-2 justify-end",children:[t.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"}),t.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 Tp(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...fp,...hp,...xp].find(a=>a.id===s||s.includes(a.id)||a.id.includes(s));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function Lp({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var W,U;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[p,m]=o.useState(null),[f,g]=o.useState("idle"),[w,A]=o.useState(""),d=e.version||null,b=((W=e.machine)==null?void 0:W.platform)||((U=e.system)==null?void 0:U.platform)||"",y=_t(e,{fallbackId:e.id}),h=b==="win32"?"🪟":b==="darwin"?"🍎":"🐧",N=s.filter(C=>C.daemonId===e.id&&C.transport==="cdp-page"),_=s.filter(C=>C.daemonId===e.id&&C.transport==="pty"),k=s.filter(C=>C.daemonId===e.id&&C.transport==="acp"),I=e.p2p,j=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const C=Ap(await r(e.id,"daemon_upgrade",{}));C.alreadyLatest?(c("done"),u(`Already on v${C.version||"latest"}.`)):C.upgraded||C.success?(c("done"),u(`Upgrade to v${C.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(C.error||"Upgrade failed"))}catch(C){c("error"),u($n(C,"Connection lost during upgrade"))}}},v=async()=>{if(m(null),!!n){g("loading");try{await n(e.id),g("done"),A("Machine disconnected.")}catch(C){g("error"),A($n(C,"Failed to disconnect"))}}},x=async()=>{if(m(null),!!a){g("loading");try{await a(e.id),g("done"),A("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(C){g("error"),A($n(C,"Failed to revoke token"))}}},E="0.8.84",T=Ec(e,E),L=or(e,E),M=N.length+_.length+k.length;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("span",{className:"text-xl",children:h}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-sm",children:y}),t.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[t.jsxs("span",{children:[e.id.substring(0,12),"…"]}),d&&t.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${T?"":"bg-bg-secondary"}`,style:T?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",d,!T&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&T&&t.jsx("button",{onClick:j,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${E}`,children:i==="upgrading"?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${L?"↑ Update now":`↑ Update${` to v${E}`}`}`}),n&&t.jsx("button",{onClick:()=>m("disconnect"),disabled:f==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&t.jsx("button",{onClick:()=>m("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),t.jsx(jp,{status:e.status==="online"?"online":"error"})]})]}),t.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[I&&t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${I.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${I.state==="connecting"||I.state==="new"?"animate-pulse":""}`,style:I.state==="connecting"||I.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",I.state==="connected"?"connected":I.state==="connecting"||I.state==="new"?"connecting...":I.state||"off"]}),I.peers!==void 0&&I.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",I.peers," peer",I.peers!==1?"s":"",")"]})]}),I&&M>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),M>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[N.map(C=>{const R=Tp(C.type),B=C.cdpConnected;return t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:R.icon}),t.jsx("span",{children:R.name}),B!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${B?"bg-green-400":"animate-pulse"}`,style:B?void 0:{background:"var(--status-warning)"},title:B?"CDP connected":"CDP connecting..."})]},C.id)}),_.map(C=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"⌨️"}),t.jsx("span",{children:C.cliName||"CLI"})]},C.id)),k.map(C=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"🔗"}),t.jsx("span",{children:C.cliName||"ACP"})]},C.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||w)&&t.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||f==="error"?"text-red-400":i==="done"||f==="done"?"text-green-400":"text-text-muted"}`,children:w||l})]}),p==="disconnect"&&t.jsx(Fo,{title:"🔌 Disconnect Machine",message:`Disconnect "${y}" from ADHDev?
33
33
 
34
34
  This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
35
35
 
@@ -40,7 +40,7 @@ This will:
40
40
  • Delete the machine registration
41
41
  • Require restarting ADHDev on that machine
42
42
 
43
- Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:x,onCancel:()=>m(null)})]})}const _p=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Rp(){const{preference:e,setPreference:s}=za();return t.jsx("div",{className:"flex gap-2",children:_p.map(r=>t.jsxs("button",{onClick:()=>s(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:[t.jsx("span",{children:r.icon}),r.label]},r.id))})}function Pp(e){const s=e.trim();return/^#[0-9a-fA-F]{6}$/.test(s)?s:/^#[0-9a-fA-F]{3}$/.test(s)?`#${s[1]}${s[1]}${s[2]}${s[2]}${s[3]}${s[3]}`:null}function Dp(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Kn(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function zo(e){const{r:s,g:r,b:n}=Dp(e);return .2126*Kn(s)+.7152*Kn(r)+.0722*Kn(n)}function Vo(e,s){const r=zo(e),n=zo(s),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function $c(e){const s=Pp(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return Vo(s,r)>=Vo(s,n)?r:n}const ma={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},pa={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},Ep=[{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"}}}],Kc="adhdev-chat-theme",Bc="adhdev-chat-theme-custom";function Yr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Kc)||"ember"}catch{return"ember"}}function Wt(e){try{const s=localStorage.getItem(Bc);if(s){const r=JSON.parse(s);return{...e==="dark"?ma:pa,...r[e]}}}catch{}return e==="dark"?ma:pa}function Dr(e,s){try{localStorage.setItem(Bc,JSON.stringify({dark:e,light:s}))}catch{}}function $t(e,s){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}, ${s})`}function on(e,s){const r=Math.min(255,parseInt(e.slice(1,3),16)+s),n=Math.min(255,parseInt(e.slice(3,5),16)+s),a=Math.min(255,parseInt(e.slice(5,7),16)+s);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const $p={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function ir(e,s){var a;const r=(a=$p[e])==null?void 0:a[s];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",on(r,24)),n.style.setProperty("--accent-on-primary",$c(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${on(r,18)})`),n.style.setProperty("--border-accent",$t(r,.35)),n.style.setProperty("--nav-active-bg",$t(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${$t(r,.06)}`)}function xs(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",$t(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",$t(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",$t(e.borderSubtle,.25)),s.style.setProperty("--text-primary",e.textPrimary),s.style.setProperty("--text-secondary",e.textSecondary),s.style.setProperty("--text-muted",e.textMuted),s.style.setProperty("--border-subtle",$t(e.borderSubtle,.5)),s.style.setProperty("--border-default",$t(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",on(e.accentColor,30)),s.style.setProperty("--accent-on-primary",$c(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${on(e.accentColor,40)})`),s.style.setProperty("--border-accent",$t(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",$t(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${$t(e.accentColor,.06)}`),s.style.setProperty("--chat-user-bg",e.userBubble),s.style.setProperty("--chat-user-color",e.userText),s.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),s.style.setProperty("--chat-assistant-bg",e.assistantBubble),s.style.setProperty("--chat-assistant-color",e.assistantText),s.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),s.style.setProperty("--chat-assistant-border",`1px solid ${$t(e.accentColor,.12)}`),s.style.setProperty("--chat-container-bg",e.containerBg),s.style.setProperty("--dashboard-pane-bg",e.containerBg),s.style.setProperty("--chat-thought-accent",e.accentColor),s.style.setProperty("--chat-tool-accent",e.accentColor),s.style.setProperty("--chat-action-color",e.accentColor),s.style.setProperty("--chat-send-bg",e.sendButton),s.style.setProperty("--chat-input-border",e.inputBorder)}function Va(){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 Kp(e){try{localStorage.setItem(Kc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=bs()?"dark":"light";xs(Wt(s))}else Va(),ir(e,bs()?"dark":"light")}function Bp(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Yr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=bs()?"dark":"light";xs(Wt(s))}else Va(),ir(e,bs()?"dark":"light")}function bs(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Nt({label:e,value:s,onChange:r}){return t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[t.jsx("input",{type:"color",value:s,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),t.jsx("input",{type:"text",value:s,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 Qs({title:e,children:s}){return t.jsxs("div",{style:{marginBottom:14},children:[t.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}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s})]})}function Wp({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,a]=o.useState(()=>Wt(r));o.useEffect(()=>{a(Wt(r))},[r]);const i=o.useCallback((c,l)=>{a(u=>{const p={...u,[c]:l},f=Wt(r==="dark"?"light":"dark");return r==="dark"?Dr(p,f):Dr(f,p),xs(p),s(p),p})},[r,s]);return t.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[t.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",t.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"]})]}),t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsxs(Qs,{title:"App Background",children:[t.jsx(Nt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),t.jsx(Nt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),t.jsx(Nt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),t.jsxs(Qs,{title:"App Text",children:[t.jsx(Nt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),t.jsx(Nt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),t.jsx(Nt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),t.jsxs(Qs,{title:"Borders & Accent",children:[t.jsx(Nt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),t.jsx(Nt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),t.jsx(Nt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),t.jsxs("div",{children:[t.jsxs(Qs,{title:"Chat Bubbles",children:[t.jsx(Nt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),t.jsx(Nt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),t.jsx(Nt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),t.jsx(Nt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),t.jsxs(Qs,{title:"Chat Layout",children:[t.jsx(Nt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),t.jsx(Nt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),t.jsx(Nt,{label:"Input border",value:n.inputBorder,onChange:c=>i("inputBorder",c)}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[t.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)"}}),t.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),t.jsx("button",{onClick:()=>{const c=e?ma:pa,u=Wt(e?"light":"dark");e?Dr(c,u):Dr(u,c),a(c),xs(c),s(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 Op(){const[e,s]=o.useState(Yr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Wt("dark"));o.useEffect(()=>{n(bs());const u=new MutationObserver(()=>{const f=bs();n(f);const g=Yr();g==="custom"?xs(Wt(f?"dark":"light")):ir(g,f?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const p=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=bs();n(f);const g=Yr();g==="custom"?xs(Wt(f?"dark":"light")):ir(g,f?"dark":"light")};return p.addEventListener("change",m),()=>{u.disconnect(),p.removeEventListener("change",m)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?xs(Wt(r?"dark":"light")):(Va(),ir(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Wt(r?"dark":"light"))},[r]);const c=u=>{s(u),Kp(u)},l=[...Ep,{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 t.jsxs("div",{children:[t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:l.map(u=>{const p=e===u.id,m=r?u.preview.dark:u.preview.light,f=u.id==="honey"||u.id==="ember"?"#1a1a1a":u.id==="custom"?a.userText:"#fff";return t.jsxs("button",{onClick:()=>c(u.id),className:"text-left rounded-xl p-3 transition-all",style:{background:p?"var(--bg-glass-hover)":"var(--bg-glass)",border:p?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:p?1:.75},children:[t.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:"Hello! How can I help?"}),t.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.userBubble,color:f},children:"Fix the bug please"}),t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:"On it! ✨"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[p&&t.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:u.id==="custom"?"🎨 Custom":u.name}),t.jsx("div",{className:"text-[10px] text-text-muted",children:u.description})]})]})]},u.id)})}),e==="custom"&&t.jsx(Wp,{dark:r,onColorsChange:u=>i(u)})]})}const Ga="adhdev_mobileDashboardMode_v1",fa="adhdev:mobile-dashboard-mode-change";function qa(){try{return localStorage.getItem(Ga)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Hp(e){if(typeof window>"u")return()=>{};const s=a=>{e(a??qa())},r=a=>{const i=a.detail;s(i)},n=a=>{a.key&&a.key!==Ga||s()};return window.addEventListener(fa,r),window.addEventListener("storage",n),()=>{window.removeEventListener(fa,r),window.removeEventListener("storage",n)}}function Up(e){try{localStorage.setItem(Ga,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(fa,{detail:e}))}function Fp(){const[e,s]=o.useState(!0);return o.useEffect(()=>{s(qa()==="chat")},[]),t.jsx(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Qt,{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=>{s(r),Up(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}function zp(e,s,r){return{...e||{},id:s,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 Vp(e,s){const{sendData:r}=Pt(),{injectEntries:n,getIdes:a}=en(),i=Array.from(new Set(e.filter(Boolean))).join("|");o.useEffect(()=>{if(!(s!=null&&s.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const l=c.map(u=>as.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:s==null?void 0:s.intervalMs}},p=>{const m=a().find(g=>g.id===u),f=zp(m,u,p);n([f])}));return()=>{l.forEach(u=>u())}},[i,a,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}const Gp=4e3;function Wc(e,s){const{sendData:r}=Pt(),[n,a]=o.useState(null),[i,c]=o.useState(!1);return o.useEffect(()=>{if(!e){a(null),c(!1);return}if(!(s!=null&&s.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const u=as.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(s==null?void 0:s.includeSessions)!==!1,...typeof(s==null?void 0:s.limit)=="number"?{limit:s.limit}:{},...typeof(s==null?void 0:s.intervalMs)=="number"?{intervalMs:s.intervalMs}:{}}},p=>{l&&(clearTimeout(l),l=null),a(p.diagnostics),c(!1)});return u.initialSendAccepted?l=setTimeout(()=>{c(!1)},Gp):c(!1),()=>{l&&clearTimeout(l),u()}},[e,s==null?void 0:s.enabled,s==null?void 0:s.includeSessions,s==null?void 0:s.intervalMs,s==null?void 0:s.limit,r]),{diagnostics:n,loading:i,applyDiagnostics:a}}function qp(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Oc(e){const{sendData:s}=Pt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=qp(e);if(!a||!e.sessionId||!s){n({});return}const i=as.subscribe({sendData:s},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}),Ds.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()}},[e.daemonId,e.routeId,e.sessionId,s]),r}const Hc="adhdev_hiddenTabs";function Yp(){try{const e=localStorage.getItem(Hc);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function Ns(e){try{localStorage.setItem(Hc,JSON.stringify([...e]))}catch{}}function Er(e){return Aa(e)}function Ya(e,s){return ss(s).some(r=>e.has(r))}function Xp(){const[e,s]=o.useState(Yp),r=o.useCallback(p=>{s(m=>{const f=new Set(m);return f.has(p)?f.delete(p):f.add(p),Ns(f),f})},[]),n=o.useCallback(p=>{s(m=>{if(m.has(p))return m;const f=new Set(m);return f.add(p),Ns(f),f})},[]),a=o.useCallback(p=>{s(m=>{if(!m.has(p))return m;const f=new Set(m);return f.delete(p),Ns(f),f})},[]),i=o.useCallback(()=>{s(p=>{if(p.size===0)return p;const m=new Set;return Ns(m),m})},[]),c=o.useCallback((p,m)=>{s(f=>{const g=new Set(f);for(const w of m)g.add(w);return Ns(g),g})},[]),l=o.useCallback((p,m)=>{s(f=>{const g=new Set(f);for(const w of m)g.delete(w);return Ns(g),g})},[]),u=o.useCallback(p=>Ya(e,p),[e]);return{hiddenTabs:e,toggleTab:r,hideTab:n,showTab:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function Uc(e){return e instanceof Error?e.message:String(e||"")}function Xa(e){const s=Uc(e);return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("P2P channel not open")||s.includes("P2P not available")||s.includes("P2P data channel closed")||s.includes("P2P receiver stopped")}function Qa(e){const s=Uc(e);return s.includes("P2P command timeout")||s.includes("P2P data channel closed")||s.includes("P2P receiver stopped")}function Go(e,s){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=s[r];return!n||e.mode===n?e:{...e,mode:n}}function Qp(e,s){if(!Array.isArray(e)||e.length===0||!s||Object.keys(s).length===0)return e;let r=!1;const n=e.map(a=>{const i=Go(a,s),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>Go(u,s)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function Fc(e,s){if(!s)return null;for(const r of e){if(r.sessionId===s&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal";for(const n of r.childSessions||[])if(n.id===s&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal"}return null}function Jp(e,s){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,i]of Object.entries(e))Fc(s,a)===i&&(delete n[a],r=!0);return r?n:e}function Zp({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{Zi()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:jc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Lu(a),o.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(l=>{const u=Date.now(),p={};for(const[m,f]of Object.entries(l))u-f<5e3&&(p[m]=f);return Object.keys(p).length===Object.keys(l).length?l:p})},5500);return()=>clearTimeout(c)},[s,r]),o.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const u=l.filter(p=>p.timestamp>c).slice(-100);return u.length===l.length?l:u})},6e4);return()=>clearInterval(i)},[n]),null}function ef(e){const s=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of s){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 Bn(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==s[r])return!1;return!0}function tf(e){let s=2166136261;for(let r=0;r<e.length;r+=1)s^=e.charCodeAt(r),s=Math.imul(s,16777619)>>>0;return s.toString(16).padStart(8,"0")}function qo(e){if(!e)return"";const s=Array.isArray(e.messages)?e.messages:[],r=s[s.length-1],n=r?tf($s(r.content)):"";return[e.id||"",e.title||"",e.status||"",s.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 sf(e){const s=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.lastUpdated||""),qo(e.activeChat),...s.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastUpdated||""),qo(r.activeChat)].join(":"))].join("|")}function rf(e,s){const r=Date.now();return e.map(n=>{const a=s[n.tabKey];return a&&r-a<5e3?{...n,messages:[],title:""}:n})}function nf(e,s){const r=[],n=e.sessionId||e.instanceId;r.push({key:e.id,ref:s[e.id]}),n&&r.push({key:n,ref:s[n]});for(const a of e.childSessions||[]){const i=a.id||a.providerType,c=`${e.id}:${i}`;r.push({key:c,ref:s[c]}),r.push({key:a.id,ref:s[a.id]})}return r}function af(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r].key!==s[r].key||e[r].ref!==s[r].ref)return!1;return!0}function of(e,s){const r=new Map;for(const n of e){const a=s.get(n.routeId)||n;for(const i of ss({routeId:n.routeId}))r.set(i,a);for(const i of ss({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of ss({tabKey:n.tabKey}))r.set(i,n)}return r}function cf(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function lf(e){const s=cf(e);if(!s)return`empty:${e.messages.length}`;if(s.id)return`id:${String(s.id)}`;if(s._localId)return`local:${String(s._localId)}`;const r=String(s.role||""),n=$s(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function df({ides:e,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:a}){const i=o.useMemo(()=>ef(e),[e]),c=o.useMemo(()=>Ac(e),[e]),l=o.useRef([]),u=o.useRef([]),p=o.useRef([]),m=o.useRef(new Map),f=o.useRef(new Map),g=o.useMemo(()=>{const k=new Map,I=[];for(const E of i){const{connectionState:T="new",machineName:L}=Mc(E,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),M=nf(E,r),W=sf(E),U=m.current.get(E.id);if(U&&U.ide===E&&U.sourceSignature===W&&U.connectionState===T&&U.machineName===L&&af(U.localRefs,M)){k.set(E.id,U),I.push(...U.conversations);continue}const C=Fa(E,r,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),R={ide:E,sourceSignature:W,connectionState:T,machineName:L,localRefs:M,conversations:C};k.set(E.id,R),I.push(...C)}m.current=k;const j=new Map,v=E=>{const T=lf(E),L=f.current.get(E.tabKey);if(L&&L.signature===T)return j.set(E.tabKey,L),L.timestamp;const M={signature:T,timestamp:ic(E)||(L==null?void 0:L.timestamp)||0};return j.set(E.tabKey,M),M.timestamp},x=[...I].sort((E,T)=>cc(E,T,v));return f.current=j,x},[i,r,s,c]),w=o.useMemo(()=>{const k=rf(g,n);return Bn(l.current,k)?l.current:(l.current=k,k)},[g,n]),A=o.useMemo(()=>{const k=new Map,I=Array.from(new Set(w.map(j=>j.routeId)));for(const j of I){const v=Ot(w,j);v&&k.set(j,v)}return k},[w]),d=o.useMemo(()=>{const k=new Map;for(const I of w){const j=A.get(I.routeId),v=I.streamSource==="native"&&j?j:I;for(const x of ss({providerSessionId:I.providerSessionId,sessionId:I.sessionId}))k.set(x,v)}return k},[w,A]),b=o.useMemo(()=>of(w,A),[w,A]),y=o.useCallback(k=>{if(k)return d.get(k)},[d]),h=o.useCallback(k=>{if(k)return b.get(k)},[b]),N=o.useMemo(()=>{const k=w.filter(I=>!Ya(a,I));return Bn(u.current,k)?u.current:(u.current=k,k)},[w,a]),_=o.useMemo(()=>{const k=N.map(I=>I.tabKey);return Bn(p.current,k)?p.current:(p.current=k,k)},[N]);return{chatIdes:i,conversations:w,visibleConversations:N,visibleTabKeys:_,resolveConversationBySessionId:y,resolveConversationByTarget:h}}function uf({isMobile:e,urlActiveTab:s,resolveConversationBySessionId:r,setSearchParams:n}){const a=o.useMemo(()=>{var l;return e||!s?null:((l=r(s))==null?void 0:l.tabKey)??null},[e,r,s]),i=o.useMemo(()=>{var l;return!e||!s?null:((l=r(s))==null?void 0:l.tabKey)??null},[e,r,s]),c=o.useCallback(()=>{s&&n(l=>{const u=new URLSearchParams(l);return u.delete("activeTab"),u},{replace:!0})},[n,s]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function mf({ides:e,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:a}){o.useEffect(()=>{st.setIdes(e)},[e]),o.useEffect(()=>{st.setResolveAction((i,c,l)=>{s(i,c,l).catch(()=>{})})},[s]),o.useEffect(()=>{const i=st.onToast(u=>{r(m=>m.some(g=>g.message===u.message&&u.timestamp-g.timestamp<3e3)?m:[...m.slice(-4),{id:u.id,message:u.message,type:u.type,timestamp:u.timestamp,targetKey:u.targetKey,actions:u.actions}]);const p=u.duration||5e3;setTimeout(()=>r(m=>m.filter(f=>f.id!==u.id)),p)}),c=st.onSystemMessage((u,p)=>{var w,A;const m=a(u),f=(w=p._localId)==null?void 0:w.startsWith("sys_approval_"),g=!!(m&&(m.status==="waiting_approval"||(A=m.modalButtons)!=null&&A.length||m.modalMessage));f&&g||n(d=>({...d,[u]:[...d[u]||[],p]}))}),l=st.onClearSystemMessage((u,p)=>{n(m=>{var f;return(f=m[u])!=null&&f.length?{...m,[u]:m[u].filter(g=>{var w;return!(g.role==="system"&&((w=g._localId)!=null&&w.startsWith(p)))})}:m})});return()=>{i(),c(),l()}},[r,n]),o.useEffect(()=>{const i=gc.on("status_event",c=>{st.handleRawEvent(c,"ws")});return()=>{i()}},[]),o.useEffect(()=>{var c;const i=l=>{var b;const u=l.data;if((u==null?void 0:u.type)!=="notification_action"||typeof u.action!="string"||!u.action.startsWith("approval_")||!(u.daemonId||u.targetSessionId||u.targetKey))return;const p=u.targetSessionId||u.targetKey||u.daemonId,m=a(p),f=(m==null?void 0:m.routeId)||u.daemonId;if(!f)return;const g=Number(u.buttonIndex),w=u.button||((b=m==null?void 0:m.modalButtons)==null?void 0:b[g])||"Approve",A=String(w).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),d=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(A);s(f,"resolve_action",{action:d?"approve":"reject",button:w,...Number.isFinite(g)&&{buttonIndex:g},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...u.targetSessionId&&{targetSessionId:u.targetSessionId}}).catch(y=>console.error("[SW Action] approval failed:",y))};return(c=navigator.serviceWorker)==null||c.addEventListener("message",i),()=>{var l;return(l=navigator.serviceWorker)==null?void 0:l.removeEventListener("message",i)}},[a,s])}const pf="adhdev_dashboardLayout_v1",ff="adhdev_dashboardDockview_v1",hf="adhdev_dashboardDockviewHiddenRestore_v1",Js={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Ja(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function zc(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Vc(e){return`${pf}:${e}`}function xf(e){const s=Vc(e);return Ja(s,null)}function bf(e,s){try{const r=s.groupAssignments.length===0&&s.focusedGroup===0&&Object.keys(s.groupActiveTabIds).length===0&&Object.keys(s.groupTabOrders).length===0&&s.groupSizes.length===0,n=Vc(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function Gc(e){return`${ff}:${e}`}function gf(e){const s=Gc(e);return Ja(s,null)}function yf(e,s){try{const r=Gc(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function qc(e){return`${hf}:${e}`}function vf(e){const s=qc(e);return Ja(s,{})}function wf(e,s){try{const r=qc(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function jf(){return{groupAssignments:[...Js.groupAssignments],focusedGroup:Js.focusedGroup,groupActiveTabIds:{...Js.groupActiveTabIds},groupTabOrders:{...Js.groupTabOrders},groupSizes:[...Js.groupSizes]}}function kf(){const[e]=o.useState(()=>zc(typeof window<"u"?window.innerWidth:1280)),[s,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,u]=o.useState({}),[p,m]=o.useState([]),[f,g]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[w,A]=o.useState(!1),d=o.useCallback(()=>{if(w)return;const b=xf(e)??jf();r(new Map(b.groupAssignments)),a(b.focusedGroup),c(b.groupActiveTabIds),u(b.groupTabOrders),m(b.groupSizes),A(!0)},[w,e]);return o.useEffect(()=>{w&&bf(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:p})},[w,e,s,n,i,l,p]),o.useEffect(()=>{const b=window.matchMedia("(max-width: 767px)"),y=h=>g(h.matches);return b.addEventListener("change",y),()=>b.removeEventListener("change",y)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:a,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:l,setGroupTabOrders:u,groupSizes:p,setGroupSizes:m,isMobile:f,hasHydratedStoredLayout:w,hydrateStoredLayout:d}}function Sf(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=Ia(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Nf({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:l,setSearchParams:u,historyModalOpen:p,activeConv:m,isRefreshingHistory:f,ides:g,handleRefreshHistory:w}){const A=o.useRef(!1),d=o.useRef(!1),b=o.useRef(null),y=o.useRef(!1);o.useEffect(()=>{if(!e||A.current||s.length===0)return;if(!a){i();return}const h=r(e);if(!h)return;const N=n.get(h.tabKey)??0;c(_=>({..._,[N]:h.tabKey})),l(N),A.current=!0,d.current=!0,b.current!=null&&(window.clearTimeout(b.current),b.current=null),u(_=>{const k=new URLSearchParams(_);return k.delete("activeTab"),k},{replace:!0})},[e,s,r,n,a,i,c,l,u]),o.useEffect(()=>{if(!(d.current||a)&&s.length!==0){if(!e){i(),d.current=!0;return}if(A.current){d.current=!0;return}if(b.current==null)return b.current=window.setTimeout(()=>{b.current=null,!(d.current||a)&&(i(),d.current=!0)},1500),()=>{b.current!=null&&(window.clearTimeout(b.current),b.current=null)}}},[e,s.length,a,i]),o.useEffect(()=>{if(!p){y.current=!1;return}if(!m||y.current||f)return;const h=g.find(N=>N.id===m.routeId);h&&(!h.chats||h.chats.length===0||Sf(h.chats,m))&&(y.current=!0,w())},[p,m,f,g,w]),o.useEffect(()=>{if(!m)return;let h=null,N=0,_=-1,k=0;const I=()=>{h=null;const j=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(x=>x.offsetParent!==null);if(j.length===0){N<18&&(N+=1,h=requestAnimationFrame(I));return}let v=0;for(const x of j)x.scrollTop=x.scrollHeight,v+=x.scrollHeight;v===_?k+=1:(k=0,_=v),N+=1,!(k>=2||N>=18)&&(h=requestAnimationFrame(I))};return h=requestAnimationFrame(I),()=>{h!=null&&cancelAnimationFrame(h)}},[m==null?void 0:m.tabKey])}function Cf({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[u,p]=o.useState(null),[m,f]=o.useState(null),g=o.useMemo(()=>{if(e||!n)return null;const y=l(n);return y&&!tt(y)&&!Ze(y)?y:null},[e,n,l]),w=o.useMemo(()=>{const y=u==null?void 0:u.routeId;if(!y)return null;const h=u!=null&&u.tabKey?i.find(N=>N.tabKey===u.tabKey):a?i.find(N=>N.tabKey===a):null;return(h==null?void 0:h.routeId)===y?h:Ot(i,y)},[i,u,a]),A=o.useMemo(()=>{if(w)return c.find(y=>y.id===w.routeId)},[c,w]);o.useEffect(()=>{g&&(p({routeId:g.routeId,tabKey:Ro(g)}),f(g),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,g]);const d=o.useCallback(y=>{y&&(p({routeId:y.routeId,tabKey:Ro(y)}),f(y))},[]),b=o.useCallback(()=>{p(null),f(null)},[]);return{remoteDialogConv:w,remoteDialogIdeEntry:A,remoteDialogActiveConv:m,setRemoteDialogActiveConv:f,openRemoteDialog:d,closeRemoteDialog:b}}function Wn(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0];if((r==null?void 0:r.active)===!0)return!0;const n=Ia(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Yo({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:a,setLocalUserMessages:i,setClearedTabs:c}){const[l,u]=o.useState(!1),[p,m]=o.useState(!1),f=o.useCallback(async d=>{try{await e("standalone","launch_ide",{ideType:d,enableCdp:!0})}catch(b){console.error("Launch failed",b)}},[e]),g=o.useCallback(async(d,b)=>{try{const y=d||(s==null?void 0:s.daemonId)||"",h=await e(y,"switch_chat",{id:b,sessionId:b,...Rs(s)}),N=h==null?void 0:h.result;if((h==null?void 0:h.success)===!0||N==="switched"||N==="switched-by-title")return;N===!1||N==="not_found"?Xs(a,"⚠️ Session tab not found — try refreshing history"):typeof N=="string"&&N.startsWith("error:")?Xs(a,`⚠️ Switch error: ${N}`):Xs(a,"⚠️ Session switch failed")}catch(y){console.error("Switch failed",y),Xs(a,`❌ Switch failed: ${y.message||"connection error"}`)}},[s,e,a]),w=o.useCallback(async()=>{if(!(!s||l)){u(!0);try{const d=fr(s);await e(d,"new_chat",{...Rs(s)}),c(b=>({...b,[s.tabKey]:Date.now()})),i(b=>({...b,[s.tabKey]:[]}))}catch(d){console.error("New chat failed",d)}finally{u(!1)}}},[s,l,e,c,i]),A=o.useCallback(async()=>{var d,b;if(!(!s||p)){m(!0);try{const y=fr(s),h=async()=>e(y,"list_chats",{forceExpand:!0,...Rs(s)});let N=await h(),_=(N==null?void 0:N.chats)||((d=N==null?void 0:N.result)==null?void 0:d.chats);Wn(_,s)&&(await new Promise(k=>setTimeout(k,450)),N=await h(),_=(N==null?void 0:N.chats)||((b=N==null?void 0:N.result)==null?void 0:b.chats)),N!=null&&N.success&&Array.isArray(_)&&(n(s.routeId,_),Wn(_,s)&&!Wn(r,s)&&Xs(a,"⚠️ History dialog did not fully open — try once more"))}catch(y){console.error("Refresh history failed",y)}finally{m(!1)}}},[s,r,p,e,n,a]);return{isCreatingChat:l,isRefreshingHistory:p,handleLaunchIde:f,handleSwitchSession:g,handleNewChat:w,handleRefreshHistory:A}}function If(e,s){if(e.size!==s.size)return!1;for(const[r,n]of e)if(s.get(r)!==n)return!1;return!0}function Af(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function Xo(e,s){const r=Object.keys(e),n=Object.keys(s);return r.length!==n.length?!1:r.every(a=>s[Number(a)]===e[Number(a)])}function $r(e,s){const r=new Set(s),n=s.length>0?[0]:[];for(const[c,l]of e)!r.has(c)||l<=0||n.includes(l)||n.push(l);n.sort((c,l)=>c-l);const a={};n.forEach((c,l)=>{a[c]=l}),n.length===0&&(a[0]=0);const i=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const u=a[l];typeof u=="number"&&u>0&&i.set(c,u)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function Qo(e,s){const r={};for(const[n,a]of Object.entries(e)){const i=s[Number(n)];typeof i=="number"&&(r[i]=a)}return r}function Mf(e,s,r){if(s.length===0)return 0;if(typeof r[e]=="number")return r[e];const n=[...s].reverse().find(a=>a<e)??s[0];return r[n]??0}function Tf(e,s,r){if(s.length<=1)return[];const n=s.map(c=>e[c]).filter(c=>Number.isFinite(c)),a=n.length===s.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 Jo(e,s){const r={};for(const[n,a]of Object.entries(e)){const i=Number(n);r[i>=s?i+1:i]=a}return r}function Zo(e){return Array(e).fill(100/e)}function Lf({groupAssignments:e,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:a,groupSizes:i,setGroupSizes:c,isMobile:l,visibleConversations:u,visibleTabKeys:p}){const m=o.useRef(null),f=o.useMemo(()=>$r(e,p),[e,p]),g=f.assignments,w=o.useMemo(()=>l?1:f.groupCount,[f.groupCount,l]),A=w>1,d=o.useCallback((k,I)=>{s(j=>{const v=new Map($r(j,p).assignments);return I===0?v.delete(k):v.set(k,I),v}),n(j=>({...j,[I]:k})),r(I)},[s,p,n,r]),b=o.useCallback(k=>{s(I=>{const j=$r(I,p).assignments,v=new Map;for(const[x,E]of j)E!==k&&(E>k?v.set(x,E-1):v.set(x,E));return v}),c(I=>{if(I.length<=1)return[];const j=[...I];j.splice(k,1);const v=j.reduce((x,E)=>x+E,0);return v>0?j.map(x=>x/v*100):[]}),r(0)},[s,p,c,r]),y=o.useCallback((k,I)=>{I.preventDefault();const j=m.current;if(!j)return;const v=I.clientX,x=j.offsetWidth,E=i.length===w?[...i]:Zo(w),T=M=>{const U=(M.clientX-v)/x*100,C=[...E];C[k]=Math.max(15,E[k]+U),C[k+1]=Math.max(15,E[k+1]-U),c(C)},L=()=>{document.removeEventListener("mousemove",T),document.removeEventListener("mouseup",L),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",T),document.addEventListener("mouseup",L)},[i,w,c]),h=o.useCallback((k,I,j)=>{if(w>=4)return;const v=j==="left"?I:I+1;s(x=>{const E=$r(x,p).assignments,T=new Map;for(const L of u){const M=E.get(L.tabKey)??0,W=M>=v?M+1:M;W>0&&T.set(L.tabKey,W)}return v>0&&T.set(k,v),T}),c(x=>{const E=x.length===w?[...x]:Zo(w),T=E[I]??100/w,L=Math.max(15,T/2),M=Math.max(15,T/2),W=[...E];W[I]=L,W.splice(v,0,M);const U=W.reduce((C,R)=>C+R,0);return W.map(C=>C/U*100)}),n(x=>{const E=Jo(x,v);return E[v]=k,E}),a(x=>{const E=Jo(x,v);return E[v]=[k],E}),r(v)},[w,s,p,u,c,n,a,r]);o.useEffect(()=>{If(e,g)||s(g)},[e,g,s]),o.useEffect(()=>{const{mapping:k,usedGroups:I}=f;n(j=>{const v=Qo(j,k);return Xo(j,v)?j:v}),a(j=>{const v=Qo(j,k);return Xo(j,v)?j:v}),r(j=>{const v=l?0:Mf(j,I,k);return j===v?j:v}),c(j=>{const v=l?[]:Tf(j,I,f.groupCount);return Af(j,v)?j:v})},[f,l,n,a,r,c]);const N=o.useMemo(()=>{const k=Array.from({length:w},()=>[]);for(const I of u){const j=g.get(I.tabKey)??0,v=Math.min(j,w-1);k[v].push(I)}return k},[u,g,w]),_=o.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:m,normalizedGroupAssignments:g,numGroups:w,isSplitMode:A,groupedConvs:N,moveTabToGroup:d,closeGroup:b,handleResizeStart:y,splitTabRelative:h,clearAllSplits:_}}function _f({ides:e,sendDaemonCommand:s}){const r="0.8.83",n=o.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:Ec(m,r)).sort((m,f)=>Number(or(f,r))-Number(or(m,r))),[r,e]),a=o.useMemo(()=>n.some(m=>or(m,r)),[r,n]),[i,c]=o.useState(!1),[l,u]=o.useState({}),p=o.useCallback(async m=>{var f,g;u(w=>({...w,[m]:"upgrading"}));try{const w=await s(m,"daemon_upgrade",{});(f=w==null?void 0:w.result)!=null&&f.upgraded||(g=w==null?void 0:w.result)!=null&&g.success?u(A=>({...A,[m]:"done"})):u(A=>({...A,[m]:"error"}))}catch{u(w=>({...w,[m]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:p}}const ha="adhdev_dashboard_notifications_v2",xa="adhdev_dashboard_notifications_v1",wr=80;function Xr(e,s=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:s}function Za(e){return{...e,createdAt:Xr(e.createdAt),updatedAt:Xr(e.updatedAt,e.createdAt),lastEventAt:Xr(e.lastEventAt,e.updatedAt||e.createdAt)}}function Rf(e){const s=Aa(e);return s==="unknown:"?e.id:s}function ei(e){return[e.type,Ui(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Pf(e,s,r,n){var c;const a=Date.now(),i=[];for(const l of e){const u=l.sessionId?s.get(l.sessionId):void 0;if(u!=null&&u.surfaceHidden)continue;const p=ei({type:"task_complete",sessionId:l.sessionId,providerSessionId:l.providerSessionId,tabKey:l.tabKey,lastMessageHash:l.lastMessageHash,lastMessageAt:l.lastMessageAt,lastUpdated:(u==null?void 0:u.lastUpdated)||l.lastUpdated}),m=!!((c=n==null?void 0:n.get(p))!=null&&c.forceUnread),f=fn(l,s,{notificationStateBySessionId:r}),g=f.inboxBucket==="needs_attention"?"needs_attention":f.inboxBucket==="task_complete"&&f.unread||(u==null?void 0:u.inboxBucket)==="task_complete"&&m?"task_complete":null;if(!g)continue;const w=Xr(l.lastMessageAt||(u==null?void 0:u.lastUpdated)||l.lastUpdated,a),A=g==="task_complete"?p:ei({type:g,sessionId:l.sessionId,providerSessionId:l.providerSessionId,tabKey:l.tabKey,lastMessageHash:l.lastMessageHash,lastMessageAt:l.lastMessageAt,lastUpdated:(u==null?void 0:u.lastUpdated)||l.lastUpdated});i.push(Za({id:A,dedupKey:A,type:g,routeId:l.routeId,machineId:l.daemonId||l.routeId,sessionId:l.sessionId,providerSessionId:l.providerSessionId,tabKey:l.tabKey,title:nc(l),preview:em(l),createdAt:w,updatedAt:w,lastEventAt:w}))}return i.sort((l,u)=>u.updatedAt-l.updatedAt)}function Df(e,s=wr){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=Rf(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,s))}function Ef(e){return e.filter(s=>typeof s.readAt=="number"||typeof s.deletedAt=="number").map(s=>({id:s.id,...typeof s.readAt=="number"?{readAt:s.readAt}:{},...typeof s.deletedAt=="number"?{deletedAt:s.deletedAt}:{}}))}function $f(e){return new Map(e.map(s=>[s.id,s]))}function Yc(e,s,r=wr){const n=new Map;for(const i of s)n.set(i.id,i);const a=e.map(i=>{const c=Za(i),l=n.get(c.id);return{...c,...typeof(l==null?void 0:l.readAt)=="number"?{readAt:l.readAt}:{},...typeof(l==null?void 0:l.deletedAt)=="number"?{deletedAt:l.deletedAt}:{}}});return Df(a,r)}function Kf(e,s,r=wr){const n=new Set(Yc(s,[],r).map(a=>a.id));return e.filter(a=>n.has(a.id)).slice(0,Math.max(0,r))}function Bf(e,s,r=Date.now()){const n=e.filter(a=>a.id!==s);return n.push({id:s,readAt:r}),n}function Wf(e,s){const r=e.filter(n=>n.id!==s);return r.push({id:s,forceUnread:!0}),r}function Of(e,s,r,n=Date.now()){const a=e.filter(i=>{const c=s.find(l=>l.id===i.id);return!c||!ur(c,r)});for(const i of s)ur(i,r)&&a.push({id:i.id,readAt:n});return a}function Hf(e,s){const r=e.filter(n=>n.id!==s);return r.push({id:s,deletedAt:Date.now()}),r}function Uf(e){return e.filter(s=>!s.readAt&&!s.deletedAt).length}function Ff(e){const s=new Map;for(const r of e){if(r.deletedAt)continue;const n=ss(r);if(n.length===0)continue;const a=r.readAt?0:1;for(const i of n){const c=s.get(i);if(!c){s.set(i,{unreadCount:a,latestNotificationAt:r.updatedAt,latestRecordId:r.id});continue}s.set(i,{unreadCount:c.unreadCount+a,latestNotificationAt:Math.max(c.latestNotificationAt,r.updatedAt),latestRecordId:c.latestNotificationAt>=r.updatedAt?c.latestRecordId:r.id})}}return s}function zf(){if(typeof window>"u")return[];const e=s=>{if(!s||typeof s!="object")return null;const r=s;if(typeof r.id!="string"||r.id.length===0)return null;const n=typeof r.readAt=="number"&&Number.isFinite(r.readAt)?r.readAt:void 0,a=typeof r.deletedAt=="number"&&Number.isFinite(r.deletedAt)?r.deletedAt:void 0,i=r.forceUnread===!0;return typeof n!="number"&&typeof a!="number"&&!i?null:{id:r.id,...typeof n=="number"?{readAt:n}:{},...typeof a=="number"?{deletedAt:a}:{},...i?{forceUnread:!0}:{}}};try{const s=window.localStorage.getItem(ha),r=s?JSON.parse(s):[];if(Array.isArray(r))return r.map(e).filter(n=>!!n)}catch{}try{const s=window.localStorage.getItem(xa),r=s?JSON.parse(s):[];return Array.isArray(r)?Ef(r.map(n=>Za(n)).filter(n=>!n.deletedAt)):[]}catch{return[]}}function Vf(e){if(!(typeof window>"u"))try{const s=e.filter(r=>typeof r.readAt=="number"||typeof r.deletedAt=="number"||r.forceUnread===!0).slice(0,wr);if(s.length===0){window.localStorage.removeItem(ha),window.localStorage.removeItem(xa);return}window.localStorage.setItem(ha,JSON.stringify(s)),window.localStorage.removeItem(xa)}catch{}}function Gf(e,s){return e===s?!0:e.length!==s.length?!1:e.every((r,n)=>{const a=s[n];return a?r.id===a.id&&r.readAt===a.readAt&&r.deletedAt===a.deletedAt&&r.forceUnread===a.forceUnread:!1})}function qf(e){const{conversations:s,liveSessionInboxState:r,maxItems:n=wr}=e,[a,i]=o.useState(()=>zf()),c=o.useMemo(()=>$f(a),[a]),l=o.useMemo(()=>Pf(s,r,void 0,c),[s,r,c]),u=o.useMemo(()=>Yc(l,a,n),[l,a,n]),p=o.useMemo(()=>Ff(u),[u]);o.useEffect(()=>{i(d=>{const b=Kf(d,l,n);return Gf(d,b)?d:b})},[l,n]),o.useEffect(()=>{Vf(a)},[a]);const m=o.useMemo(()=>Uf(u),[u]),f=o.useCallback((d,b)=>{i(y=>Bf(y,d,b))},[]),g=o.useCallback(d=>{i(b=>Wf(b,d))},[]),w=o.useCallback((d,b)=>{i(y=>Of(y,u,d,b))},[u]),A=o.useCallback(d=>{i(b=>Hf(b,d))},[]);return{notifications:u,unreadCount:m,notificationStateBySessionId:p,markRead:f,markUnread:g,markTargetRead:w,deleteNotification:A}}function Xc(){return"select_session"}function Yf(){return"open_panel"}function Xf({hasMessage:e,blockedMessage:s}){return e?!!s:!0}function Qf(e,s,r=2e3){return e?e.tabKey===s.tabKey&&e.message===s.message&&s.timestamp-e.timestamp<r:!1}function ti(e,s){return e?e.tabKey===s.tabKey&&e.message===s.message&&e.timestamp===s.timestamp?null:e:null}function si(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function eo(e){return e instanceof Error?e.message:String(e||"")}function ri(e){const s=eo(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function ni(e,s){const r=eo(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function xn({sendDaemonCommand:e,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:a}){const[i,c]=o.useState(!1),[l,u]=o.useState(!1),[p,m]=o.useState(null),f=o.useRef(!1),g=o.useRef(null);o.useEffect(()=>{m(null)},[s==null?void 0:s.tabKey]);const w=o.useCallback(async y=>{if(!s)return!1;const h=y.trim(),N=Ea(s);if(Xf({hasMessage:!!h,blockedMessage:N,sendInFlight:f.current}))return N&&m(N),!1;const _=Date.now(),k={tabKey:s.tabKey,message:h,timestamp:_};if(Qf(g.current,k))return m(null),!0;f.current=!0,u(!0),m(null),g.current=k;const I=`${_}-${Math.random().toString(36).slice(2,8)}`,j={role:"user",content:h,timestamp:_,_localId:I},v=!0;r(x=>({...x,[k.tabKey]:[...x[k.tabKey]||[],j]}));try{const x=fr(s);if(!x)return g.current=ti(g.current,k),v&&r(L=>({...L,[k.tabKey]:(L[k.tabKey]||[]).filter(M=>M._localId!==I)})),m("Unable to send message right now."),!1;const E=await e(x,"send_chat",{message:h,...Rs(s)}),T=si(E);if(v&&(T!=null&&T.deduplicated))return r(L=>({...L,[k.tabKey]:(L[k.tabKey]||[]).filter(M=>M._localId!==I)})),m(null),!0;if((T==null?void 0:T.sent)===!1)throw new Error((T==null?void 0:T.error)||"Send failed");if((T==null?void 0:T.success)===!1)throw new Error((T==null?void 0:T.error)||"Send failed");return setTimeout(()=>{const L=Date.now()-6e4;r(M=>{const W=M[k.tabKey];if(!W)return M;const U=W.filter(C=>C.timestamp>L);return U.length===W.length?M:{...M,[k.tabKey]:U}})},6e4),m(null),!0}catch(x){const E=eo(x);return E.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",E):console.warn("Send blocked/failed",x),g.current=ti(g.current,k),r(T=>({...T,[k.tabKey]:(T[k.tabKey]||[]).filter(L=>L._localId!==I)})),m(vm(x)),!1}finally{f.current=!1,u(!1)}},[s,e,n,r]),A=o.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await e(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(y){console.error("Relaunch failed",y)}},[s,e]),d=o.useCallback(async y=>{if(s)try{const N=(s.modalButtons||[]).indexOf(y),_=y.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(_),I=fr(s);if(!I)return;const j=await e(I,"resolve_action",{button:y,action:k?"approve":"reject",...N>=0&&{buttonIndex:N},...Rs(s)}),v=si(j);v.success||n(x=>[...x,{routeId:s.tabKey,text:ni(y,v==null?void 0:v.error),timestamp:Date.now()}])}catch(h){ri(h)||console.error("[ModalButton] Error:",h),n(N=>[...N,{routeId:s.tabKey,text:ri(h)?ni(y,h):`❌ **${y}** error`,timestamp:Date.now()}])}},[s,e,n]),b=o.useCallback(async()=>{if(!(!s||i)){c(!0);try{await e(s.routeId,Yf(),{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(y){console.error("Focus agent failed",y)}finally{c(!1)}}},[s,i,e]);return{isSendingChat:l,sendFeedbackMessage:p,isFocusingAgent:i,handleSendChat:w,handleRelaunch:A,handleModalButton:d,handleFocusAgent:b}}const to=o.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m=null,handleFocusAgent:f,isFocusingAgent:g,actionLogs:w,userName:A,scrollToBottomRequestNonce:d,isInputActive:b=!0}){const y=Oc(s),h=y.status||y.modalMessage||y.modalButtons?{...s,...y.status?{status:y.status}:{},...y.modalMessage!==void 0?{modalMessage:y.modalMessage}:{},...y.modalButtons!==void 0?{modalButtons:y.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(Vi,{activeConv:h,onModalButton:c}),h.transport!=="pty"&&h.transport!=="acp"&&h.cdpConnected===!1?t.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:t.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:[t.jsx("span",{className:"text-sm",children:t.jsx(vs,{size:14})}),t.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),t.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,h.transport==="pty"?t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{display:n?"flex":"none",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(Vm,{activeConv:h,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m,isVisible:n})}),!n&&t.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(da,{activeConv:h,ideEntry:a,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:w,userName:A,scrollToBottomRequestNonce:d,isInputActive:b})})]}):t.jsx(da,{activeConv:h,ideEntry:a,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:w,userName:A,scrollToBottomRequestNonce:d,isInputActive:b})]})},(e,s)=>e.activeConv===s.activeConv&&e.isCliTerminal===s.isCliTerminal&&e.ideEntry===s.ideEntry&&e.terminalRef===s.terminalRef&&e.handleModalButton===s.handleModalButton&&e.handleRelaunch===s.handleRelaunch&&e.handleSendChat===s.handleSendChat&&e.isSendingChat===s.isSendingChat&&e.sendFeedbackMessage===s.sendFeedbackMessage&&e.handleFocusAgent===s.handleFocusAgent&&e.isFocusingAgent===s.isFocusingAgent&&e.actionLogs===s.actionLogs&&e.userName===s.userName&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&e.isInputActive===s.isInputActive);function Jf({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:u,onBack:p,onOpenNativeConversation:m,onOpenMachine:f,onOpenHistory:g,onOpenRemote:w,onHideConversation:A,onStopCli:d,cliViewMode:b,onSetCliViewMode:y,handleSendChat:h,handleFocusAgent:N,handleModalButton:_,handleRelaunch:k}){const I=o.useRef(null),j=tt(e)&&!s,v=j&&b==="terminal",x=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:`flex items-center justify-between gap-3 ${x} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:t.jsx(ja,{size:18})}),t.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:lt(e)}),t.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:t.jsx(dc,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>m(e),onOpenMachine:()=>f(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[j&&b&&t.jsx(Ka,{mode:b,onChange:y,compact:!0}),j&&d&&t.jsx("button",{onClick:()=>{d(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:t.jsx(At,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:t.jsx(Sa,{size:14})}),!s&&!j&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>w(e),type:"button",children:t.jsx(Rt,{size:14})}),A&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>A(e),type:"button",title:"Close chat",children:t.jsx(At,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(to,{activeConv:e,clearToken:0,isCliTerminal:v,ideEntry:n,terminalRef:I,handleModalButton:_,handleRelaunch:k,handleSendChat:h,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:N,isFocusingAgent:u,actionLogs:a,userName:i})})]})}const On={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 Zf(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Qc(){const[e,s]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{s(Zf())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(On[c].cmd).catch(()=>{}),i(!0),setTimeout(()=>i(!1),2e3)},[c]);return t.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:[t.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[t.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:()=>s("unix"),children:"🍎🐧 macOS / Linux"}),t.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:()=>s("windows"),children:"🪟 Windows"})]}),e==="windows"&&t.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[t.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"}),t.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"})]}),t.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:l,title:"Click to copy",children:[t.jsx("span",{className:"text-text-muted select-none",children:On[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:On[c].cmd}),t.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:a?"✓":"📋"})]}),t.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",t.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function Jc({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:Rt},{key:"chats",label:"Chats",icon:Qt}];return t.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:t.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 t.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:()=>s(n),type:"button","aria-pressed":c,children:[t.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:t.jsx(i,{size:15})}),t.jsx("span",{children:a})]},n)})})})}function Kr({title:e,className:s=""}){return t.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${s}`,children:t.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function Cs({children:e,className:s=""}){return t.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)] ${s}`,children:e})}function Zs({icon:e,title:s,subtitle:r,children:n}){return t.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:[t.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}),t.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:s}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function Br({item:e,type:s,getAvatarText:r,onOpenConversation:n}){const a=s==="needs_attention"||s==="task_complete",i=s==="working",c=s==="earlier",l=s==="task_complete",{isReconnecting:u,isConnecting:p}=zs(e.conversation),m=lt(e.conversation),f=ks(e.conversation),g=wc(e.conversation,{requiresAction:s==="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",A=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",d=c?"text-text-secondary":"text-text-primary",b=c?"text-text-muted":"text-text-secondary",y=c?"text-text-secondary opacity-80":"text-text-muted",h=c?"text-text-muted opacity-80":"text-text-muted",N="text-[color:var(--status-warning)]";return t.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?t.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,t.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${A}`,style:a?{color:"var(--accent-on-primary)"}:void 0,children:r(m)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${d}`,children:m}),!i&&t.jsx("span",{className:`text-[11px] font-medium shrink-0 ${h}`,children:zi(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${b}`,children:[f,u?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${N} animate-pulse`,children:"Reconnecting…"})]}):p?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):g==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:N,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${y}`,children:e.preview})]}),a&&!l&&t.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),l&&t.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&&t.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 ai({size:e=32,label:s}){return t.jsxs("div",{className:"flex flex-col items-center gap-2.5",children:[t.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}}),s&&t.jsx("div",{className:"text-xs font-semibold text-accent-primary-light tracking-tight",children:s})]})}function eh({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:u,onShowConversation:p,onShowAllHidden:m,onOpenNewSession:f,onOpenMachine:g,onOpenSettings:w,onSectionChange:A,wsStatus:d="connected",isStandalone:b=!1}){const y=d==="disconnected"||d==="reconnecting"||d==="offline"||d==="auth_failed",h=c.length>0,N=s.length>0||r.length>0||n.length>0||a.length>0,_=e==="machines"?"Machines":"Chats",k=b?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",I=b?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]";return t.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[t.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${k}`,children:t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:_}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(s.length>0||r.length>0)&&t.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:[t.jsx(mn,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.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:t.jsx(dn,{size:18})})]})]})}),t.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${I}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:y?t.jsx(Zs,{icon:t.jsx(ai,{label:"Reconnecting…"}),title:"Connecting to server",subtitle:d==="offline"?"Your device appears to be offline. Waiting for network…":d==="auth_failed"?"Session expired. Please log in again.":"Establishing connection to the server. This usually takes a moment."}):c.length===0?t.jsx(Zs,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:b?"Waiting for your daemon":"Connect your machines",subtitle:b?"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:!b&&t.jsx("div",{className:"w-full max-w-[360px] mt-4",children:t.jsx(Qc,{})})}):t.jsx(Cs,{children:c.map((j,v)=>t.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:()=>g(j.id),type:"button",children:[t.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(j.label)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:j.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:j.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[j.unread," new"]}):j.total>0?`${j.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:j.subtitle}),j.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[j.total," chat",j.total!==1?"s":"",j.unread>0?` · ${j.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},j.id))})}),e==="chats"&&s.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Kr,{title:"Needs attention",className:"mb-0"}),t.jsx(Cs,{children:s.map((j,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Br,{item:j,type:"needs_attention",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&r.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Kr,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(Cs,{children:r.map((j,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Br,{item:j,type:"task_complete",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&n.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Kr,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(Cs,{children:n.map((j,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Br,{item:j,type:"working",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&t.jsx(Kr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?t.jsx(Cs,{children:a.map((j,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Br,{item:j,type:"earlier",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))}):N?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):y?t.jsx(Zs,{icon:t.jsx(ai,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):h?t.jsx(Zs,{icon:t.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:t.jsx(Qt,{size:20})}),title:"No conversations yet",subtitle:"Your machines are available. Open a machine, wait for P2P to connect, then launch your first IDE, CLI, or ACP session."}):t.jsx(Zs,{icon:t.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&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.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:[t.jsx("span",{children:"Hidden"}),t.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:m,children:"Restore all"})]}),t.jsx(Cs,{className:"bg-bg-secondary/25",children:i.map((j,v)=>t.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:()=>p(j),type:"button",children:[t.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(lt(j))}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:lt(j)}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:ks(j)}),t.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},j.tabKey))})]})]}),e==="chats"&&f&&t.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:f,"aria-label":"Start new session",children:t.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),t.jsx(Jc,{section:e,onSectionChange:A})]})}function th(e){if(!e)return"";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(e))}catch{return new Date(e).toLocaleString()}}function Zc(e){const s=[e.workspace||"Workspace unknown"],r=ws(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=th(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function bn(...e){const s=new Set,r=[],n=a=>{const i=typeof a=="string"?a.trim():"";if(!i)return;const c=i.toLowerCase();s.has(c)||(s.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 sh(e){const s=e.trim();if(!s)return null;if(s.startsWith("~"))return s;if(/^[A-Za-z]:$/.test(s))return`${s[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(s))return`${s[0].toUpperCase()}:${s.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(s))return`${s[0].toUpperCase()}:\\${s.slice(2).replace(/[\\/]+/g,"\\")}`;const r=s.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),a=(r[2]||"").replace(/[\\/]+/g,"\\");return a?`${n}:\\${a}`:`${n}:\\`}return null}function gn(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=sh(r);if(n)return n}return"C:\\"}for(const r of s){const n=typeof r=="string"?r.trim():"";if(n)return n}return"~"}function rh(e){const s=e.replace(/[\\/]+$/,"");if(!s||s==="/"||/^[A-Za-z]:$/.test(s))return null;const r=s.includes("\\")?"\\":"/",n=s.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 nh(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function yn(e,s,r){const n=await e(s,"file_list_browse",{path:r}),a=nh(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=(p,m)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${m}`:p==="/"||p==="\\"?`${c}${m}`:`${p.replace(/[\\/]+$/,"")}${c}${m}`,u=Array.isArray(a==null?void 0:a.files)?a.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:typeof(p==null?void 0:p.path)=="string"&&p.path.trim()?p.path:l(i,p.name)})).sort((p,m)=>p.name.localeCompare(m.name)):[];return{path:i,directories:u}}function vn({title:e,description:s,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:u,onConfirm:p}){const[m,f]=o.useState(r);o.useEffect(()=>{f(r)},[r]);const g=rh(r),w=m.trim();return t.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:t.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:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.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:t.jsx(At,{size:16})})]}),t.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[t.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:()=>{!g||a||u(g)},disabled:!g||a,children:[t.jsx(ja,{size:15}),"Parent"]}),t.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"text",value:m,onChange:A=>f(A.target.value),onKeyDown:A=>{A.key!=="Enter"||!w||a||(A.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"}),t.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"})]})]})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):i?t.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):n.length===0?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):t.jsx("div",{className:"p-3",children:n.map(A=>t.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(A.path),children:[t.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:t.jsx(Es,{size:17})}),t.jsxs("span",{className:"min-w-0 flex-1",children:[t.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:A.name}),t.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:A.path})]})]},A.path))})}),t.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:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(w||r),disabled:!w&&!r||a,children:c})]})]})})}function so({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:u=!1,showArgsInput:p,argsValue:m,onArgsChange:f,showModelInput:g,modelValue:w,onModelChange:A,historyProviderNode:d,onConfirm:b,onCancel:y}){const h=n==null?void 0:n.find(N=>N.key===a);return t.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:t.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:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:y,"aria-label":"Close launch confirmation",children:t.jsx(At,{size:16})})]}),t.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&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),t.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=>t.jsx("option",{value:N.key,children:N.label},N.key))}),(h==null?void 0:h.description)&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:h.description})]}),d,r.map(N=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:N.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:N.value})]},`${N.label}:${N.value}`)),g&&A&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),t.jsx("input",{type:"text",value:w||"",onChange:N=>A(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})]}),p&&f&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),t.jsx("input",{type:"text",value:m||"",onChange:N=>f(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})]})]}),t.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:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:y,disabled:u,children:"Cancel"}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:b,disabled:u,children:[t.jsx(Na,{size:14}),u?l:c]})]})]})})}function oi(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function gs(e){const{machine:s,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 s.workspaces||[])i.push({key:`saved:${u.id}`,label:`${u.id===s.defaultWorkspaceId?"⭐ ":""}${oi(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const c=(r==null?void 0:r.trim())||"",l=c?(s.workspaces||[]).find(u=>u.path===c):null;if(c&&!l&&i.push({key:`custom:${c}`,label:oi(c),description:c,workspaceId:null,workspacePath:c}),n){const u=`saved:${n}`;if(i.some(p=>p.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 ah(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function oh(e){return[ah(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function ih(e){return e.lastLaunchedAt?pn(e.lastLaunchedAt):""}function el(e){return{metaText:oh(e),updatedLabel:ih(e)}}function Hn(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function ch({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var ze,xt,bt,ct;const c=yr(),[l,u]=o.useState(!1),p=(((ze=e.detectedIdes)==null?void 0:ze.length)||0)>0,m=o.useMemo(()=>(e.workspaces||[]).map(Te=>({id:Te.id,path:Te.path,label:Te.label})),[e]),f=e.defaultWorkspaceId||null,[g,w]=o.useState(f||((xt=m[0])==null?void 0:xt.id)||""),[A,d]=o.useState(""),[b,y]=o.useState(""),[h,N]=o.useState([]),[_,k]=o.useState(!1),[I,j]=o.useState(""),[v,x]=o.useState(!1),[E,T]=o.useState(Hn(p,s.length,r.length)),L=o.useRef(null),[M,W]=o.useState(null),U=o.useRef("__home__"),[C,R]=o.useState("__home__"),[B,S]=o.useState(""),[D,Y]=o.useState(""),[q,H]=o.useState(""),[re,ie]=o.useState([]),[Se,X]=o.useState(()=>jt().textQuery),[fe,we]=o.useState(()=>jt().workspaceQuery),[ce,he]=o.useState(()=>jt().modelQuery),[de,z]=o.useState(()=>jt().resumableOnly),[ge,ae]=o.useState(()=>jt().sortMode),[oe,ee]=o.useState(!1),[ue,se]=o.useState(!1),ke=o.useRef(null),ye=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const K=g==="__custom__"?A.trim():((bt=m.find(Te=>Te.id===g))==null?void 0:bt.path)||"",V=g==="__custom__"&&!!K&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),ve=g!=="__custom__"&&((ct=m.find(Te=>Te.id===g))==null?void 0:ct.path)||"",xe=o.useMemo(()=>(e.recentLaunches||[]).map(Te=>Te.workspace),[e]),Q=o.useCallback(async Te=>{k(!0),j("");try{const Xe=await a(Te);y(Xe.path),d(Xe.path),N(Xe.directories)}catch(Xe){j(Xe instanceof Error?Xe.message:"Could not load folder")}finally{k(!1)}},[a]),Me=o.useCallback(()=>{var Xe;w("__custom__"),x(!0);const Te=gn(e.platform,bn(A.trim(),ve,xe,e.defaultWorkspacePath,(Xe=m.find(Ue=>Ue.id===f))==null?void 0:Xe.path,m.map(Ue=>Ue.path)));Q(Te)},[A,f,Q,xe,ve,e.platform,m]),We=o.useCallback(Te=>{if(Te!=null&&Te.workspaceId){w(Te.workspaceId),d("");return}if(Te!=null&&Te.workspacePath){w("__custom__"),d(Te.workspacePath);return}w(""),d("")},[]),Pe=o.useCallback(Te=>{if(w(Te),Te==="__custom__"){Me();return}d("")},[Me]),Ke=o.useCallback(Te=>{w("__custom__"),d(Te)},[]),Je=o.useCallback((Te,Xe)=>{L.current=Xe,U.current=Te.selectedWorkspaceKey||"__home__",R(Te.selectedWorkspaceKey||"__home__"),S(Te.initialArgs||""),Y(Te.initialModel||""),H(""),ie([]);const Ue=Te.providerType?`${e.id}:${Te.providerType}`:null;if(Xm(ye.current,Ue)){const Fe=jt();X(Fe.textQuery),we(Fe.workspaceQuery),he(Fe.modelQuery),z(Fe.resumableOnly),ae(Fe.sortMode)}ye.current=Ue,W(Te),Te.providerType&&i&&(ee(!0),i(Te.providerType).then(Fe=>ie(Fe||[])).catch(Fe=>console.warn("Failed to load saved sessions",Fe)).finally(()=>ee(!1)))},[i,e.id]),Ge=o.useMemo(()=>Sc(re,{textQuery:Se,workspaceQuery:fe,modelQuery:ce,resumableOnly:de,sortMode:ge}),[ce,de,re,ge,Se,fe]);o.useEffect(()=>{q&&(Ge.some(Te=>Te.providerSessionId===q)||H(""))},[Ge,q]);const ut=o.useCallback(()=>{L.current&&(se(!0),L.current().finally(()=>{L.current=null,se(!1),W(null)}))},[]),it=o.useCallback(()=>{L.current=null,W(null)},[]),ht=o.useCallback(Te=>{U.current=Te,R(Te)},[]);return o.useEffect(()=>{var Te;ke.current!==e.id&&(ke.current=e.id,w(f||((Te=m[0])==null?void 0:Te.id)||"__custom__"),d(""),y(""),N([]),j(""),x(!1),X(jt().textQuery),we(jt().workspaceQuery),he(jt().modelQuery),z(jt().resumableOnly),ae(jt().sortMode),ye.current=null,T(Hn(p,s.length,r.length)))},[r.length,s.length,f,p,e.id,m]),o.useEffect(()=>{var Te;g!=="__custom__"&&(g&&m.some(Xe=>Xe.id===g)||w(f||((Te=m[0])==null?void 0:Te.id)||"__custom__"))},[f,g,m]),o.useEffect(()=>{E==="ide"&&p||E==="cli"&&s.length>0||E==="acp"&&r.length>0||T(Hn(p,s.length,r.length))},[E,r.length,s.length,p]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:p,workspaceRows:m,defaultWorkspaceId:f,workspaceChoice:g,customWorkspacePath:A,browseCurrentPath:b,browseDirectories:h,browseBusy:_,browseError:I,browseDialogOpen:v,activeLauncherKind:E,launchConfirm:M,launchConfirmWorkspaceKeyRef:U,launchConfirmWorkspaceKey:C,launchConfirmArgs:B,launchConfirmModel:D,launchConfirmResumeId:q,launchConfirmSavedSessions:re,launchConfirmTextFilter:Se,launchConfirmWorkspaceFilter:fe,launchConfirmModelFilter:ce,launchConfirmResumableOnly:de,launchConfirmSortMode:ge,filteredLaunchConfirmSavedSessions:Ge,launchConfirmSessionsLoading:oe,launchConfirmBusy:ue,resolvedWorkspacePath:K,canCreateMissingWorkspace:V,openBrowseDialog:Me,loadBrowsePath:Q,handleWorkspaceChoiceChange:Pe,chooseCustomWorkspacePath:Ke,setCustomWorkspacePath:d,setBrowseDialogOpen:x,setActiveLauncherKind:T,openLaunchConfirm:Je,handleConfirmLaunch:ut,closeLaunchConfirm:it,setWorkspaceSelectionFromOption:We,setLaunchConfirmWorkspaceKeyAndSync:ht,setLaunchConfirmArgs:S,setLaunchConfirmModel:Y,setLaunchConfirmResumeId:H,setLaunchConfirmTextFilter:X,setLaunchConfirmWorkspaceFilter:we,setLaunchConfirmModelFilter:he,setLaunchConfirmResumableOnly:z,setLaunchConfirmSortMode:ae}}function lh({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:u,section:p,showBottomNav:m,onBack:f,onSectionChange:g,onOpenConversation:w,onOpenRecent:A,onOpenMachineDetails:d,onMachineUpgrade:b,onLaunchDetectedIde:y,onAddWorkspace:h,onBrowseDirectory:N,onLaunchWorkspaceProvider:_,onListSavedSessions:k}){const I=C=>C==="ide"?"IDE":C==="cli"?"CLI":"ACP",j=r.slice(0,4),v=s.slice(0,3),x=ch({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:N,onListSavedSessions:k}),E=o.useMemo(()=>j.map(C=>{const{metaText:R,updatedLabel:B}=el(C);return{key:`recent-launch:${C.id}`,primary:C.label,secondary:R,updatedLabel:B,onClick:()=>{const{options:S,selectedKey:D}=gs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspacePath:C.workspace});x.openLaunchConfirm({title:C.kind==="ide"?fs("restart-ide",C.label):C.providerSessionId?Oa(C.label):fs("start-fresh",C.label),description:C.kind==="ide"?hs("restart-ide"):C.providerSessionId?Ha():hs("start-fresh"),confirmLabel:C.kind==="ide"?Os("restart-ide"):C.providerSessionId?nn(!0):Os("start-fresh"),busyLabel:C.kind==="ide"?Hs("restart-ide"):C.providerSessionId?Ba(!0):Hs("start-fresh"),workspaceOptions:S,selectedWorkspaceKey:D,details:[{label:"Mode",value:I(C.kind)},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]},async()=>{const Y=S.find(q=>q.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(Y),await A({...C,workspace:(Y==null?void 0:Y.workspacePath)??null})})}}}),[x,A,j]),T=o.useMemo(()=>v.map(C=>({key:`recent-chat:${C.conversation.tabKey}`,primary:lt(C.conversation),secondary:Hm(C.conversation,{timestampLabel:C.timestamp?zi(C.timestamp):null}),unread:C.unread,onClick:()=>w(C.conversation)})),[w,v]),L=x.showAllRecent?E:E.slice(0,4),M=E.length>0,W=T.length>0,U=u?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:`flex items-center justify-between gap-3 ${U} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.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:t.jsx(ja,{size:18})}),t.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:_t(e,{fallbackId:e.id})}),t.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}`:""]})]})]})}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[W&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:T.map(C=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${C.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:C.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))})]}),M&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:L.map(C=>t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:C.onClick,children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:C.primary}),C.updatedLabel&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:C.updatedLabel})]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))}),E.length>4&&t.jsx("div",{className:"flex justify-center px-4 pt-2",children:t.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:()=>x.setShowAllRecent(C=>!C),children:x.showAllRecent?"Show fewer":`Show ${E.length-4} more`})})]}),(x.hasIdeOptions||n.length>0||a.length>0)&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:t.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:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),t.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),t.jsx("select",{value:x.workspaceChoice,onChange:C=>x.handleWorkspaceChoiceChange(C.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:x.workspaceRows.length>0?t.jsxs(t.Fragment,{children:[x.workspaceRows.map(C=>t.jsxs("option",{value:C.id,children:[C.id===x.defaultWorkspaceId?"⭐ ":"",hn(C.path,C.label)||C.path]},C.id)),t.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):t.jsx("option",{value:"__custom__",children:"Select workspace…"})}),x.workspaceChoice==="__custom__"&&t.jsxs("div",{className:"flex flex-col gap-2.5",children:[t.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start gap-3",children:[t.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:t.jsx(Es,{size:17})}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),t.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:x.resolvedWorkspacePath||x.browseCurrentPath||"No folder selected yet."})]})]})}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.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:x.openBrowseDialog,children:"Select workspace…"}),t.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:()=>{x.resolvedWorkspacePath&&h(x.resolvedWorkspacePath)},disabled:!x.resolvedWorkspacePath||x.browseBusy,children:"Save as workspace"})]})]}),x.resolvedWorkspacePath&&t.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath})]})}),t.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[x.hasIdeOptions&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${x.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:()=>x.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${x.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:()=>x.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${x.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:()=>x.setActiveLauncherKind("acp"),children:"ACP"})]}),x.activeLauncherKind&&t.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[t.jsx("div",{className:"text-xs font-bold text-text-secondary",children:x.activeLauncherKind==="ide"?"Choose an IDE":x.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),t.jsx("div",{className:"grid grid-cols-1 gap-2",children:x.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(C=>t.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:B}=gs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspaceId:x.workspaceChoice!=="__custom__"?x.workspaceChoice:null,currentWorkspacePath:x.resolvedWorkspacePath});x.openLaunchConfirm({title:`Launch ${C.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:R,selectedWorkspaceKey:B,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:C.name}]},async()=>{const S=R.find(D=>D.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(S),y(C.type,{workspacePath:(S==null?void 0:S.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:C.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath||"Use selected workspace"})]},C.type)):(x.activeLauncherKind==="cli"?n:a).map(C=>t.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=x.activeLauncherKind==="cli"?"cli":"acp",{options:B,selectedKey:S}=gs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspaceId:x.workspaceChoice!=="__custom__"?x.workspaceChoice:null,currentWorkspacePath:x.resolvedWorkspacePath});x.openLaunchConfirm({title:`Launch ${C.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${R.toUpperCase()}`,workspaceOptions:B,selectedWorkspaceKey:S,details:[{label:"Mode",value:R.toUpperCase()},{label:"Provider",value:C.displayName}],showArgsInput:!0,showModelInput:R==="acp",initialArgs:"",initialModel:"",providerType:C.type},async()=>{const D=B.find(Y=>Y.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(D),_(R,C.type,{workspaceId:(D==null?void 0:D.workspaceId)??null,workspacePath:(D==null?void 0:D.workspacePath)??null,args:x.launchConfirmArgs,model:x.launchConfirmModel,resumeSessionId:x.launchConfirmResumeId||null})})},children:[t.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[C.icon?`${C.icon} `:"",C.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath||"Use selected workspace"})]},C.type))})]}),l.message&&t.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,x.canCreateMissingWorkspace&&t.jsx("div",{className:"mt-2",children:t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[34px] px-4 rounded-lg bg-surface-primary text-text-primary font-bold text-xs",onClick:()=>h(x.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[i&&t.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:b,children:[t.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),t.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:d,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),x.browseDialogOpen&&t.jsx(vn,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:x.browseCurrentPath,directories:x.browseDirectories,busy:x.browseBusy,error:x.browseError,confirmLabel:"Use this folder",onClose:()=>x.setBrowseDialogOpen(!1),onNavigate:C=>{x.loadBrowsePath(C)},onConfirm:C=>{x.chooseCustomWorkspacePath(C),x.setBrowseDialogOpen(!1)}}),x.launchConfirm&&t.jsx(so,{title:x.launchConfirm.title,description:x.launchConfirm.description,details:x.launchConfirm.details,workspaceOptions:x.launchConfirm.workspaceOptions,selectedWorkspaceKey:x.launchConfirmWorkspaceKey,onWorkspaceChange:x.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:x.launchConfirm.providerType?nn(!!x.launchConfirmResumeId):x.launchConfirm.confirmLabel,busyLabel:x.launchConfirm.providerType?void 0:x.launchConfirm.busyLabel,busy:x.launchConfirmBusy,showArgsInput:x.launchConfirm.showArgsInput,argsValue:x.launchConfirmArgs,onArgsChange:x.setLaunchConfirmArgs,showModelInput:x.launchConfirm.showModelInput,modelValue:x.launchConfirmModel,onModelChange:x.setLaunchConfirmModel,historyProviderNode:x.launchConfirm.providerType&&(x.launchConfirmSessionsLoading||x.launchConfirmSavedSessions.length>0)&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),x.launchConfirmSessionsLoading&&t.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:Wa()}),t.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[t.jsx("input",{type:"text",value:x.launchConfirmTextFilter,onChange:C=>x.setLaunchConfirmTextFilter(C.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:x.launchConfirmWorkspaceFilter,onChange:C=>x.setLaunchConfirmWorkspaceFilter(C.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:x.launchConfirmModelFilter,onChange:C=>x.setLaunchConfirmModelFilter(C.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsxs("select",{value:x.launchConfirmSortMode,onChange:C=>x.setLaunchConfirmSortMode(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"recent",children:"Most recent"}),t.jsx("option",{value:"oldest",children:"Oldest first"}),t.jsx("option",{value:"messages",children:"Most messages"})]})]}),t.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsx("input",{type:"checkbox",checked:x.launchConfirmResumableOnly,onChange:C=>x.setLaunchConfirmResumableOnly(C.target.checked),disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),"Resume-ready only"]}),t.jsxs("select",{value:x.launchConfirmResumeId,onChange:C=>x.setLaunchConfirmResumeId(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"",children:Zm()}),x.filteredLaunchConfirmSavedSessions.map(C=>t.jsxs("option",{value:C.providerSessionId,disabled:!C.canResume,children:[C.title||C.providerSessionId," ",C.canResume?"":"(workspace missing)"]},C.providerSessionId))]}),!x.launchConfirmSessionsLoading&&x.launchConfirmSavedSessions.length>0&&x.filteredLaunchConfirmSavedSessions.length===0&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),x.launchConfirmResumeId&&(()=>{const C=x.filteredLaunchConfirmSavedSessions.find(B=>B.providerSessionId===x.launchConfirmResumeId);if(!C)return null;const R=Zc(C);return t.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:[t.jsx("div",{className:"font-semibold text-text-primary truncate",children:R.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:R.providerSessionId}),t.jsx("div",{className:"mt-1",children:R.metaLine}),R.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:R.updatedLabel}),R.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:R.preview})]})})()]}),onConfirm:x.handleConfirmLaunch,onCancel:x.closeLaunchConfirm}),m&&t.jsx(Jc,{section:p,onSectionChange:g})]})}function tl(e){var r;const s=((r=e.p2p)==null?void 0:r.state)||"";return s==="connected"?"Connected":s==="connecting"||s==="new"||s==="checking"?"Connecting":"Offline"}function dh(e,s){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:ws(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):s.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var c,l,u,p,m;const a=mr(n)?"cli":Ls(n)?"acp":"ide",i=ws(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(mr(n)?n.cliName||n.type:Ls(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Ls(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((m=(p=(u=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:u.at)==null?void 0:p.call(u,-1))==null?void 0:m.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function uh(e,s){const r=new Map;for(const n of s){const a=os(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((f,g)=>g.timestamp-f.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=aa(n),u=a.filter(f=>f.unread||f.requiresAction).length,p=tl(n),m=[n.platform||"machine",p].filter(Boolean);return{id:n.id,label:_t(n,{fallbackId:n.id}),subtitle:m.join(" · "),unread:u,total:a.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?Um(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 Wr(e,s){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}`,s)}catch{}}function mh({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:m,onRequestedMachineConsumed:f,requestedMobileSection:g,onRequestedMobileSectionConsumed:w,setSelectedTabKey:A,setScreen:d,setSelectedMachineId:b,setSection:y,setMachineBackTarget:h,resetMachineAction:N,markNotificationTargetRead:_}){const k=o.useRef(null),I=o.useCallback(j=>{if(!(j!=null&&j.sessionId))return;const v=tn(j,c),x=Math.max(Date.now(),us(j),v.lastUpdated||0);Wr("mark_read:start",{tabKey:j.tabKey,sessionId:j.sessionId,displayPrimary:lt(j),inboxBucket:v.inboxBucket,unread:v.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,activityAt:us(j),readAt:x}),_({sessionId:j.sessionId,providerSessionId:j.providerSessionId,tabKey:j.tabKey,routeId:j.routeId},x),l(os(j)||j.routeId,"mark_session_seen",{sessionId:j.sessionId,seenAt:x}).then(E=>{Wr("mark_read:result",{tabKey:j.tabKey,sessionId:j.sessionId,result:E})}).catch(E=>{Wr("mark_read:error",{tabKey:j.tabKey,sessionId:j.sessionId,error:E instanceof Error?E.message:String(E)})})},[c,l]);return o.useEffect(()=>{var v;if(!n){d("inbox"),A(((v=e[0])==null?void 0:v.tabKey)||null),k.current=null;return}if(i!=="chat"){k.current=null;return}const j=`${n.tabKey}:${n.sessionId||""}`;k.current!==j&&(k.current=j,I(n))},[e,I,i,n,d,A]),o.useEffect(()=>{if(!u)return;const j=e.find(v=>v.tabKey===u);j&&(A(j.tabKey),d("chat"),p==null||p())},[e,p,u,d,A]),o.useEffect(()=>{if(!m)return;const j=s.find(v=>v.id===m);j&&(b(j.id),N(),y("machines"),h("inbox"),d("machine"),f==null||f())},[s,f,m,N,h,d,y,b]),o.useEffect(()=>{g&&(y(g),d("inbox"),w==null||w())},[w,g,d,y]),o.useEffect(()=>{const j=r.filter(v=>v.inboxBucket==="task_complete"||v.unread);j.length!==0&&Wr("inbox_state",{screen:i,selectedTabKey:a,items:j.map(v=>{const x=tn(v.conversation,c);return{liveState:x,tabKey:v.conversation.tabKey,sessionId:v.conversation.sessionId,displayPrimary:lt(v.conversation),serverBucket:x.inboxBucket,computedBucket:v.inboxBucket,serverUnread:x.unread,computedUnread:v.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,activityAt:us(v.conversation)}})})},[r,c,i,a]),{markConversationRead:I}}function ph(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function ii(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function fh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function hh({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[u,p]=o.useState(null),m=o.useCallback(()=>{i("idle"),l(""),p(null)},[]),f=o.useCallback(async(h,N,_)=>{var k;try{i("loading"),l(`Launching ${N}…`);const I={ideType:N,enableCdp:!0};(k=_==null?void 0:_.workspacePath)!=null&&k.trim()&&(I.workspace=_.workspacePath.trim()),await e(h,"launch_ide",I),i("done"),l(`${N} launch requested`)}catch(I){i("error"),l(I instanceof Error?I.message:"Launch IDE failed"),console.error("Launch IDE failed",I)}},[e]),g=o.useCallback(async(h,N,_)=>{if(N.trim())try{i("loading"),l(_!=null&&_.createIfMissing?"Creating folder…":"Saving workspace…");const k=await e(h,"workspace_add",{path:N.trim(),createIfMissing:(_==null?void 0:_.createIfMissing)===!0});if(k!=null&&k.success){i("done"),l(_!=null&&_.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((k==null?void 0:k.error)||"Could not save workspace")}catch(k){i("error"),l(k instanceof Error?k.message:"Could not save workspace")}},[e]),w=o.useCallback(async h=>{var N,_,k,I,j,v;try{i("loading"),l("Starting daemon upgrade…");const x=await e(h,"daemon_upgrade",{});if((N=x==null?void 0:x.result)!=null&&N.alreadyLatest){i("done"),l(`Already on v${((_=x==null?void 0:x.result)==null?void 0:_.version)||"latest"}.`);return}if((k=x==null?void 0:x.result)!=null&&k.upgraded||(I=x==null?void 0:x.result)!=null&&I.success){i("done"),l(`Upgrade to v${((j=x==null?void 0:x.result)==null?void 0:j.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((v=x==null?void 0:x.result)==null?void 0:v.error)||"Upgrade failed")}catch(x){i("error"),l(x instanceof Error?x.message:"Upgrade failed")}},[e]),A=o.useCallback(async(h,N,_,k)=>{var v,x,E;const I=Date.now(),j={machineId:h,kind:N,providerType:_,workspaceId:(k==null?void 0:k.workspaceId)||null,workspacePath:(k==null?void 0:k.workspacePath)||null,resumeSessionId:(k==null?void 0:k.resumeSessionId)||null,startedAt:I};try{i("loading"),l(`Launching ${_}…`),p(j);const T={cliType:_};(v=k==null?void 0:k.workspacePath)!=null&&v.trim()?T.dir=k.workspacePath.trim():k!=null&&k.workspaceId&&(T.workspaceId=k.workspaceId),k!=null&&k.resumeSessionId&&(T.resumeSessionId=k.resumeSessionId),(x=k==null?void 0:k.args)!=null&&x.trim()&&(T.cliArgs=k.args.trim().split(/\s+/).filter(Boolean)),(E=k==null?void 0:k.model)!=null&&E.trim()&&(T.initialModel=k.model.trim());const L=await e(h,"launch_cli",T),M=(L==null?void 0:L.result)||L,W=(M==null?void 0:M.sessionId)||(M==null?void 0:M.id);if(L!=null&&L.success&&W){p(null),i("done"),l(`${_} launched`),s(ns(W));return}if(L!=null&&L.success){i("loading"),l(`${_} launch requested — waiting for session…`);return}p(null),i("error"),l((L==null?void 0:L.error)||(M==null?void 0:M.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(T){if(fh(T)){i("loading"),l(`${_} launch requested — waiting for session…`);return}p(null),i("error"),l(T instanceof Error?T.message:`Could not launch ${N.toUpperCase()} workspace`)}},[s,e]),d=o.useCallback(async(h,N)=>{try{const _=await e(h,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),k=(_==null?void 0:_.result)??_;return Array.isArray(k==null?void 0:k.sessions)?k.sessions:[]}catch(_){return console.error("Failed to list saved sessions on mobile:",_),[]}},[e]),b=o.useCallback(async(h,N)=>yn(e,h,N),[e]);o.useEffect(()=>{if(!u)return;const h=ii(u.workspacePath),N=r.find(k=>{var T,L,M,W;if(!k||k.type==="adhdev-daemon"||ph(k.daemonId||k.id)!==u.machineId||(k.transport==="acp"?"acp":k.transport==="pty"?"cli":null)!==u.kind||String(k.agentType||k.type||"")!==u.providerType)return!1;const x=String(k.providerSessionId||"");if(u.resumeSessionId&&x)return x===u.resumeSessionId;if(h){const U=ii(k.workspace||k.runtimeWorkspaceLabel);return U?U===h:!1}return Number(k.lastUpdated||k._lastUpdate||k.timestamp||((W=(M=(L=(T=k.activeChat)==null?void 0:T.messages)==null?void 0:L.at)==null?void 0:M.call(L,-1))==null?void 0:W.timestamp)||0)>=u.startedAt-5e3});if(!N)return;const _=lc({entrySessionId:N.sessionId,entryInstanceId:N.instanceId,entryRouteId:N.id,conversations:n});_&&(p(null),i("done"),l(`${u.providerType} launched`),s(ns(_)))},[n,r,s,u]),o.useEffect(()=>{if(!u)return;const h=window.setTimeout(()=>{p(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(h)},[u]);const y=o.useCallback(async(h,N)=>{if(N.kind==="ide"&&N.providerType){await f(h,N.providerType,{workspacePath:N.workspace||null});return}(N.kind==="cli"||N.kind==="acp")&&N.providerType&&await A(h,N.kind,N.providerType,{workspacePath:N.workspace||null,resumeSessionId:N.providerSessionId||null})},[f,A]);return{machineAction:{state:a,message:c},resetMachineAction:m,handleLaunchDetectedIde:f,handleAddWorkspace:g,handleMachineUpgrade:w,handleLaunchWorkspaceProvider:A,handleListSavedSessions:d,handleBrowseDirectory:b,handleOpenRecent:y}}function xh({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:p}){const m=o.useCallback(y=>{i(y.tabKey),c("chat"),n(y)},[n,c,i]),f=o.useCallback(y=>{const h=e.find(N=>N.routeId===y.routeId&&N.streamSource==="native");h&&(i(h.tabKey),c("chat"),n(h))},[e,n,c,i]),g=o.useCallback(()=>{n(s),c("inbox")},[n,s,c]),w=o.useCallback((y,h="inbox")=>{l(y),a(),u("machines"),p(h),c("machine")},[a,p,c,u,l]),A=o.useCallback(y=>{const h=os(y);h&&w(h,"chat")},[w]),d=o.useCallback(()=>{a(),c(r)},[r,a,c]),b=o.useCallback(y=>{u(y),c("inbox")},[c,u]);return{openConversation:m,openNativeConversation:f,backFromConversation:g,openMachine:w,openConversationMachine:A,backFromMachine:d,changeMachineSection:b}}function bh(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function Or(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function gh({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,userName:u,requestedActiveTabKey:p,onRequestedActiveTabConsumed:m,requestedMachineId:f,onRequestedMachineConsumed:g,requestedMobileSection:w,onRequestedMobileSectionConsumed:A,onOpenHistory:d,onOpenRemote:b,onStopCli:y,wsStatus:h,isConnected:N,onShowHiddenConversation:_,onShowAllHiddenConversations:k,onHideConversation:I,onOpenNewSession:j,notificationStateBySessionId:v,liveSessionInboxState:x,onMarkNotificationTargetRead:E}){const[T,L]=o.useState(()=>{var Q;return((Q=e[0])==null?void 0:Q.tabKey)||null}),[M,W]=o.useState(()=>e[0]?"chat":"inbox"),[U,C]=o.useState("chats"),[R,B]=o.useState(null),[S,D]=o.useState("inbox"),Y=Us(),q="0.8.83",H=o.useMemo(()=>e.find(Q=>Q.tabKey===T)||e[0]||null,[e,T]),re=o.useMemo(()=>H?r.find(Q=>Q.id===H.routeId):void 0,[r,H]),ie=o.useMemo(()=>!H||Ze(H)||!tt(H)?null:Bs(H),[H]),Se=o.useMemo(()=>r.filter(Q=>Q.type==="adhdev-daemon").sort(Ta),[r]),X=o.useMemo(()=>Se.find(Q=>Q.id===R)||null,[Se,R]),fe=xn({sendDaemonCommand:a,activeConv:H||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),we=hh({sendDaemonCommand:a,navigate:Y,ides:r,conversations:e}),ce=o.useMemo(()=>e.map(Q=>{const Me=M==="chat"&&(H==null?void 0:H.tabKey)===Q.tabKey,We=fn(Q,x,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Me,notificationStateBySessionId:v}),Pe=us(Q),Ke=vc(Q);return{conversation:Q,timestamp:Pe,preview:Ke,unread:We.unread,requiresAction:We.requiresAction,isWorking:We.isWorking,inboxBucket:We.inboxBucket}}),[e,x,v,M,H]),{markConversationRead:he}=mh({conversations:e,machineEntries:Se,items:ce,selectedConversation:H,selectedTabKey:T,screen:M,liveSessionInboxState:x,sendDaemonCommand:a,requestedActiveTabKey:p,onRequestedActiveTabConsumed:m,requestedMachineId:f,onRequestedMachineConsumed:g,requestedMobileSection:w,onRequestedMobileSectionConsumed:A,setSelectedTabKey:L,setScreen:W,setSelectedMachineId:B,setSection:C,setMachineBackTarget:D,resetMachineAction:we.resetMachineAction,markNotificationTargetRead:E}),de=xh({conversations:e,selectedConversation:H,machineBackTarget:S,markConversationRead:he,resetMachineAction:we.resetMachineAction,setSelectedTabKey:L,setScreen:W,setSelectedMachineId:B,setSection:C,setMachineBackTarget:D}),z=o.useMemo(()=>Or(ce.filter(Q=>Q.requiresAction)),[ce]),ge=o.useMemo(()=>Or(ce.filter(Q=>Q.unread&&!Q.requiresAction)),[ce]),ae=o.useMemo(()=>Or(ce.filter(Q=>!Q.unread&&!Q.requiresAction&&Q.isWorking)),[ce]),oe=o.useMemo(()=>Or(ce.filter(Q=>!Q.unread&&!Q.requiresAction&&!Q.isWorking)),[ce]),ee=o.useMemo(()=>X?ce.filter(Q=>os(Q.conversation)===X.id):[],[ce,X]),ue=o.useMemo(()=>dh(X,r),[r,X]),se=(X==null?void 0:X.version)||null,ke=!!X&&!!se&&!0&&se!==q,ye=o.useMemo(()=>(X==null?void 0:X.availableProviders)||[],[X]),K=o.useMemo(()=>ye.filter(Q=>Q.category==="cli"&&Q.installed!==!1).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[ye]),V=o.useMemo(()=>ye.filter(Q=>Q.category==="acp"&&Q.installed!==!1).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[ye]),ve=o.useMemo(()=>uh(Se,ce),[ce,Se]),xe=o.useCallback(async Q=>{X&&await we.handleOpenRecent(X.id,Q)},[we,X]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:M==="chat"&&H?t.jsx(Jf,{selectedConversation:H,isAcp:Ze(H),isStandalone:l,selectedIdeEntry:re,actionLogs:n,userName:u,isSendingChat:fe.isSendingChat,sendFeedbackMessage:fe.sendFeedbackMessage,isFocusingAgent:fe.isFocusingAgent,handleModalButton:fe.handleModalButton,handleRelaunch:fe.handleRelaunch,onBack:de.backFromConversation,onOpenNativeConversation:de.openNativeConversation,onOpenMachine:de.openConversationMachine,onHideConversation:I,onOpenHistory:d,onOpenRemote:b,onStopCli:y,cliViewMode:ie,onSetCliViewMode:async Q=>{if(H&&ie!==Q)try{await a(os(H)||H.routeId,"set_cli_view_mode",{targetSessionId:H.sessionId,cliType:Bt(H),mode:Q})}catch(Me){const We=Qa(Me);Xa(Me)?console.warn(We?"CLI view mode result was lost after send; keeping optimistic mobile mode override:":"Skipped CLI view mode switch:",Me instanceof Error?Me.message:String(Me)):console.error("Failed to switch CLI view mode:",Me)}},handleSendChat:fe.handleSendChat,handleFocusAgent:fe.handleFocusAgent}):M==="machine"&&X?t.jsx(lh,{selectedMachineEntry:X,selectedMachineConversations:ee,selectedMachineRecentLaunches:ue,cliProviders:K,acpProviders:V,selectedMachineNeedsUpgrade:ke,appVersion:q,machineAction:we.machineAction,isStandalone:l,section:U,showBottomNav:S==="inbox",onBack:de.backFromMachine,onSectionChange:de.changeMachineSection,onOpenConversation:de.openConversation,onOpenRecent:xe,onOpenMachineDetails:()=>Y(`/machines/${X.id}`),onMachineUpgrade:()=>we.handleMachineUpgrade(X.id),onLaunchDetectedIde:(Q,Me)=>we.handleLaunchDetectedIde(X.id,Q,Me),onAddWorkspace:(Q,Me)=>we.handleAddWorkspace(X.id,Q,Me),onBrowseDirectory:Q=>we.handleBrowseDirectory(X.id,Q),onLaunchWorkspaceProvider:(Q,Me,We)=>we.handleLaunchWorkspaceProvider(X.id,Q,Me,We),onListSavedSessions:Q=>we.handleListSavedSessions(X.id,Q)}):t.jsx(eh,{section:U,attentionItems:z,unreadItems:ge,workingItems:ae,completedItems:oe,hiddenConversations:s,machineCards:ve,getAvatarText:bh,onOpenConversation:de.openConversation,onShowConversation:_,onShowAllHidden:k,onOpenNewSession:j,onOpenMachine:de.openMachine,onOpenSettings:()=>Y("/settings"),onSectionChange:C,wsStatus:h,isConnected:N,isStandalone:l})})}function Un(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function yh({conversations:e,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,u]=o.useState(!1),[p,m]=o.useState(null),f=o.useCallback(()=>{c.current=0,u(!1),m(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",f),window.addEventListener("drop",f),()=>{window.removeEventListener("dragend",f),window.removeEventListener("drop",f)}),[f]);const g=o.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),w=o.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!Un(s,r)){m("merge");return}const y=b.currentTarget.getBoundingClientRect(),h=b.clientX-y.left,N=y.width/3;h<N?m("split-left"):h>N*2?m("split-right"):m("merge")},[s,r]),A=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,u(!1),m(null))},[]),d=o.useCallback(b=>{c.current=0,u(!1);const y=b.dataTransfer.getData("text/tab-key"),h=y?e.some(_=>_.tabKey===y):!1,N=p;if(m(null),i(),!!y){if(b.preventDefault(),N==="split-left"&&Un(s,r)){r==null||r(y,"split-left");return}if(N==="split-right"&&Un(s,r)){r==null||r(y,"split-right");return}if(h){a(y);return}n==null||n(y)}},[e,p,s,r,n,a,i]);return{dragOver:l,dropAction:p,resetDragState:f,handleDragEnter:g,handleDragOver:w,handleDragLeave:A,handleDrop:d}}function vh(e,s){const r=new Set(s.map(i=>i.tabKey)),n=e.filter(i=>r.has(i)),a=s.filter(i=>!e.includes(i.tabKey)).map(i=>i.tabKey);return[...n,...a]}function wh({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(s??null),[l,u]=o.useState(r??[]),[p,m]=o.useState(null),f=o.useRef(null),g=o.useRef(null),w=o.useRef(n),A=o.useRef(a);o.useEffect(()=>{w.current=n},[n]),o.useEffect(()=>{A.current=a},[a]),o.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),o.useEffect(()=>{u(j=>{const v=vh(j,e);return v.length===j.length&&v.every((x,E)=>x===j[E])?j:v})},[e]);const d=o.useMemo(()=>{const j=p??l;if(j.length===0)return e;const v=new Map(j.map((x,E)=>[x,E]));return[...e].sort((x,E)=>{const T=v.get(x.tabKey)??999,L=v.get(E.tabKey)??999;return T-L})},[e,p,l]);o.useEffect(()=>{var v,x;if(d.length===0){i!==null&&(c(null),(v=w.current)==null||v.call(w,null));return}if(i&&d.some(E=>E.tabKey===i))return;const j=d[0].tabKey;j!==i&&(c(j),(x=w.current)==null||x.call(w,j))},[d,i]);const b=o.useMemo(()=>d.find(j=>j.tabKey===i),[d,i]),y=o.useCallback(j=>{var v;c(j),(v=w.current)==null||v.call(w,j)},[]),h=o.useCallback((j,v,x)=>{u(E=>{var W;const T=E.filter(U=>U!==j),L=T.indexOf(v);if(L<0)return E;const M=x==="left"?L:L+1;return T.splice(M,0,j),(W=A.current)==null||W.call(A,T),T}),m(null)},[]),N=o.useCallback((j,v,x)=>{const T=(l.length>0?l:e.map(W=>W.tabKey)).filter(W=>W!==j),L=T.indexOf(v);if(L<0)return;const M=x==="left"?L:L+1;T.splice(M,0,j),f.current=T,m(T)},[l,e]),_=o.useCallback(()=>{var v;const j=f.current;j&&(u(j),(v=A.current)==null||v.call(A,j))},[]),k=o.useCallback(()=>{f.current=null,m(null)},[]),I=o.useCallback(j=>{u(v=>{var E;const x=v.filter(T=>T!==j);return x.push(j),(E=A.current)==null||E.call(A,x),x})},[]);return{activeTabId:i,activeConv:b,sortedConversations:d,previewOrderRef:f,draggingTabRef:g,selectTab:y,handleTabReorder:h,updatePreviewOrder:N,commitPreviewOrder:_,clearPreviewOrder:k,moveTabToEnd:I,setDraggingTabKey:j=>{g.current=j}}}function jh({dropAction:e,canSplit:s}){return t.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[t.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:s?1:.45},children:t.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"})}),t.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:t.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"})}),t.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:s?1:.45},children:t.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 ro({conversationsCount:e,isSplitMode:s,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1}){if(a)return t.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const i=!r&&!n,c=r?"Waiting for your daemon":n?"No conversations yet":"Connect your machines",l=r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":n?"Your machines are connected. Open a machine, choose a workspace, then launch an IDE, CLI, or ACP session.":"Install ADHDev on a machine, sign in, and it will show up here.";return e===0&&!s?t.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[t.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),t.jsxs("div",{className:"text-center max-w-lg",children:[t.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:c}),t.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:l}),i&&t.jsx(Qc,{}),i&&t.jsx("div",{className:"mt-8",children:t.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 →"})})]})]}):t.jsx("div",{className:"text-sm text-text-muted opacity-50",children:s?"Move a tab here to view":"No active agent"})}const sl="adhdev-tab-shortcuts";function rl(){try{return JSON.parse(localStorage.getItem(sl)||"{}")}catch{return{}}}function nl({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>rl()),[l,u]=o.useState(null),p=o.useCallback(f=>{const g=[];return f.metaKey&&g.push(a?"⌘":"Meta"),f.ctrlKey&&g.push("Ctrl"),f.altKey&&g.push(a?"⌥":"Alt"),f.shiftKey&&g.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(g.push(f.key.length===1?f.key.toUpperCase():f.key),g.join("+"))},[a]),m=o.useCallback(f=>{c(f);try{localStorage.setItem(sl,JSON.stringify(f))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const f=g=>{if(g.preventDefault(),g.stopPropagation(),g.key==="Escape"){u(null);return}const w=p(g);if(!w)return;const A={...i};for(const[d,b]of Object.entries(A))b===w&&delete A[d];A[l]=w,m(A),u(null)};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[e,l,i,m,p]),o.useEffect(()=>{if(!e)return;const f=g=>{if(!(!g.ctrlKey&&!g.metaKey&&!g.altKey)){for(const[w,A]of Object.entries(i))if(s.includes(w)&&p(g)===A){g.preventDefault(),r(),n(w);return}}};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,i,s,r,n,p]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:u,saveShortcuts:m}}const kh=o.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:u,onSelectTab:p,onConversationActivated:m,onPreviewReorder:f,onReorderTab:g,onCommitPreviewOrder:w,onClearPreviewOrder:A,onDragStateReset:d,onDragTabKeyChange:b,onReceiveTab:y,onOpenContextMenu:h,longPressTimer:N,isGroupActive:_}){const k=zs(s),I=k.isGenerating?"agent-tab-generating":k.isWaiting?"agent-tab-waiting":"",j=k.isReconnecting,v=o.useCallback(R=>{l.current=s.tabKey,b(s.tabKey),R.dataTransfer.setData("text/tab-key",s.tabKey),R.dataTransfer.effectAllowed="move"},[s.tabKey,l,b]),x=o.useCallback(()=>{l.current=null,b(null),w(),A(),d()},[l,b,w,A,d]),E=o.useCallback(R=>{const B=l.current;if(!(!B||B===s.tabKey)&&R.dataTransfer.types.includes("text/tab-key")){R.preventDefault(),R.stopPropagation();const S=R.currentTarget.getBoundingClientRect(),D=R.clientX<S.left+S.width/2?"left":"right";f(B,s.tabKey,D)}},[s.tabKey,l,f]),T=o.useCallback(R=>{R.preventDefault(),R.stopPropagation();const B=R.dataTransfer.getData("text/tab-key");if(B&&B!==s.tabKey){const S=R.currentTarget.getBoundingClientRect(),D=R.clientX<S.left+S.width/2?"left":"right";c.includes(B)?g(B,s.tabKey,D):y&&y(B)}A()},[s.tabKey,c,g,y,A]),L=o.useCallback(R=>{R.stopPropagation(),u(),p(s.tabKey),m(s)},[s,m,u,p]),M=o.useCallback(R=>{R.preventDefault(),h(R.clientX,R.clientY,s.tabKey)},[s.tabKey,h]),W=o.useCallback(R=>{const B=R.touches[0];N.current=setTimeout(()=>{h(B.clientX,B.clientY,s.tabKey)},600)},[s.tabKey,N,h]),U=o.useCallback(()=>{N.current&&clearTimeout(N.current)},[N]),C=["adhdev-dockview-tab",I,r&&"is-active",_&&"is-group-active",j&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:C,draggable:!0,onDragStart:v,onDragEnd:x,onDragOver:E,onDrop:T,onClick:L,onContextMenu:M,onTouchStart:W,onTouchEnd:U,onTouchMove:U,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status",children:k.isGenerating?t.jsx("div",{className:"tab-spinner"}):k.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):k.isConnecting?t.jsx("div",{className:"tab-connecting-spinner"}):s.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("span",{className:"adhdev-dockview-tab-primary",title:lt(s),children:lt(s)}),t.jsx("span",{className:"adhdev-dockview-tab-meta",children:j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ps(s)}):k.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[ps(s),t.jsx("span",{className:"connecting-dots"})]}):ps(s)})]}),i&&t.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,s)=>e.conv===s.conv&&e.isActive===s.isActive&&e.isDraggedTab===s.isDraggedTab&&e.isTaskCompleteUnread===s.isTaskCompleteUnread&&e.shortcut===s.shortcut&&e.conversationKeys===s.conversationKeys&&e.isGroupActive===s.isGroupActive);function Sh({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:m,onClearPreviewOrder:f,onDragStateReset:g,onDragTabKeyChange:w,onReceiveTab:A,onHideTab:d,isGroupActive:b,allowTabShortcuts:y=!0}){const[h,N]=o.useState(null),_=o.useRef(null),k=o.useRef(null),I=o.useMemo(()=>e.map(M=>M.tabKey),[e]);xr("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(h==null?void 0:h.tabKey)||null});const{isMac:j,tabShortcuts:v,shortcutListening:x,setShortcutListening:E,saveShortcuts:T}=nl({enabled:y,sortedTabKeys:e.map(M=>M.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!h)return;const M=W=>{const U=document.querySelector("[data-pane-context-menu]");U&&U.contains(W.target)||N(null)};return window.addEventListener("mousedown",M,!0),()=>window.removeEventListener("mousedown",M,!0)},[h]),o.useEffect(()=>{const M=k.current;if(!M)return;const W=U=>{Math.abs(U.deltaY)<=Math.abs(U.deltaX)||(U.preventDefault(),M.scrollLeft+=U.deltaY)};return M.addEventListener("wheel",W,{passive:!1}),()=>M.removeEventListener("wheel",W)},[]);const L=o.useCallback((M,W,U)=>{N({x:M,y:W,tabKey:U})},[]);return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:t.jsxs("div",{ref:k,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(M=>t.jsx(kh,{conv:M,isActive:s===M.tabKey,isDraggedTab:a.current===M.tabKey,isTaskCompleteUnread:n.has(M.tabKey),shortcut:y?v[M.tabKey]:void 0,conversationKeys:I,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:m,onClearPreviewOrder:f,onDragStateReset:g,onDragTabKeyChange:w,onReceiveTab:A,onOpenContextMenu:L,longPressTimer:_,isGroupActive:b},M.tabKey)),e.length===0&&t.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),h&&t.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:h.x,top:h.y},children:[y&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:M=>{M.stopPropagation(),E(h.tabKey),N(null)},children:["⌨ ",v[h.tabKey]?`Change shortcut (${v[h.tabKey]})`:"Set shortcut"]}),v[h.tabKey]&&t.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 M={...v};delete M[h.tabKey],T(M),N(null)},children:"✕ Remove shortcut"})]}),d&&t.jsxs(t.Fragment,{children:[y&&t.jsx("div",{className:"border-t border-border-subtle my-1"}),t.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onClick:()=>{d(h.tabKey),N(null)},children:"🚫 Hide from Dashboard"})]})]}),y&&x&&t.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>E(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:M=>M.stopPropagation(),children:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",j?"⌘+1":"Ctrl+1",", ",j?"⌥+A":"Alt+A",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function Nh({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:u,userName:p,groupIndex:m,onFocus:f,isSplitMode:g,numGroups:w,onMoveTab:A,onReceiveTab:d,style:b,onActiveTabChange:y,initialActiveTabId:h,initialTabOrder:N,onTabOrderChange:_,onHideTab:k,isFocused:I,allowTabShortcuts:j=!0,notificationStateBySessionId:v,liveSessionInboxState:x}){const{sendCommand:E}=Pt(),T=o.useRef(null),{activeTabId:L,activeConv:M,sortedConversations:W,draggingTabRef:U,selectTab:C,handleTabReorder:R,updatePreviewOrder:B,commitPreviewOrder:S,clearPreviewOrder:D,moveTabToEnd:Y,setDraggingTabKey:q}=wh({conversations:e,initialActiveTabId:h,initialTabOrder:N,onActiveTabChange:y,onTabOrderChange:_}),H=xn({sendDaemonCommand:a,activeConv:M,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),{dragOver:re,dropAction:ie,resetDragState:Se,handleDragEnter:X,handleDragOver:fe,handleDragLeave:we,handleDrop:ce}=yh({conversations:e,numGroups:w,onMoveTab:A,onReceiveTab:d,onOwnTabDrop:Y,onClearPreviewOrder:D}),he=M&&!Ze(M)&&Bs(M)==="terminal",de=o.useMemo(()=>M?s.find(oe=>oe.id===M.routeId):void 0,[s,M]),z=o.useMemo(()=>M?n.filter(oe=>oe.routeId===M.tabKey):[],[n,M]),ge=o.useMemo(()=>new Set(W.filter(oe=>lu(oe,x,{isOpenConversation:oe.tabKey===L,notificationStateBySessionId:v})).map(oe=>oe.tabKey)),[L,x,W]);xr("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:L,dragOver:re});const ae=o.useCallback(oe=>{oe.streamSource==="agent-stream"&&oe.agentType&&E(oe.routeId,Xc(),{agentType:oe.agentType,...oe.sessionId&&{targetSessionId:oe.sessionId}}).catch(()=>{})},[E]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:f,style:{...b,outline:re?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(Sh,{conversations:W,activeTabId:L,groupIndex:m,numGroups:w,unreadTabKeys:ge,draggingTabRef:U,onFocus:f,onSelectTab:C,onConversationActivated:ae,onPreviewReorder:B,onReorderTab:R,onCommitPreviewOrder:S,onClearPreviewOrder:D,onDragStateReset:Se,onDragTabKeyChange:q,onMoveTab:A,onReceiveTab:d,onHideTab:k,isGroupActive:I??!1,allowTabShortcuts:j}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:X,onDragOver:fe,onDragLeave:we,onDrop:ce,children:[re&&t.jsx(jh,{dropAction:ie,canSplit:!!(w<4&&A)}),M?t.jsx(to,{activeConv:M,clearToken:r[M.tabKey]||0,isCliTerminal:!!he,ideEntry:de,terminalRef:T,handleModalButton:H.handleModalButton,handleRelaunch:H.handleRelaunch,handleSendChat:H.handleSendChat,isSendingChat:H.isSendingChat,sendFeedbackMessage:H.sendFeedbackMessage,handleFocusAgent:H.handleFocusAgent,isFocusingAgent:H.isFocusingAgent,actionLogs:z,userName:p,isInputActive:!g||!!I}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(ro,{conversationsCount:e.length,isSplitMode:g,isStandalone:l,hasRegisteredMachines:u})})]})]})}function Ch({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:p,setActionLogs:m,isStandalone:f,hasRegisteredMachines:g,userName:w,focusedGroup:A,setFocusedGroup:d,moveTabToGroup:b,splitTabRelative:y,closeGroup:h,handleResizeStart:N,groupActiveTabIds:_,setGroupActiveTabIds:k,groupTabOrders:I,setGroupTabOrders:j,toggleHiddenTab:v,allowTabShortcuts:x=!0,notificationStateBySessionId:E,liveSessionInboxState:T}){return t.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:a.map((L,M)=>{const W=s&&n.length===r?`${n[M]}%`:void 0;return t.jsxs(at.Fragment,{children:[s&&M>0&&t.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:U=>N(M-1,U),onDoubleClick:()=>h(M),title:"Drag to resize · Double-click to merge",children:t.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),t.jsx(Nh,{style:s?{flexBasis:W??`${100/r}%`,flexGrow:W?0:1,flexShrink:W?0:1}:void 0,conversations:L,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:p,setActionLogs:m,isStandalone:f,hasRegisteredMachines:g,userName:w,groupIndex:M,isFocused:s&&A===M,onFocus:()=>d(M),isSplitMode:s,numGroups:r,onMoveTab:(U,C)=>{C==="left"&&M>0?b(U,M-1):C==="right"&&M<r-1?b(U,M+1):C==="split-left"&&r<4?y(U,M,"left"):C==="split-right"&&r<4&&y(U,M,"right")},onReceiveTab:U=>b(U,M),onActiveTabChange:U=>k(C=>(C[M]??null)===(U??null)?C:{...C,[M]:U}),initialActiveTabId:_[M],initialTabOrder:I[M],onTabOrderChange:U=>j(C=>{const R=C[M]||[];return R.length===U.length&&R.every((B,S)=>B===U[S])?C:{...C,[M]:U}}),onHideTab:v,allowTabShortcuts:x,notificationStateBySessionId:E,liveSessionInboxState:T})]},M)})})}function al({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?ft.onScreenshot("ide-page",(m,f)=>{if(m!==e)return;const g=new FileReader;g.onload=()=>i(g.result),g.readAsDataURL(f)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var m;return e?((m=ft.onStatus)==null?void 0:m.call(ft,(f,g)=>{f===e&&g!=null&&g.screenshotUsage&&l(g.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,s]),o.useEffect(()=>{const p=e?ft.get(e):null;if(!(!p||r!=="connected"))return n!=="chat"&&s?p.startScreenshots(s):p.stopScreenshots(s),()=>{p.stopScreenshots(s)}},[n,r,s,e]);const u=o.useCallback(async(p,m)=>{const f=e?ft.get(e):null;return!f||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):f.sendInput(p,m,s)},[e,r,s]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:u}}const ol="adhdev-dashboard-action-shortcuts",Ih=1200,Ah={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Mh(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function nt(e,s){switch(e){case"openShortcutHelp":return"?";case"hideCurrentTab":return s?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return s?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return s?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return s?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return s?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return s?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return s?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return s?"⌘+⌥+=":"Ctrl+Alt+\\";case"splitActiveTabDown":return s?"⌘+⌥+-":"Ctrl+Alt+-";case"focusLeftPane":return s?"⌘+⌥+[":"Ctrl+Alt+←";case"focusRightPane":return s?"⌘+⌥+]":"Ctrl+Alt+→";case"focusUpPane":return s?"⌘+⌥+U":"Ctrl+Alt+↑";case"focusDownPane":return s?"⌘+⌥+J":"Ctrl+Alt+↓";case"moveActiveTabToLeftPane":return s?"⌘+⌥+,":"Ctrl+Alt+Shift+←";case"moveActiveTabToRightPane":return s?"⌘+⌥+.":"Ctrl+Alt+Shift+→";case"moveActiveTabToUpPane":return s?"⌘+⌥+I":"Ctrl+Alt+Shift+↑";case"moveActiveTabToDownPane":return s?"⌘+⌥+K":"Ctrl+Alt+Shift+↓";case"triggerPrimaryApprovalAction":return s?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return s?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return s?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return s?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return s?"⌥+[":"Ctrl+Alt+[";case"selectNextGroupTab":return s?"⌥+]":"Ctrl+Alt+]";case"toggleCliView":return s?"⌥+T":"Ctrl+Alt+T"}}function il(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:nt("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:nt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:nt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:nt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:nt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:nt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:nt("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:nt("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:nt("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:nt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:nt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:nt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:nt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:nt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:nt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:nt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:nt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:nt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:nt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:nt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:nt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:nt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:nt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:nt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:nt("toggleCliView",e)}]}function ba(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function cn(e){const s=Object.fromEntries(il(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(ol)||"{}"),n={...s,...r};for(const[a,i]of Object.entries(Ah))n[a]===i&&(n[a]=s[a]);return n}catch{return s}}function cl(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Th({enabled:e=!0,onTrigger:s}){const r=Mh(),[n,a]=o.useState(()=>cn(r)),[i,c]=o.useState(null),[l,u]=o.useState([]),p=o.useRef({parts:[],timer:null}),m=o.useCallback(d=>{const b=[];return d.metaKey&&b.push(r?"⌘":"Meta"),d.ctrlKey&&b.push("Ctrl"),d.altKey&&b.push(r?"⌥":"Alt"),d.shiftKey&&d.key.length!==1&&b.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(d.key)?null:(b.push(cl(d.key)),b.join("+"))},[r]),f=o.useCallback(d=>{a(d);try{localStorage.setItem(ol,JSON.stringify(d))}catch{}},[]);o.useEffect(()=>{const d=cn(r),b=Object.entries(n),y=Object.entries(d);b.length===y.length&&b.every(([h,N])=>d[h]===N)||f(d)},[n,r,f]);const g=o.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),w=o.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},Ih))},[]);o.useEffect(()=>{if(!i)return;const d=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){c(null),u([]);return}const y=m(b);if(!y)return;const N=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(y);if(l.length===0&&N){u([y]);return}const k=[...l,y].slice(0,2).join(" "),I={...n};for(const[j,v]of Object.entries(I))v===k&&delete I[j];I[i]=k,f(I),c(null),u([])};return window.addEventListener("keydown",d,!0),()=>window.removeEventListener("keydown",d,!0)},[n,m,f,i,l]),o.useEffect(()=>{if(!e||i)return;const d=b=>{if(b.defaultPrevented)return;const y=m(b);if(!y)return;const h=b.metaKey||b.ctrlKey||b.altKey;if(ba(b.target)&&!h)return;const N=p.current.parts,_=h?[y]:[...N.slice(-1),y].slice(-2),k=_.join(" "),I=_[_.length-1],j=Object.entries(n).filter(([,L])=>!!L),v=j.find(([,L])=>L===k);if(v){b.preventDefault(),g(),s(v[0]);return}if(j.some(([,L])=>L.startsWith(`${k} `))){b.preventDefault(),p.current.parts=_,w();return}const E=j.find(([,L])=>L===I);if(E){b.preventDefault(),g(),s(E[0]);return}if(j.some(([,L])=>L.startsWith(`${I} `))){b.preventDefault(),p.current.parts=[I],w();return}g()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n,w,e,m,s,g,i]),o.useEffect(()=>()=>g(),[g]);const A=o.useMemo(()=>il(r),[r]);return{isMac:r,actionDefinitions:A,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:f}}function Lh({isTabInPopout:e,isTabFloating:s,tabShortcut:r,actionShortcuts:n}){const a=[];return e?(s&&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})):s?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 _h(e){return e.some(s=>s.type!=="adhdev-daemon")||e.some(s=>s.type==="adhdev-daemon"&&!!s.machine)}function ci({hasStoredLayout:e,initialDataLoaded:s,visibleConversationCount:r,ides:n}){return!e||r>0?!1:s?!_h(n):!0}const ll=o.createContext(null);function wn(){const e=o.useContext(ll);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Qr(e){return lt(e)||e.tabKey}function Rh(e){return`remote:${e}`}function Zt(e){return e.startsWith("remote:")}function li(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Fn(e){var r,n,a,i,c;const s=e==null?void 0:e.defaultView;if(s)try{s.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=s.requestAnimationFrame)==null||c.call(s,()=>{var l,u;try{s.focus(),(u=(l=e==null?void 0:e.body)==null?void 0:l.focus)==null||u.call(l)}catch{}})}catch{}}function Hr(e,s){e.classList.remove(ta.className,sa.className),e.classList.add(s==="light"?ta.className:sa.className)}function di(e){return e?Array.from(new Set(e.groups.map(s=>{var r,n;return(n=(r=s.element)==null?void 0:r.ownerDocument)==null?void 0:n.defaultView}).filter(s=>!!s&&s!==window))):[]}function Ph(e){const[,s]=o.useState(0);o.useEffect(()=>{const r=()=>s(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 Dh(e,s,r){var c;const n=[s];let a;for(const l of n){let u;for(const p of l){const m=e.addPanel({id:p.tabKey,component:"conversation",title:Qr(p),params:{kind:"conversation",tabKey:p.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});u||(u=m.id)}a=u??a}return r??((c=s[0])==null?void 0:c.tabKey)??null}function ui(e,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...e.panels])Zt(n.id)||r.has(n.id)||e.removePanel(n);for(const n of s){const a=e.getPanel(n.tabKey);if(a){a.update({params:{tabKey:n.tabKey}}),a.title!==Qr(n)&&a.api.setTitle(Qr(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:Qr(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 mi(e,s,r){var u,p;const n=r?Rh(r):null;for(const m of[...e.panels])Zt(m.id)&&(!n||m.id!==n)&&e.removePanel(m);if(!r||!n)return;const a=Ot(s,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=kc(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)??((p=e.panels.find(m=>!Zt(m.id)))==null?void 0:p.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function Eh({params:e,api:s}){var f;const r=wn(),n=o.useRef(null),[a,i]=o.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=xn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(s.isActive);const g=[s.onDidActiveChange(w=>i(w.isActive)),s.onDidActiveGroupChange(w=>{if(!s.isActive&&!w.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const w of g)w.dispose()}},[s]);const u=o.useMemo(()=>c?r.ides.find(g=>g.id===c.routeId):void 0,[r.ides,c]),p=o.useMemo(()=>c?r.actionLogs.filter(g=>g.routeId===c.tabKey):[],[r.actionLogs,c]);if(!c)return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:t.jsx(ro,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,suppressGuide:r.hasDetachedConversationPanels})});const m=!Ze(c)&&Bs(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(to,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:m,ideEntry:u,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:p,userName:r.userName,scrollToBottomRequestNonce:((f=r.scrollToBottomRequest)==null?void 0:f.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a})})}function $h({params:e}){var u;const s=wn(),r=o.useMemo(()=>Ot([...s.conversationsByTabKey.values()],e.routeId),[s.conversationsByTabKey,e.routeId]),n=o.useMemo(()=>s.ides.find(p=>p.id===e.routeId),[s.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}=al({doId:a,targetSessionId:r?oc(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?t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:t.jsx(Hi,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:c,transportType:r.transport,onAction:l})}):t.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 Kh(){const e=wn();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(ro,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,suppressGuide:e.hasDetachedConversationPanels})})}function Bh(e){var w,A;Ph(e);const s=wn(),r=o.useCallback(d=>{"button"in d&&d.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const d=Ot([...s.conversationsByTabKey.values()],e.params.routeId),b=((w=e.api.group.activePanel)==null?void 0:w.id)===e.api.id,y=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${b?" is-active":""}${y?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(d==null?void 0:d.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:d!=null&&d.machineName?t.jsxs(t.Fragment,{children:[t.jsx("span",{children:"Live remote view"}),t.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),t.jsx("span",{className:"adhdev-dockview-tab-machine",children:d.machineName})]}):t.jsx("span",{children:"Live remote view"})})]})]})}const n=s.conversationsByTabKey.get(e.params.tabKey);if(!n)return t.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:t.jsx("div",{className:"adhdev-dockview-tab-copy",children:t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const a=((A=e.api.group.activePanel)==null?void 0:A.id)===e.api.id,i=e.api.isGroupActive,c=fn(n,s.liveSessionInboxState,{isOpenConversation:a,notificationStateBySessionId:s.notificationStateBySessionId}),l=c.isReconnecting,u=c.isConnecting,p=c.isGenerating,m=c.isWaiting,f=c.unread,g=s.tabShortcuts[n.tabKey];return t.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:lt(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:d=>{var b;d.preventDefault(),r(d),s.openTabContextMenu({x:d.clientX,y:d.clientY,tabKey:n.tabKey,sourceDocument:((b=d.target)==null?void 0:b.ownerDocument)??document})},children:[f&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:p?t.jsx("div",{className:"tab-spinner"}):m?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):u?t.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:lt(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ps(n)}):u?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ps(n)}):t.jsx("span",{children:ps(n)})})]}),g&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:g,children:g})]})}function Wh({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:u,initialDataLoaded:p,userName:m,toggleHiddenTab:f,actionShortcuts:g,registerActionHandlers:w,onActiveTabChange:A,requestedActiveTabKey:d,requestedRemoteIdeId:b,onRequestedActiveTabConsumed:y,scrollToBottomRequest:h,notificationStateBySessionId:N,liveSessionInboxState:_}){var Tt,J,Re;const{theme:k}=za(),{sendCommand:I}=Pt(),j=o.useRef(null),v=o.useRef(null),x=o.useRef(!1),E=o.useRef(!1),T=o.useRef(!1),L=o.useRef(null),M=o.useRef([]),[W,U]=o.useState(null),[C,R]=o.useState(!1),[B,S]=o.useState(!1),[D,Y]=o.useState(0),q=o.useRef(null),H=o.useMemo(()=>zc(typeof window<"u"?window.innerWidth:1280),[]),re=o.useRef(typeof window>"u"?{}:vf(H)),ie=o.useMemo(()=>new Map(e.map(P=>[P.tabKey,P])),[e]),Se=o.useMemo(()=>{const P=j.current;return P?P.groups.some(O=>{try{const F=O.model.location.type;return F!=="floating"&&F!=="popout"?!1:O.panels.some(G=>ie.has(G.id))}catch{return!1}}):!1},[ie,D,e]),X=o.useCallback(()=>{var P;(P=j.current)==null||P.focus()},[]),fe=o.useCallback(P=>{const O=document,F=P.document;for(const Ae of O.querySelectorAll('link[rel="stylesheet"]')){const Oe=F.createElement("link");Oe.rel="stylesheet",Oe.href=Ae.href,Ae.crossOrigin&&(Oe.crossOrigin=Ae.crossOrigin),F.head.appendChild(Oe)}for(const Ae of O.querySelectorAll("style")){const Oe=F.createElement("style");Oe.textContent=Ae.textContent,F.head.appendChild(Oe)}const G=[];for(const Ae of O.styleSheets)try{for(const Oe of Ae.cssRules)Oe instanceof CSSStyleRule&&(Oe.selectorText===":root"||Oe.selectorText==="html")&&G.push(Oe.cssText)}catch{}if(G.length>0){const Ae=F.createElement("style");Ae.textContent=G.join(`
43
+ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:x,onCancel:()=>m(null)})]})}const _p=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Rp(){const{preference:e,setPreference:s}=za();return t.jsx("div",{className:"flex gap-2",children:_p.map(r=>t.jsxs("button",{onClick:()=>s(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:[t.jsx("span",{children:r.icon}),r.label]},r.id))})}function Pp(e){const s=e.trim();return/^#[0-9a-fA-F]{6}$/.test(s)?s:/^#[0-9a-fA-F]{3}$/.test(s)?`#${s[1]}${s[1]}${s[2]}${s[2]}${s[3]}${s[3]}`:null}function Dp(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Kn(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function zo(e){const{r:s,g:r,b:n}=Dp(e);return .2126*Kn(s)+.7152*Kn(r)+.0722*Kn(n)}function Vo(e,s){const r=zo(e),n=zo(s),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function $c(e){const s=Pp(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return Vo(s,r)>=Vo(s,n)?r:n}const ma={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},pa={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},Ep=[{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"}}}],Kc="adhdev-chat-theme",Bc="adhdev-chat-theme-custom";function Yr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Kc)||"ember"}catch{return"ember"}}function Wt(e){try{const s=localStorage.getItem(Bc);if(s){const r=JSON.parse(s);return{...e==="dark"?ma:pa,...r[e]}}}catch{}return e==="dark"?ma:pa}function Dr(e,s){try{localStorage.setItem(Bc,JSON.stringify({dark:e,light:s}))}catch{}}function $t(e,s){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}, ${s})`}function on(e,s){const r=Math.min(255,parseInt(e.slice(1,3),16)+s),n=Math.min(255,parseInt(e.slice(3,5),16)+s),a=Math.min(255,parseInt(e.slice(5,7),16)+s);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const $p={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function ir(e,s){var a;const r=(a=$p[e])==null?void 0:a[s];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",on(r,24)),n.style.setProperty("--accent-on-primary",$c(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${on(r,18)})`),n.style.setProperty("--border-accent",$t(r,.35)),n.style.setProperty("--nav-active-bg",$t(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${$t(r,.06)}`)}function xs(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",$t(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",$t(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",$t(e.borderSubtle,.25)),s.style.setProperty("--text-primary",e.textPrimary),s.style.setProperty("--text-secondary",e.textSecondary),s.style.setProperty("--text-muted",e.textMuted),s.style.setProperty("--border-subtle",$t(e.borderSubtle,.5)),s.style.setProperty("--border-default",$t(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",on(e.accentColor,30)),s.style.setProperty("--accent-on-primary",$c(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${on(e.accentColor,40)})`),s.style.setProperty("--border-accent",$t(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",$t(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${$t(e.accentColor,.06)}`),s.style.setProperty("--chat-user-bg",e.userBubble),s.style.setProperty("--chat-user-color",e.userText),s.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),s.style.setProperty("--chat-assistant-bg",e.assistantBubble),s.style.setProperty("--chat-assistant-color",e.assistantText),s.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),s.style.setProperty("--chat-assistant-border",`1px solid ${$t(e.accentColor,.12)}`),s.style.setProperty("--chat-container-bg",e.containerBg),s.style.setProperty("--dashboard-pane-bg",e.containerBg),s.style.setProperty("--chat-thought-accent",e.accentColor),s.style.setProperty("--chat-tool-accent",e.accentColor),s.style.setProperty("--chat-action-color",e.accentColor),s.style.setProperty("--chat-send-bg",e.sendButton),s.style.setProperty("--chat-input-border",e.inputBorder)}function Va(){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 Kp(e){try{localStorage.setItem(Kc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=bs()?"dark":"light";xs(Wt(s))}else Va(),ir(e,bs()?"dark":"light")}function Bp(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Yr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=bs()?"dark":"light";xs(Wt(s))}else Va(),ir(e,bs()?"dark":"light")}function bs(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Nt({label:e,value:s,onChange:r}){return t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[t.jsx("input",{type:"color",value:s,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),t.jsx("input",{type:"text",value:s,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 Qs({title:e,children:s}){return t.jsxs("div",{style:{marginBottom:14},children:[t.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}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s})]})}function Wp({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,a]=o.useState(()=>Wt(r));o.useEffect(()=>{a(Wt(r))},[r]);const i=o.useCallback((c,l)=>{a(u=>{const p={...u,[c]:l},f=Wt(r==="dark"?"light":"dark");return r==="dark"?Dr(p,f):Dr(f,p),xs(p),s(p),p})},[r,s]);return t.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[t.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",t.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"]})]}),t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsxs(Qs,{title:"App Background",children:[t.jsx(Nt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),t.jsx(Nt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),t.jsx(Nt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),t.jsxs(Qs,{title:"App Text",children:[t.jsx(Nt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),t.jsx(Nt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),t.jsx(Nt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),t.jsxs(Qs,{title:"Borders & Accent",children:[t.jsx(Nt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),t.jsx(Nt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),t.jsx(Nt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),t.jsxs("div",{children:[t.jsxs(Qs,{title:"Chat Bubbles",children:[t.jsx(Nt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),t.jsx(Nt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),t.jsx(Nt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),t.jsx(Nt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),t.jsxs(Qs,{title:"Chat Layout",children:[t.jsx(Nt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),t.jsx(Nt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),t.jsx(Nt,{label:"Input border",value:n.inputBorder,onChange:c=>i("inputBorder",c)}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[t.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)"}}),t.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),t.jsx("button",{onClick:()=>{const c=e?ma:pa,u=Wt(e?"light":"dark");e?Dr(c,u):Dr(u,c),a(c),xs(c),s(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 Op(){const[e,s]=o.useState(Yr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Wt("dark"));o.useEffect(()=>{n(bs());const u=new MutationObserver(()=>{const f=bs();n(f);const g=Yr();g==="custom"?xs(Wt(f?"dark":"light")):ir(g,f?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const p=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=bs();n(f);const g=Yr();g==="custom"?xs(Wt(f?"dark":"light")):ir(g,f?"dark":"light")};return p.addEventListener("change",m),()=>{u.disconnect(),p.removeEventListener("change",m)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?xs(Wt(r?"dark":"light")):(Va(),ir(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Wt(r?"dark":"light"))},[r]);const c=u=>{s(u),Kp(u)},l=[...Ep,{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 t.jsxs("div",{children:[t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:l.map(u=>{const p=e===u.id,m=r?u.preview.dark:u.preview.light,f=u.id==="honey"||u.id==="ember"?"#1a1a1a":u.id==="custom"?a.userText:"#fff";return t.jsxs("button",{onClick:()=>c(u.id),className:"text-left rounded-xl p-3 transition-all",style:{background:p?"var(--bg-glass-hover)":"var(--bg-glass)",border:p?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:p?1:.75},children:[t.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:"Hello! How can I help?"}),t.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.userBubble,color:f},children:"Fix the bug please"}),t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:"On it! ✨"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[p&&t.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:u.id==="custom"?"🎨 Custom":u.name}),t.jsx("div",{className:"text-[10px] text-text-muted",children:u.description})]})]})]},u.id)})}),e==="custom"&&t.jsx(Wp,{dark:r,onColorsChange:u=>i(u)})]})}const Ga="adhdev_mobileDashboardMode_v1",fa="adhdev:mobile-dashboard-mode-change";function qa(){try{return localStorage.getItem(Ga)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Hp(e){if(typeof window>"u")return()=>{};const s=a=>{e(a??qa())},r=a=>{const i=a.detail;s(i)},n=a=>{a.key&&a.key!==Ga||s()};return window.addEventListener(fa,r),window.addEventListener("storage",n),()=>{window.removeEventListener(fa,r),window.removeEventListener("storage",n)}}function Up(e){try{localStorage.setItem(Ga,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(fa,{detail:e}))}function Fp(){const[e,s]=o.useState(!0);return o.useEffect(()=>{s(qa()==="chat")},[]),t.jsx(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Qt,{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=>{s(r),Up(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}function zp(e,s,r){return{...e||{},id:s,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 Vp(e,s){const{sendData:r}=Pt(),{injectEntries:n,getIdes:a}=en(),i=Array.from(new Set(e.filter(Boolean))).join("|");o.useEffect(()=>{if(!(s!=null&&s.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const l=c.map(u=>as.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:s==null?void 0:s.intervalMs}},p=>{const m=a().find(g=>g.id===u),f=zp(m,u,p);n([f])}));return()=>{l.forEach(u=>u())}},[i,a,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}const Gp=4e3;function Wc(e,s){const{sendData:r}=Pt(),[n,a]=o.useState(null),[i,c]=o.useState(!1);return o.useEffect(()=>{if(!e){a(null),c(!1);return}if(!(s!=null&&s.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const u=as.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(s==null?void 0:s.includeSessions)!==!1,...typeof(s==null?void 0:s.limit)=="number"?{limit:s.limit}:{},...typeof(s==null?void 0:s.intervalMs)=="number"?{intervalMs:s.intervalMs}:{}}},p=>{l&&(clearTimeout(l),l=null),a(p.diagnostics),c(!1)});return u.initialSendAccepted?l=setTimeout(()=>{c(!1)},Gp):c(!1),()=>{l&&clearTimeout(l),u()}},[e,s==null?void 0:s.enabled,s==null?void 0:s.includeSessions,s==null?void 0:s.intervalMs,s==null?void 0:s.limit,r]),{diagnostics:n,loading:i,applyDiagnostics:a}}function qp(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Oc(e){const{sendData:s}=Pt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=qp(e);if(!a||!e.sessionId||!s){n({});return}const i=as.subscribe({sendData:s},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}),Ds.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()}},[e.daemonId,e.routeId,e.sessionId,s]),r}const Hc="adhdev_hiddenTabs";function Yp(){try{const e=localStorage.getItem(Hc);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function Ns(e){try{localStorage.setItem(Hc,JSON.stringify([...e]))}catch{}}function Er(e){return Aa(e)}function Ya(e,s){return ss(s).some(r=>e.has(r))}function Xp(){const[e,s]=o.useState(Yp),r=o.useCallback(p=>{s(m=>{const f=new Set(m);return f.has(p)?f.delete(p):f.add(p),Ns(f),f})},[]),n=o.useCallback(p=>{s(m=>{if(m.has(p))return m;const f=new Set(m);return f.add(p),Ns(f),f})},[]),a=o.useCallback(p=>{s(m=>{if(!m.has(p))return m;const f=new Set(m);return f.delete(p),Ns(f),f})},[]),i=o.useCallback(()=>{s(p=>{if(p.size===0)return p;const m=new Set;return Ns(m),m})},[]),c=o.useCallback((p,m)=>{s(f=>{const g=new Set(f);for(const w of m)g.add(w);return Ns(g),g})},[]),l=o.useCallback((p,m)=>{s(f=>{const g=new Set(f);for(const w of m)g.delete(w);return Ns(g),g})},[]),u=o.useCallback(p=>Ya(e,p),[e]);return{hiddenTabs:e,toggleTab:r,hideTab:n,showTab:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function Uc(e){return e instanceof Error?e.message:String(e||"")}function Xa(e){const s=Uc(e);return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("P2P channel not open")||s.includes("P2P not available")||s.includes("P2P data channel closed")||s.includes("P2P receiver stopped")}function Qa(e){const s=Uc(e);return s.includes("P2P command timeout")||s.includes("P2P data channel closed")||s.includes("P2P receiver stopped")}function Go(e,s){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=s[r];return!n||e.mode===n?e:{...e,mode:n}}function Qp(e,s){if(!Array.isArray(e)||e.length===0||!s||Object.keys(s).length===0)return e;let r=!1;const n=e.map(a=>{const i=Go(a,s),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>Go(u,s)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function Fc(e,s){if(!s)return null;for(const r of e){if(r.sessionId===s&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal";for(const n of r.childSessions||[])if(n.id===s&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal"}return null}function Jp(e,s){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,i]of Object.entries(e))Fc(s,a)===i&&(delete n[a],r=!0);return r?n:e}function Zp({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{Zi()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:jc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Lu(a),o.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(l=>{const u=Date.now(),p={};for(const[m,f]of Object.entries(l))u-f<5e3&&(p[m]=f);return Object.keys(p).length===Object.keys(l).length?l:p})},5500);return()=>clearTimeout(c)},[s,r]),o.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const u=l.filter(p=>p.timestamp>c).slice(-100);return u.length===l.length?l:u})},6e4);return()=>clearInterval(i)},[n]),null}function ef(e){const s=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of s){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 Bn(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==s[r])return!1;return!0}function tf(e){let s=2166136261;for(let r=0;r<e.length;r+=1)s^=e.charCodeAt(r),s=Math.imul(s,16777619)>>>0;return s.toString(16).padStart(8,"0")}function qo(e){if(!e)return"";const s=Array.isArray(e.messages)?e.messages:[],r=s[s.length-1],n=r?tf($s(r.content)):"";return[e.id||"",e.title||"",e.status||"",s.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 sf(e){const s=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.lastUpdated||""),qo(e.activeChat),...s.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastUpdated||""),qo(r.activeChat)].join(":"))].join("|")}function rf(e,s){const r=Date.now();return e.map(n=>{const a=s[n.tabKey];return a&&r-a<5e3?{...n,messages:[],title:""}:n})}function nf(e,s){const r=[],n=e.sessionId||e.instanceId;r.push({key:e.id,ref:s[e.id]}),n&&r.push({key:n,ref:s[n]});for(const a of e.childSessions||[]){const i=a.id||a.providerType,c=`${e.id}:${i}`;r.push({key:c,ref:s[c]}),r.push({key:a.id,ref:s[a.id]})}return r}function af(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r].key!==s[r].key||e[r].ref!==s[r].ref)return!1;return!0}function of(e,s){const r=new Map;for(const n of e){const a=s.get(n.routeId)||n;for(const i of ss({routeId:n.routeId}))r.set(i,a);for(const i of ss({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of ss({tabKey:n.tabKey}))r.set(i,n)}return r}function cf(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function lf(e){const s=cf(e);if(!s)return`empty:${e.messages.length}`;if(s.id)return`id:${String(s.id)}`;if(s._localId)return`local:${String(s._localId)}`;const r=String(s.role||""),n=$s(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function df({ides:e,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:a}){const i=o.useMemo(()=>ef(e),[e]),c=o.useMemo(()=>Ac(e),[e]),l=o.useRef([]),u=o.useRef([]),p=o.useRef([]),m=o.useRef(new Map),f=o.useRef(new Map),g=o.useMemo(()=>{const k=new Map,I=[];for(const E of i){const{connectionState:T="new",machineName:L}=Mc(E,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),M=nf(E,r),W=sf(E),U=m.current.get(E.id);if(U&&U.ide===E&&U.sourceSignature===W&&U.connectionState===T&&U.machineName===L&&af(U.localRefs,M)){k.set(E.id,U),I.push(...U.conversations);continue}const C=Fa(E,r,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),R={ide:E,sourceSignature:W,connectionState:T,machineName:L,localRefs:M,conversations:C};k.set(E.id,R),I.push(...C)}m.current=k;const j=new Map,v=E=>{const T=lf(E),L=f.current.get(E.tabKey);if(L&&L.signature===T)return j.set(E.tabKey,L),L.timestamp;const M={signature:T,timestamp:ic(E)||(L==null?void 0:L.timestamp)||0};return j.set(E.tabKey,M),M.timestamp},x=[...I].sort((E,T)=>cc(E,T,v));return f.current=j,x},[i,r,s,c]),w=o.useMemo(()=>{const k=rf(g,n);return Bn(l.current,k)?l.current:(l.current=k,k)},[g,n]),A=o.useMemo(()=>{const k=new Map,I=Array.from(new Set(w.map(j=>j.routeId)));for(const j of I){const v=Ot(w,j);v&&k.set(j,v)}return k},[w]),d=o.useMemo(()=>{const k=new Map;for(const I of w){const j=A.get(I.routeId),v=I.streamSource==="native"&&j?j:I;for(const x of ss({providerSessionId:I.providerSessionId,sessionId:I.sessionId}))k.set(x,v)}return k},[w,A]),b=o.useMemo(()=>of(w,A),[w,A]),y=o.useCallback(k=>{if(k)return d.get(k)},[d]),h=o.useCallback(k=>{if(k)return b.get(k)},[b]),N=o.useMemo(()=>{const k=w.filter(I=>!Ya(a,I));return Bn(u.current,k)?u.current:(u.current=k,k)},[w,a]),_=o.useMemo(()=>{const k=N.map(I=>I.tabKey);return Bn(p.current,k)?p.current:(p.current=k,k)},[N]);return{chatIdes:i,conversations:w,visibleConversations:N,visibleTabKeys:_,resolveConversationBySessionId:y,resolveConversationByTarget:h}}function uf({isMobile:e,urlActiveTab:s,resolveConversationBySessionId:r,setSearchParams:n}){const a=o.useMemo(()=>{var l;return e||!s?null:((l=r(s))==null?void 0:l.tabKey)??null},[e,r,s]),i=o.useMemo(()=>{var l;return!e||!s?null:((l=r(s))==null?void 0:l.tabKey)??null},[e,r,s]),c=o.useCallback(()=>{s&&n(l=>{const u=new URLSearchParams(l);return u.delete("activeTab"),u},{replace:!0})},[n,s]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function mf({ides:e,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:a}){o.useEffect(()=>{st.setIdes(e)},[e]),o.useEffect(()=>{st.setResolveAction((i,c,l)=>{s(i,c,l).catch(()=>{})})},[s]),o.useEffect(()=>{const i=st.onToast(u=>{r(m=>m.some(g=>g.message===u.message&&u.timestamp-g.timestamp<3e3)?m:[...m.slice(-4),{id:u.id,message:u.message,type:u.type,timestamp:u.timestamp,targetKey:u.targetKey,actions:u.actions}]);const p=u.duration||5e3;setTimeout(()=>r(m=>m.filter(f=>f.id!==u.id)),p)}),c=st.onSystemMessage((u,p)=>{var w,A;const m=a(u),f=(w=p._localId)==null?void 0:w.startsWith("sys_approval_"),g=!!(m&&(m.status==="waiting_approval"||(A=m.modalButtons)!=null&&A.length||m.modalMessage));f&&g||n(d=>({...d,[u]:[...d[u]||[],p]}))}),l=st.onClearSystemMessage((u,p)=>{n(m=>{var f;return(f=m[u])!=null&&f.length?{...m,[u]:m[u].filter(g=>{var w;return!(g.role==="system"&&((w=g._localId)!=null&&w.startsWith(p)))})}:m})});return()=>{i(),c(),l()}},[r,n]),o.useEffect(()=>{const i=gc.on("status_event",c=>{st.handleRawEvent(c,"ws")});return()=>{i()}},[]),o.useEffect(()=>{var c;const i=l=>{var b;const u=l.data;if((u==null?void 0:u.type)!=="notification_action"||typeof u.action!="string"||!u.action.startsWith("approval_")||!(u.daemonId||u.targetSessionId||u.targetKey))return;const p=u.targetSessionId||u.targetKey||u.daemonId,m=a(p),f=(m==null?void 0:m.routeId)||u.daemonId;if(!f)return;const g=Number(u.buttonIndex),w=u.button||((b=m==null?void 0:m.modalButtons)==null?void 0:b[g])||"Approve",A=String(w).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),d=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(A);s(f,"resolve_action",{action:d?"approve":"reject",button:w,...Number.isFinite(g)&&{buttonIndex:g},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...u.targetSessionId&&{targetSessionId:u.targetSessionId}}).catch(y=>console.error("[SW Action] approval failed:",y))};return(c=navigator.serviceWorker)==null||c.addEventListener("message",i),()=>{var l;return(l=navigator.serviceWorker)==null?void 0:l.removeEventListener("message",i)}},[a,s])}const pf="adhdev_dashboardLayout_v1",ff="adhdev_dashboardDockview_v1",hf="adhdev_dashboardDockviewHiddenRestore_v1",Js={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Ja(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function zc(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Vc(e){return`${pf}:${e}`}function xf(e){const s=Vc(e);return Ja(s,null)}function bf(e,s){try{const r=s.groupAssignments.length===0&&s.focusedGroup===0&&Object.keys(s.groupActiveTabIds).length===0&&Object.keys(s.groupTabOrders).length===0&&s.groupSizes.length===0,n=Vc(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function Gc(e){return`${ff}:${e}`}function gf(e){const s=Gc(e);return Ja(s,null)}function yf(e,s){try{const r=Gc(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function qc(e){return`${hf}:${e}`}function vf(e){const s=qc(e);return Ja(s,{})}function wf(e,s){try{const r=qc(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function jf(){return{groupAssignments:[...Js.groupAssignments],focusedGroup:Js.focusedGroup,groupActiveTabIds:{...Js.groupActiveTabIds},groupTabOrders:{...Js.groupTabOrders},groupSizes:[...Js.groupSizes]}}function kf(){const[e]=o.useState(()=>zc(typeof window<"u"?window.innerWidth:1280)),[s,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,u]=o.useState({}),[p,m]=o.useState([]),[f,g]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[w,A]=o.useState(!1),d=o.useCallback(()=>{if(w)return;const b=xf(e)??jf();r(new Map(b.groupAssignments)),a(b.focusedGroup),c(b.groupActiveTabIds),u(b.groupTabOrders),m(b.groupSizes),A(!0)},[w,e]);return o.useEffect(()=>{w&&bf(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:p})},[w,e,s,n,i,l,p]),o.useEffect(()=>{const b=window.matchMedia("(max-width: 767px)"),y=h=>g(h.matches);return b.addEventListener("change",y),()=>b.removeEventListener("change",y)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:a,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:l,setGroupTabOrders:u,groupSizes:p,setGroupSizes:m,isMobile:f,hasHydratedStoredLayout:w,hydrateStoredLayout:d}}function Sf(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=Ia(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Nf({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:l,setSearchParams:u,historyModalOpen:p,activeConv:m,isRefreshingHistory:f,ides:g,handleRefreshHistory:w}){const A=o.useRef(!1),d=o.useRef(!1),b=o.useRef(null),y=o.useRef(!1);o.useEffect(()=>{if(!e||A.current||s.length===0)return;if(!a){i();return}const h=r(e);if(!h)return;const N=n.get(h.tabKey)??0;c(_=>({..._,[N]:h.tabKey})),l(N),A.current=!0,d.current=!0,b.current!=null&&(window.clearTimeout(b.current),b.current=null),u(_=>{const k=new URLSearchParams(_);return k.delete("activeTab"),k},{replace:!0})},[e,s,r,n,a,i,c,l,u]),o.useEffect(()=>{if(!(d.current||a)&&s.length!==0){if(!e){i(),d.current=!0;return}if(A.current){d.current=!0;return}if(b.current==null)return b.current=window.setTimeout(()=>{b.current=null,!(d.current||a)&&(i(),d.current=!0)},1500),()=>{b.current!=null&&(window.clearTimeout(b.current),b.current=null)}}},[e,s.length,a,i]),o.useEffect(()=>{if(!p){y.current=!1;return}if(!m||y.current||f)return;const h=g.find(N=>N.id===m.routeId);h&&(!h.chats||h.chats.length===0||Sf(h.chats,m))&&(y.current=!0,w())},[p,m,f,g,w]),o.useEffect(()=>{if(!m)return;let h=null,N=0,_=-1,k=0;const I=()=>{h=null;const j=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(x=>x.offsetParent!==null);if(j.length===0){N<18&&(N+=1,h=requestAnimationFrame(I));return}let v=0;for(const x of j)x.scrollTop=x.scrollHeight,v+=x.scrollHeight;v===_?k+=1:(k=0,_=v),N+=1,!(k>=2||N>=18)&&(h=requestAnimationFrame(I))};return h=requestAnimationFrame(I),()=>{h!=null&&cancelAnimationFrame(h)}},[m==null?void 0:m.tabKey])}function Cf({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[u,p]=o.useState(null),[m,f]=o.useState(null),g=o.useMemo(()=>{if(e||!n)return null;const y=l(n);return y&&!tt(y)&&!Ze(y)?y:null},[e,n,l]),w=o.useMemo(()=>{const y=u==null?void 0:u.routeId;if(!y)return null;const h=u!=null&&u.tabKey?i.find(N=>N.tabKey===u.tabKey):a?i.find(N=>N.tabKey===a):null;return(h==null?void 0:h.routeId)===y?h:Ot(i,y)},[i,u,a]),A=o.useMemo(()=>{if(w)return c.find(y=>y.id===w.routeId)},[c,w]);o.useEffect(()=>{g&&(p({routeId:g.routeId,tabKey:Ro(g)}),f(g),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,g]);const d=o.useCallback(y=>{y&&(p({routeId:y.routeId,tabKey:Ro(y)}),f(y))},[]),b=o.useCallback(()=>{p(null),f(null)},[]);return{remoteDialogConv:w,remoteDialogIdeEntry:A,remoteDialogActiveConv:m,setRemoteDialogActiveConv:f,openRemoteDialog:d,closeRemoteDialog:b}}function Wn(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0];if((r==null?void 0:r.active)===!0)return!0;const n=Ia(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Yo({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:a,setLocalUserMessages:i,setClearedTabs:c}){const[l,u]=o.useState(!1),[p,m]=o.useState(!1),f=o.useCallback(async d=>{try{await e("standalone","launch_ide",{ideType:d,enableCdp:!0})}catch(b){console.error("Launch failed",b)}},[e]),g=o.useCallback(async(d,b)=>{try{const y=d||(s==null?void 0:s.daemonId)||"",h=await e(y,"switch_chat",{id:b,sessionId:b,...Rs(s)}),N=h==null?void 0:h.result;if((h==null?void 0:h.success)===!0||N==="switched"||N==="switched-by-title")return;N===!1||N==="not_found"?Xs(a,"⚠️ Session tab not found — try refreshing history"):typeof N=="string"&&N.startsWith("error:")?Xs(a,`⚠️ Switch error: ${N}`):Xs(a,"⚠️ Session switch failed")}catch(y){console.error("Switch failed",y),Xs(a,`❌ Switch failed: ${y.message||"connection error"}`)}},[s,e,a]),w=o.useCallback(async()=>{if(!(!s||l)){u(!0);try{const d=fr(s);await e(d,"new_chat",{...Rs(s)}),c(b=>({...b,[s.tabKey]:Date.now()})),i(b=>({...b,[s.tabKey]:[]}))}catch(d){console.error("New chat failed",d)}finally{u(!1)}}},[s,l,e,c,i]),A=o.useCallback(async()=>{var d,b;if(!(!s||p)){m(!0);try{const y=fr(s),h=async()=>e(y,"list_chats",{forceExpand:!0,...Rs(s)});let N=await h(),_=(N==null?void 0:N.chats)||((d=N==null?void 0:N.result)==null?void 0:d.chats);Wn(_,s)&&(await new Promise(k=>setTimeout(k,450)),N=await h(),_=(N==null?void 0:N.chats)||((b=N==null?void 0:N.result)==null?void 0:b.chats)),N!=null&&N.success&&Array.isArray(_)&&(n(s.routeId,_),Wn(_,s)&&!Wn(r,s)&&Xs(a,"⚠️ History dialog did not fully open — try once more"))}catch(y){console.error("Refresh history failed",y)}finally{m(!1)}}},[s,r,p,e,n,a]);return{isCreatingChat:l,isRefreshingHistory:p,handleLaunchIde:f,handleSwitchSession:g,handleNewChat:w,handleRefreshHistory:A}}function If(e,s){if(e.size!==s.size)return!1;for(const[r,n]of e)if(s.get(r)!==n)return!1;return!0}function Af(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function Xo(e,s){const r=Object.keys(e),n=Object.keys(s);return r.length!==n.length?!1:r.every(a=>s[Number(a)]===e[Number(a)])}function $r(e,s){const r=new Set(s),n=s.length>0?[0]:[];for(const[c,l]of e)!r.has(c)||l<=0||n.includes(l)||n.push(l);n.sort((c,l)=>c-l);const a={};n.forEach((c,l)=>{a[c]=l}),n.length===0&&(a[0]=0);const i=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const u=a[l];typeof u=="number"&&u>0&&i.set(c,u)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function Qo(e,s){const r={};for(const[n,a]of Object.entries(e)){const i=s[Number(n)];typeof i=="number"&&(r[i]=a)}return r}function Mf(e,s,r){if(s.length===0)return 0;if(typeof r[e]=="number")return r[e];const n=[...s].reverse().find(a=>a<e)??s[0];return r[n]??0}function Tf(e,s,r){if(s.length<=1)return[];const n=s.map(c=>e[c]).filter(c=>Number.isFinite(c)),a=n.length===s.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 Jo(e,s){const r={};for(const[n,a]of Object.entries(e)){const i=Number(n);r[i>=s?i+1:i]=a}return r}function Zo(e){return Array(e).fill(100/e)}function Lf({groupAssignments:e,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:a,groupSizes:i,setGroupSizes:c,isMobile:l,visibleConversations:u,visibleTabKeys:p}){const m=o.useRef(null),f=o.useMemo(()=>$r(e,p),[e,p]),g=f.assignments,w=o.useMemo(()=>l?1:f.groupCount,[f.groupCount,l]),A=w>1,d=o.useCallback((k,I)=>{s(j=>{const v=new Map($r(j,p).assignments);return I===0?v.delete(k):v.set(k,I),v}),n(j=>({...j,[I]:k})),r(I)},[s,p,n,r]),b=o.useCallback(k=>{s(I=>{const j=$r(I,p).assignments,v=new Map;for(const[x,E]of j)E!==k&&(E>k?v.set(x,E-1):v.set(x,E));return v}),c(I=>{if(I.length<=1)return[];const j=[...I];j.splice(k,1);const v=j.reduce((x,E)=>x+E,0);return v>0?j.map(x=>x/v*100):[]}),r(0)},[s,p,c,r]),y=o.useCallback((k,I)=>{I.preventDefault();const j=m.current;if(!j)return;const v=I.clientX,x=j.offsetWidth,E=i.length===w?[...i]:Zo(w),T=M=>{const U=(M.clientX-v)/x*100,C=[...E];C[k]=Math.max(15,E[k]+U),C[k+1]=Math.max(15,E[k+1]-U),c(C)},L=()=>{document.removeEventListener("mousemove",T),document.removeEventListener("mouseup",L),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",T),document.addEventListener("mouseup",L)},[i,w,c]),h=o.useCallback((k,I,j)=>{if(w>=4)return;const v=j==="left"?I:I+1;s(x=>{const E=$r(x,p).assignments,T=new Map;for(const L of u){const M=E.get(L.tabKey)??0,W=M>=v?M+1:M;W>0&&T.set(L.tabKey,W)}return v>0&&T.set(k,v),T}),c(x=>{const E=x.length===w?[...x]:Zo(w),T=E[I]??100/w,L=Math.max(15,T/2),M=Math.max(15,T/2),W=[...E];W[I]=L,W.splice(v,0,M);const U=W.reduce((C,R)=>C+R,0);return W.map(C=>C/U*100)}),n(x=>{const E=Jo(x,v);return E[v]=k,E}),a(x=>{const E=Jo(x,v);return E[v]=[k],E}),r(v)},[w,s,p,u,c,n,a,r]);o.useEffect(()=>{If(e,g)||s(g)},[e,g,s]),o.useEffect(()=>{const{mapping:k,usedGroups:I}=f;n(j=>{const v=Qo(j,k);return Xo(j,v)?j:v}),a(j=>{const v=Qo(j,k);return Xo(j,v)?j:v}),r(j=>{const v=l?0:Mf(j,I,k);return j===v?j:v}),c(j=>{const v=l?[]:Tf(j,I,f.groupCount);return Af(j,v)?j:v})},[f,l,n,a,r,c]);const N=o.useMemo(()=>{const k=Array.from({length:w},()=>[]);for(const I of u){const j=g.get(I.tabKey)??0,v=Math.min(j,w-1);k[v].push(I)}return k},[u,g,w]),_=o.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:m,normalizedGroupAssignments:g,numGroups:w,isSplitMode:A,groupedConvs:N,moveTabToGroup:d,closeGroup:b,handleResizeStart:y,splitTabRelative:h,clearAllSplits:_}}function _f({ides:e,sendDaemonCommand:s}){const r="0.8.84",n=o.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:Ec(m,r)).sort((m,f)=>Number(or(f,r))-Number(or(m,r))),[r,e]),a=o.useMemo(()=>n.some(m=>or(m,r)),[r,n]),[i,c]=o.useState(!1),[l,u]=o.useState({}),p=o.useCallback(async m=>{var f,g;u(w=>({...w,[m]:"upgrading"}));try{const w=await s(m,"daemon_upgrade",{});(f=w==null?void 0:w.result)!=null&&f.upgraded||(g=w==null?void 0:w.result)!=null&&g.success?u(A=>({...A,[m]:"done"})):u(A=>({...A,[m]:"error"}))}catch{u(w=>({...w,[m]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:p}}const ha="adhdev_dashboard_notifications_v2",xa="adhdev_dashboard_notifications_v1",wr=80;function Xr(e,s=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:s}function Za(e){return{...e,createdAt:Xr(e.createdAt),updatedAt:Xr(e.updatedAt,e.createdAt),lastEventAt:Xr(e.lastEventAt,e.updatedAt||e.createdAt)}}function Rf(e){const s=Aa(e);return s==="unknown:"?e.id:s}function ei(e){return[e.type,Ui(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Pf(e,s,r,n){var c;const a=Date.now(),i=[];for(const l of e){const u=l.sessionId?s.get(l.sessionId):void 0;if(u!=null&&u.surfaceHidden)continue;const p=ei({type:"task_complete",sessionId:l.sessionId,providerSessionId:l.providerSessionId,tabKey:l.tabKey,lastMessageHash:l.lastMessageHash,lastMessageAt:l.lastMessageAt,lastUpdated:(u==null?void 0:u.lastUpdated)||l.lastUpdated}),m=!!((c=n==null?void 0:n.get(p))!=null&&c.forceUnread),f=fn(l,s,{notificationStateBySessionId:r}),g=f.inboxBucket==="needs_attention"?"needs_attention":f.inboxBucket==="task_complete"&&f.unread||(u==null?void 0:u.inboxBucket)==="task_complete"&&m?"task_complete":null;if(!g)continue;const w=Xr(l.lastMessageAt||(u==null?void 0:u.lastUpdated)||l.lastUpdated,a),A=g==="task_complete"?p:ei({type:g,sessionId:l.sessionId,providerSessionId:l.providerSessionId,tabKey:l.tabKey,lastMessageHash:l.lastMessageHash,lastMessageAt:l.lastMessageAt,lastUpdated:(u==null?void 0:u.lastUpdated)||l.lastUpdated});i.push(Za({id:A,dedupKey:A,type:g,routeId:l.routeId,machineId:l.daemonId||l.routeId,sessionId:l.sessionId,providerSessionId:l.providerSessionId,tabKey:l.tabKey,title:nc(l),preview:em(l),createdAt:w,updatedAt:w,lastEventAt:w}))}return i.sort((l,u)=>u.updatedAt-l.updatedAt)}function Df(e,s=wr){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=Rf(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,s))}function Ef(e){return e.filter(s=>typeof s.readAt=="number"||typeof s.deletedAt=="number").map(s=>({id:s.id,...typeof s.readAt=="number"?{readAt:s.readAt}:{},...typeof s.deletedAt=="number"?{deletedAt:s.deletedAt}:{}}))}function $f(e){return new Map(e.map(s=>[s.id,s]))}function Yc(e,s,r=wr){const n=new Map;for(const i of s)n.set(i.id,i);const a=e.map(i=>{const c=Za(i),l=n.get(c.id);return{...c,...typeof(l==null?void 0:l.readAt)=="number"?{readAt:l.readAt}:{},...typeof(l==null?void 0:l.deletedAt)=="number"?{deletedAt:l.deletedAt}:{}}});return Df(a,r)}function Kf(e,s,r=wr){const n=new Set(Yc(s,[],r).map(a=>a.id));return e.filter(a=>n.has(a.id)).slice(0,Math.max(0,r))}function Bf(e,s,r=Date.now()){const n=e.filter(a=>a.id!==s);return n.push({id:s,readAt:r}),n}function Wf(e,s){const r=e.filter(n=>n.id!==s);return r.push({id:s,forceUnread:!0}),r}function Of(e,s,r,n=Date.now()){const a=e.filter(i=>{const c=s.find(l=>l.id===i.id);return!c||!ur(c,r)});for(const i of s)ur(i,r)&&a.push({id:i.id,readAt:n});return a}function Hf(e,s){const r=e.filter(n=>n.id!==s);return r.push({id:s,deletedAt:Date.now()}),r}function Uf(e){return e.filter(s=>!s.readAt&&!s.deletedAt).length}function Ff(e){const s=new Map;for(const r of e){if(r.deletedAt)continue;const n=ss(r);if(n.length===0)continue;const a=r.readAt?0:1;for(const i of n){const c=s.get(i);if(!c){s.set(i,{unreadCount:a,latestNotificationAt:r.updatedAt,latestRecordId:r.id});continue}s.set(i,{unreadCount:c.unreadCount+a,latestNotificationAt:Math.max(c.latestNotificationAt,r.updatedAt),latestRecordId:c.latestNotificationAt>=r.updatedAt?c.latestRecordId:r.id})}}return s}function zf(){if(typeof window>"u")return[];const e=s=>{if(!s||typeof s!="object")return null;const r=s;if(typeof r.id!="string"||r.id.length===0)return null;const n=typeof r.readAt=="number"&&Number.isFinite(r.readAt)?r.readAt:void 0,a=typeof r.deletedAt=="number"&&Number.isFinite(r.deletedAt)?r.deletedAt:void 0,i=r.forceUnread===!0;return typeof n!="number"&&typeof a!="number"&&!i?null:{id:r.id,...typeof n=="number"?{readAt:n}:{},...typeof a=="number"?{deletedAt:a}:{},...i?{forceUnread:!0}:{}}};try{const s=window.localStorage.getItem(ha),r=s?JSON.parse(s):[];if(Array.isArray(r))return r.map(e).filter(n=>!!n)}catch{}try{const s=window.localStorage.getItem(xa),r=s?JSON.parse(s):[];return Array.isArray(r)?Ef(r.map(n=>Za(n)).filter(n=>!n.deletedAt)):[]}catch{return[]}}function Vf(e){if(!(typeof window>"u"))try{const s=e.filter(r=>typeof r.readAt=="number"||typeof r.deletedAt=="number"||r.forceUnread===!0).slice(0,wr);if(s.length===0){window.localStorage.removeItem(ha),window.localStorage.removeItem(xa);return}window.localStorage.setItem(ha,JSON.stringify(s)),window.localStorage.removeItem(xa)}catch{}}function Gf(e,s){return e===s?!0:e.length!==s.length?!1:e.every((r,n)=>{const a=s[n];return a?r.id===a.id&&r.readAt===a.readAt&&r.deletedAt===a.deletedAt&&r.forceUnread===a.forceUnread:!1})}function qf(e){const{conversations:s,liveSessionInboxState:r,maxItems:n=wr}=e,[a,i]=o.useState(()=>zf()),c=o.useMemo(()=>$f(a),[a]),l=o.useMemo(()=>Pf(s,r,void 0,c),[s,r,c]),u=o.useMemo(()=>Yc(l,a,n),[l,a,n]),p=o.useMemo(()=>Ff(u),[u]);o.useEffect(()=>{i(d=>{const b=Kf(d,l,n);return Gf(d,b)?d:b})},[l,n]),o.useEffect(()=>{Vf(a)},[a]);const m=o.useMemo(()=>Uf(u),[u]),f=o.useCallback((d,b)=>{i(y=>Bf(y,d,b))},[]),g=o.useCallback(d=>{i(b=>Wf(b,d))},[]),w=o.useCallback((d,b)=>{i(y=>Of(y,u,d,b))},[u]),A=o.useCallback(d=>{i(b=>Hf(b,d))},[]);return{notifications:u,unreadCount:m,notificationStateBySessionId:p,markRead:f,markUnread:g,markTargetRead:w,deleteNotification:A}}function Xc(){return"select_session"}function Yf(){return"open_panel"}function Xf({hasMessage:e,blockedMessage:s}){return e?!!s:!0}function Qf(e,s,r=2e3){return e?e.tabKey===s.tabKey&&e.message===s.message&&s.timestamp-e.timestamp<r:!1}function ti(e,s){return e?e.tabKey===s.tabKey&&e.message===s.message&&e.timestamp===s.timestamp?null:e:null}function si(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function eo(e){return e instanceof Error?e.message:String(e||"")}function ri(e){const s=eo(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function ni(e,s){const r=eo(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function xn({sendDaemonCommand:e,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:a}){const[i,c]=o.useState(!1),[l,u]=o.useState(!1),[p,m]=o.useState(null),f=o.useRef(!1),g=o.useRef(null);o.useEffect(()=>{m(null)},[s==null?void 0:s.tabKey]);const w=o.useCallback(async y=>{if(!s)return!1;const h=y.trim(),N=Ea(s);if(Xf({hasMessage:!!h,blockedMessage:N,sendInFlight:f.current}))return N&&m(N),!1;const _=Date.now(),k={tabKey:s.tabKey,message:h,timestamp:_};if(Qf(g.current,k))return m(null),!0;f.current=!0,u(!0),m(null),g.current=k;const I=`${_}-${Math.random().toString(36).slice(2,8)}`,j={role:"user",content:h,timestamp:_,_localId:I},v=!0;r(x=>({...x,[k.tabKey]:[...x[k.tabKey]||[],j]}));try{const x=fr(s);if(!x)return g.current=ti(g.current,k),v&&r(L=>({...L,[k.tabKey]:(L[k.tabKey]||[]).filter(M=>M._localId!==I)})),m("Unable to send message right now."),!1;const E=await e(x,"send_chat",{message:h,...Rs(s)}),T=si(E);if(v&&(T!=null&&T.deduplicated))return r(L=>({...L,[k.tabKey]:(L[k.tabKey]||[]).filter(M=>M._localId!==I)})),m(null),!0;if((T==null?void 0:T.sent)===!1)throw new Error((T==null?void 0:T.error)||"Send failed");if((T==null?void 0:T.success)===!1)throw new Error((T==null?void 0:T.error)||"Send failed");return setTimeout(()=>{const L=Date.now()-6e4;r(M=>{const W=M[k.tabKey];if(!W)return M;const U=W.filter(C=>C.timestamp>L);return U.length===W.length?M:{...M,[k.tabKey]:U}})},6e4),m(null),!0}catch(x){const E=eo(x);return E.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",E):console.warn("Send blocked/failed",x),g.current=ti(g.current,k),r(T=>({...T,[k.tabKey]:(T[k.tabKey]||[]).filter(L=>L._localId!==I)})),m(vm(x)),!1}finally{f.current=!1,u(!1)}},[s,e,n,r]),A=o.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await e(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(y){console.error("Relaunch failed",y)}},[s,e]),d=o.useCallback(async y=>{if(s)try{const N=(s.modalButtons||[]).indexOf(y),_=y.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(_),I=fr(s);if(!I)return;const j=await e(I,"resolve_action",{button:y,action:k?"approve":"reject",...N>=0&&{buttonIndex:N},...Rs(s)}),v=si(j);v.success||n(x=>[...x,{routeId:s.tabKey,text:ni(y,v==null?void 0:v.error),timestamp:Date.now()}])}catch(h){ri(h)||console.error("[ModalButton] Error:",h),n(N=>[...N,{routeId:s.tabKey,text:ri(h)?ni(y,h):`❌ **${y}** error`,timestamp:Date.now()}])}},[s,e,n]),b=o.useCallback(async()=>{if(!(!s||i)){c(!0);try{await e(s.routeId,Yf(),{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(y){console.error("Focus agent failed",y)}finally{c(!1)}}},[s,i,e]);return{isSendingChat:l,sendFeedbackMessage:p,isFocusingAgent:i,handleSendChat:w,handleRelaunch:A,handleModalButton:d,handleFocusAgent:b}}const to=o.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m=null,handleFocusAgent:f,isFocusingAgent:g,actionLogs:w,userName:A,scrollToBottomRequestNonce:d,isInputActive:b=!0}){const y=Oc(s),h=y.status||y.modalMessage||y.modalButtons?{...s,...y.status?{status:y.status}:{},...y.modalMessage!==void 0?{modalMessage:y.modalMessage}:{},...y.modalButtons!==void 0?{modalButtons:y.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(Vi,{activeConv:h,onModalButton:c}),h.transport!=="pty"&&h.transport!=="acp"&&h.cdpConnected===!1?t.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:t.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:[t.jsx("span",{className:"text-sm",children:t.jsx(vs,{size:14})}),t.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),t.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,h.transport==="pty"?t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{display:n?"flex":"none",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(Vm,{activeConv:h,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m,isVisible:n})}),!n&&t.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(da,{activeConv:h,ideEntry:a,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:w,userName:A,scrollToBottomRequestNonce:d,isInputActive:b})})]}):t.jsx(da,{activeConv:h,ideEntry:a,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:w,userName:A,scrollToBottomRequestNonce:d,isInputActive:b})]})},(e,s)=>e.activeConv===s.activeConv&&e.isCliTerminal===s.isCliTerminal&&e.ideEntry===s.ideEntry&&e.terminalRef===s.terminalRef&&e.handleModalButton===s.handleModalButton&&e.handleRelaunch===s.handleRelaunch&&e.handleSendChat===s.handleSendChat&&e.isSendingChat===s.isSendingChat&&e.sendFeedbackMessage===s.sendFeedbackMessage&&e.handleFocusAgent===s.handleFocusAgent&&e.isFocusingAgent===s.isFocusingAgent&&e.actionLogs===s.actionLogs&&e.userName===s.userName&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&e.isInputActive===s.isInputActive);function Jf({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:u,onBack:p,onOpenNativeConversation:m,onOpenMachine:f,onOpenHistory:g,onOpenRemote:w,onHideConversation:A,onStopCli:d,cliViewMode:b,onSetCliViewMode:y,handleSendChat:h,handleFocusAgent:N,handleModalButton:_,handleRelaunch:k}){const I=o.useRef(null),j=tt(e)&&!s,v=j&&b==="terminal",x=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:`flex items-center justify-between gap-3 ${x} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:t.jsx(ja,{size:18})}),t.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:lt(e)}),t.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:t.jsx(dc,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>m(e),onOpenMachine:()=>f(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[j&&b&&t.jsx(Ka,{mode:b,onChange:y,compact:!0}),j&&d&&t.jsx("button",{onClick:()=>{d(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:t.jsx(At,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:t.jsx(Sa,{size:14})}),!s&&!j&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>w(e),type:"button",children:t.jsx(Rt,{size:14})}),A&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>A(e),type:"button",title:"Close chat",children:t.jsx(At,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(to,{activeConv:e,clearToken:0,isCliTerminal:v,ideEntry:n,terminalRef:I,handleModalButton:_,handleRelaunch:k,handleSendChat:h,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:N,isFocusingAgent:u,actionLogs:a,userName:i})})]})}const On={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 Zf(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Qc(){const[e,s]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{s(Zf())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(On[c].cmd).catch(()=>{}),i(!0),setTimeout(()=>i(!1),2e3)},[c]);return t.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:[t.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[t.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:()=>s("unix"),children:"🍎🐧 macOS / Linux"}),t.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:()=>s("windows"),children:"🪟 Windows"})]}),e==="windows"&&t.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[t.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"}),t.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"})]}),t.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:l,title:"Click to copy",children:[t.jsx("span",{className:"text-text-muted select-none",children:On[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:On[c].cmd}),t.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:a?"✓":"📋"})]}),t.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",t.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function Jc({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:Rt},{key:"chats",label:"Chats",icon:Qt}];return t.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:t.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 t.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:()=>s(n),type:"button","aria-pressed":c,children:[t.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:t.jsx(i,{size:15})}),t.jsx("span",{children:a})]},n)})})})}function Kr({title:e,className:s=""}){return t.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${s}`,children:t.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function Cs({children:e,className:s=""}){return t.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)] ${s}`,children:e})}function Zs({icon:e,title:s,subtitle:r,children:n}){return t.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:[t.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}),t.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:s}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function Br({item:e,type:s,getAvatarText:r,onOpenConversation:n}){const a=s==="needs_attention"||s==="task_complete",i=s==="working",c=s==="earlier",l=s==="task_complete",{isReconnecting:u,isConnecting:p}=zs(e.conversation),m=lt(e.conversation),f=ks(e.conversation),g=wc(e.conversation,{requiresAction:s==="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",A=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",d=c?"text-text-secondary":"text-text-primary",b=c?"text-text-muted":"text-text-secondary",y=c?"text-text-secondary opacity-80":"text-text-muted",h=c?"text-text-muted opacity-80":"text-text-muted",N="text-[color:var(--status-warning)]";return t.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?t.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,t.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${A}`,style:a?{color:"var(--accent-on-primary)"}:void 0,children:r(m)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${d}`,children:m}),!i&&t.jsx("span",{className:`text-[11px] font-medium shrink-0 ${h}`,children:zi(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${b}`,children:[f,u?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${N} animate-pulse`,children:"Reconnecting…"})]}):p?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):g==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:N,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${y}`,children:e.preview})]}),a&&!l&&t.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),l&&t.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&&t.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 ai({size:e=32,label:s}){return t.jsxs("div",{className:"flex flex-col items-center gap-2.5",children:[t.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}}),s&&t.jsx("div",{className:"text-xs font-semibold text-accent-primary-light tracking-tight",children:s})]})}function eh({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:u,onShowConversation:p,onShowAllHidden:m,onOpenNewSession:f,onOpenMachine:g,onOpenSettings:w,onSectionChange:A,wsStatus:d="connected",isStandalone:b=!1}){const y=d==="disconnected"||d==="reconnecting"||d==="offline"||d==="auth_failed",h=c.length>0,N=s.length>0||r.length>0||n.length>0||a.length>0,_=e==="machines"?"Machines":"Chats",k=b?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",I=b?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]";return t.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[t.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${k}`,children:t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:_}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(s.length>0||r.length>0)&&t.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:[t.jsx(mn,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.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:t.jsx(dn,{size:18})})]})]})}),t.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${I}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:y?t.jsx(Zs,{icon:t.jsx(ai,{label:"Reconnecting…"}),title:"Connecting to server",subtitle:d==="offline"?"Your device appears to be offline. Waiting for network…":d==="auth_failed"?"Session expired. Please log in again.":"Establishing connection to the server. This usually takes a moment."}):c.length===0?t.jsx(Zs,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:b?"Waiting for your daemon":"Connect your machines",subtitle:b?"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:!b&&t.jsx("div",{className:"w-full max-w-[360px] mt-4",children:t.jsx(Qc,{})})}):t.jsx(Cs,{children:c.map((j,v)=>t.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:()=>g(j.id),type:"button",children:[t.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(j.label)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:j.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:j.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[j.unread," new"]}):j.total>0?`${j.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:j.subtitle}),j.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[j.total," chat",j.total!==1?"s":"",j.unread>0?` · ${j.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},j.id))})}),e==="chats"&&s.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Kr,{title:"Needs attention",className:"mb-0"}),t.jsx(Cs,{children:s.map((j,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Br,{item:j,type:"needs_attention",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&r.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Kr,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(Cs,{children:r.map((j,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Br,{item:j,type:"task_complete",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&n.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Kr,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(Cs,{children:n.map((j,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Br,{item:j,type:"working",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&t.jsx(Kr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?t.jsx(Cs,{children:a.map((j,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Br,{item:j,type:"earlier",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))}):N?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):y?t.jsx(Zs,{icon:t.jsx(ai,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):h?t.jsx(Zs,{icon:t.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:t.jsx(Qt,{size:20})}),title:"No conversations yet",subtitle:"Your machines are available. Open a machine, wait for P2P to connect, then launch your first IDE, CLI, or ACP session."}):t.jsx(Zs,{icon:t.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&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.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:[t.jsx("span",{children:"Hidden"}),t.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:m,children:"Restore all"})]}),t.jsx(Cs,{className:"bg-bg-secondary/25",children:i.map((j,v)=>t.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:()=>p(j),type:"button",children:[t.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(lt(j))}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:lt(j)}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:ks(j)}),t.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},j.tabKey))})]})]}),e==="chats"&&f&&t.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:f,"aria-label":"Start new session",children:t.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),t.jsx(Jc,{section:e,onSectionChange:A})]})}function th(e){if(!e)return"";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(e))}catch{return new Date(e).toLocaleString()}}function Zc(e){const s=[e.workspace||"Workspace unknown"],r=ws(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=th(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function bn(...e){const s=new Set,r=[],n=a=>{const i=typeof a=="string"?a.trim():"";if(!i)return;const c=i.toLowerCase();s.has(c)||(s.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 sh(e){const s=e.trim();if(!s)return null;if(s.startsWith("~"))return s;if(/^[A-Za-z]:$/.test(s))return`${s[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(s))return`${s[0].toUpperCase()}:${s.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(s))return`${s[0].toUpperCase()}:\\${s.slice(2).replace(/[\\/]+/g,"\\")}`;const r=s.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),a=(r[2]||"").replace(/[\\/]+/g,"\\");return a?`${n}:\\${a}`:`${n}:\\`}return null}function gn(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=sh(r);if(n)return n}return"C:\\"}for(const r of s){const n=typeof r=="string"?r.trim():"";if(n)return n}return"~"}function rh(e){const s=e.replace(/[\\/]+$/,"");if(!s||s==="/"||/^[A-Za-z]:$/.test(s))return null;const r=s.includes("\\")?"\\":"/",n=s.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 nh(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function yn(e,s,r){const n=await e(s,"file_list_browse",{path:r}),a=nh(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=(p,m)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${m}`:p==="/"||p==="\\"?`${c}${m}`:`${p.replace(/[\\/]+$/,"")}${c}${m}`,u=Array.isArray(a==null?void 0:a.files)?a.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:typeof(p==null?void 0:p.path)=="string"&&p.path.trim()?p.path:l(i,p.name)})).sort((p,m)=>p.name.localeCompare(m.name)):[];return{path:i,directories:u}}function vn({title:e,description:s,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:u,onConfirm:p}){const[m,f]=o.useState(r);o.useEffect(()=>{f(r)},[r]);const g=rh(r),w=m.trim();return t.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:t.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:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.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:t.jsx(At,{size:16})})]}),t.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[t.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:()=>{!g||a||u(g)},disabled:!g||a,children:[t.jsx(ja,{size:15}),"Parent"]}),t.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"text",value:m,onChange:A=>f(A.target.value),onKeyDown:A=>{A.key!=="Enter"||!w||a||(A.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"}),t.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"})]})]})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):i?t.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):n.length===0?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):t.jsx("div",{className:"p-3",children:n.map(A=>t.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(A.path),children:[t.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:t.jsx(Es,{size:17})}),t.jsxs("span",{className:"min-w-0 flex-1",children:[t.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:A.name}),t.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:A.path})]})]},A.path))})}),t.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:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(w||r),disabled:!w&&!r||a,children:c})]})]})})}function so({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:u=!1,showArgsInput:p,argsValue:m,onArgsChange:f,showModelInput:g,modelValue:w,onModelChange:A,historyProviderNode:d,onConfirm:b,onCancel:y}){const h=n==null?void 0:n.find(N=>N.key===a);return t.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:t.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:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:y,"aria-label":"Close launch confirmation",children:t.jsx(At,{size:16})})]}),t.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&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),t.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=>t.jsx("option",{value:N.key,children:N.label},N.key))}),(h==null?void 0:h.description)&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:h.description})]}),d,r.map(N=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:N.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:N.value})]},`${N.label}:${N.value}`)),g&&A&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),t.jsx("input",{type:"text",value:w||"",onChange:N=>A(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})]}),p&&f&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),t.jsx("input",{type:"text",value:m||"",onChange:N=>f(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})]})]}),t.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:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:y,disabled:u,children:"Cancel"}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:b,disabled:u,children:[t.jsx(Na,{size:14}),u?l:c]})]})]})})}function oi(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function gs(e){const{machine:s,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 s.workspaces||[])i.push({key:`saved:${u.id}`,label:`${u.id===s.defaultWorkspaceId?"⭐ ":""}${oi(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const c=(r==null?void 0:r.trim())||"",l=c?(s.workspaces||[]).find(u=>u.path===c):null;if(c&&!l&&i.push({key:`custom:${c}`,label:oi(c),description:c,workspaceId:null,workspacePath:c}),n){const u=`saved:${n}`;if(i.some(p=>p.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 ah(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function oh(e){return[ah(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function ih(e){return e.lastLaunchedAt?pn(e.lastLaunchedAt):""}function el(e){return{metaText:oh(e),updatedLabel:ih(e)}}function Hn(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function ch({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var ze,xt,bt,ct;const c=yr(),[l,u]=o.useState(!1),p=(((ze=e.detectedIdes)==null?void 0:ze.length)||0)>0,m=o.useMemo(()=>(e.workspaces||[]).map(Te=>({id:Te.id,path:Te.path,label:Te.label})),[e]),f=e.defaultWorkspaceId||null,[g,w]=o.useState(f||((xt=m[0])==null?void 0:xt.id)||""),[A,d]=o.useState(""),[b,y]=o.useState(""),[h,N]=o.useState([]),[_,k]=o.useState(!1),[I,j]=o.useState(""),[v,x]=o.useState(!1),[E,T]=o.useState(Hn(p,s.length,r.length)),L=o.useRef(null),[M,W]=o.useState(null),U=o.useRef("__home__"),[C,R]=o.useState("__home__"),[B,S]=o.useState(""),[D,Y]=o.useState(""),[q,H]=o.useState(""),[re,ie]=o.useState([]),[Se,X]=o.useState(()=>jt().textQuery),[fe,we]=o.useState(()=>jt().workspaceQuery),[ce,he]=o.useState(()=>jt().modelQuery),[de,z]=o.useState(()=>jt().resumableOnly),[ge,ae]=o.useState(()=>jt().sortMode),[oe,ee]=o.useState(!1),[ue,se]=o.useState(!1),ke=o.useRef(null),ye=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const K=g==="__custom__"?A.trim():((bt=m.find(Te=>Te.id===g))==null?void 0:bt.path)||"",V=g==="__custom__"&&!!K&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),ve=g!=="__custom__"&&((ct=m.find(Te=>Te.id===g))==null?void 0:ct.path)||"",xe=o.useMemo(()=>(e.recentLaunches||[]).map(Te=>Te.workspace),[e]),Q=o.useCallback(async Te=>{k(!0),j("");try{const Xe=await a(Te);y(Xe.path),d(Xe.path),N(Xe.directories)}catch(Xe){j(Xe instanceof Error?Xe.message:"Could not load folder")}finally{k(!1)}},[a]),Me=o.useCallback(()=>{var Xe;w("__custom__"),x(!0);const Te=gn(e.platform,bn(A.trim(),ve,xe,e.defaultWorkspacePath,(Xe=m.find(Ue=>Ue.id===f))==null?void 0:Xe.path,m.map(Ue=>Ue.path)));Q(Te)},[A,f,Q,xe,ve,e.platform,m]),We=o.useCallback(Te=>{if(Te!=null&&Te.workspaceId){w(Te.workspaceId),d("");return}if(Te!=null&&Te.workspacePath){w("__custom__"),d(Te.workspacePath);return}w(""),d("")},[]),Pe=o.useCallback(Te=>{if(w(Te),Te==="__custom__"){Me();return}d("")},[Me]),Ke=o.useCallback(Te=>{w("__custom__"),d(Te)},[]),Je=o.useCallback((Te,Xe)=>{L.current=Xe,U.current=Te.selectedWorkspaceKey||"__home__",R(Te.selectedWorkspaceKey||"__home__"),S(Te.initialArgs||""),Y(Te.initialModel||""),H(""),ie([]);const Ue=Te.providerType?`${e.id}:${Te.providerType}`:null;if(Xm(ye.current,Ue)){const Fe=jt();X(Fe.textQuery),we(Fe.workspaceQuery),he(Fe.modelQuery),z(Fe.resumableOnly),ae(Fe.sortMode)}ye.current=Ue,W(Te),Te.providerType&&i&&(ee(!0),i(Te.providerType).then(Fe=>ie(Fe||[])).catch(Fe=>console.warn("Failed to load saved sessions",Fe)).finally(()=>ee(!1)))},[i,e.id]),Ge=o.useMemo(()=>Sc(re,{textQuery:Se,workspaceQuery:fe,modelQuery:ce,resumableOnly:de,sortMode:ge}),[ce,de,re,ge,Se,fe]);o.useEffect(()=>{q&&(Ge.some(Te=>Te.providerSessionId===q)||H(""))},[Ge,q]);const ut=o.useCallback(()=>{L.current&&(se(!0),L.current().finally(()=>{L.current=null,se(!1),W(null)}))},[]),it=o.useCallback(()=>{L.current=null,W(null)},[]),ht=o.useCallback(Te=>{U.current=Te,R(Te)},[]);return o.useEffect(()=>{var Te;ke.current!==e.id&&(ke.current=e.id,w(f||((Te=m[0])==null?void 0:Te.id)||"__custom__"),d(""),y(""),N([]),j(""),x(!1),X(jt().textQuery),we(jt().workspaceQuery),he(jt().modelQuery),z(jt().resumableOnly),ae(jt().sortMode),ye.current=null,T(Hn(p,s.length,r.length)))},[r.length,s.length,f,p,e.id,m]),o.useEffect(()=>{var Te;g!=="__custom__"&&(g&&m.some(Xe=>Xe.id===g)||w(f||((Te=m[0])==null?void 0:Te.id)||"__custom__"))},[f,g,m]),o.useEffect(()=>{E==="ide"&&p||E==="cli"&&s.length>0||E==="acp"&&r.length>0||T(Hn(p,s.length,r.length))},[E,r.length,s.length,p]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:p,workspaceRows:m,defaultWorkspaceId:f,workspaceChoice:g,customWorkspacePath:A,browseCurrentPath:b,browseDirectories:h,browseBusy:_,browseError:I,browseDialogOpen:v,activeLauncherKind:E,launchConfirm:M,launchConfirmWorkspaceKeyRef:U,launchConfirmWorkspaceKey:C,launchConfirmArgs:B,launchConfirmModel:D,launchConfirmResumeId:q,launchConfirmSavedSessions:re,launchConfirmTextFilter:Se,launchConfirmWorkspaceFilter:fe,launchConfirmModelFilter:ce,launchConfirmResumableOnly:de,launchConfirmSortMode:ge,filteredLaunchConfirmSavedSessions:Ge,launchConfirmSessionsLoading:oe,launchConfirmBusy:ue,resolvedWorkspacePath:K,canCreateMissingWorkspace:V,openBrowseDialog:Me,loadBrowsePath:Q,handleWorkspaceChoiceChange:Pe,chooseCustomWorkspacePath:Ke,setCustomWorkspacePath:d,setBrowseDialogOpen:x,setActiveLauncherKind:T,openLaunchConfirm:Je,handleConfirmLaunch:ut,closeLaunchConfirm:it,setWorkspaceSelectionFromOption:We,setLaunchConfirmWorkspaceKeyAndSync:ht,setLaunchConfirmArgs:S,setLaunchConfirmModel:Y,setLaunchConfirmResumeId:H,setLaunchConfirmTextFilter:X,setLaunchConfirmWorkspaceFilter:we,setLaunchConfirmModelFilter:he,setLaunchConfirmResumableOnly:z,setLaunchConfirmSortMode:ae}}function lh({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:u,section:p,showBottomNav:m,onBack:f,onSectionChange:g,onOpenConversation:w,onOpenRecent:A,onOpenMachineDetails:d,onMachineUpgrade:b,onLaunchDetectedIde:y,onAddWorkspace:h,onBrowseDirectory:N,onLaunchWorkspaceProvider:_,onListSavedSessions:k}){const I=C=>C==="ide"?"IDE":C==="cli"?"CLI":"ACP",j=r.slice(0,4),v=s.slice(0,3),x=ch({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:N,onListSavedSessions:k}),E=o.useMemo(()=>j.map(C=>{const{metaText:R,updatedLabel:B}=el(C);return{key:`recent-launch:${C.id}`,primary:C.label,secondary:R,updatedLabel:B,onClick:()=>{const{options:S,selectedKey:D}=gs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspacePath:C.workspace});x.openLaunchConfirm({title:C.kind==="ide"?fs("restart-ide",C.label):C.providerSessionId?Oa(C.label):fs("start-fresh",C.label),description:C.kind==="ide"?hs("restart-ide"):C.providerSessionId?Ha():hs("start-fresh"),confirmLabel:C.kind==="ide"?Os("restart-ide"):C.providerSessionId?nn(!0):Os("start-fresh"),busyLabel:C.kind==="ide"?Hs("restart-ide"):C.providerSessionId?Ba(!0):Hs("start-fresh"),workspaceOptions:S,selectedWorkspaceKey:D,details:[{label:"Mode",value:I(C.kind)},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]},async()=>{const Y=S.find(q=>q.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(Y),await A({...C,workspace:(Y==null?void 0:Y.workspacePath)??null})})}}}),[x,A,j]),T=o.useMemo(()=>v.map(C=>({key:`recent-chat:${C.conversation.tabKey}`,primary:lt(C.conversation),secondary:Hm(C.conversation,{timestampLabel:C.timestamp?zi(C.timestamp):null}),unread:C.unread,onClick:()=>w(C.conversation)})),[w,v]),L=x.showAllRecent?E:E.slice(0,4),M=E.length>0,W=T.length>0,U=u?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:`flex items-center justify-between gap-3 ${U} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.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:t.jsx(ja,{size:18})}),t.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:_t(e,{fallbackId:e.id})}),t.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}`:""]})]})]})}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[W&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:T.map(C=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${C.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:C.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))})]}),M&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:L.map(C=>t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:C.onClick,children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:C.primary}),C.updatedLabel&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:C.updatedLabel})]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))}),E.length>4&&t.jsx("div",{className:"flex justify-center px-4 pt-2",children:t.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:()=>x.setShowAllRecent(C=>!C),children:x.showAllRecent?"Show fewer":`Show ${E.length-4} more`})})]}),(x.hasIdeOptions||n.length>0||a.length>0)&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:t.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:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),t.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),t.jsx("select",{value:x.workspaceChoice,onChange:C=>x.handleWorkspaceChoiceChange(C.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:x.workspaceRows.length>0?t.jsxs(t.Fragment,{children:[x.workspaceRows.map(C=>t.jsxs("option",{value:C.id,children:[C.id===x.defaultWorkspaceId?"⭐ ":"",hn(C.path,C.label)||C.path]},C.id)),t.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):t.jsx("option",{value:"__custom__",children:"Select workspace…"})}),x.workspaceChoice==="__custom__"&&t.jsxs("div",{className:"flex flex-col gap-2.5",children:[t.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start gap-3",children:[t.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:t.jsx(Es,{size:17})}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),t.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:x.resolvedWorkspacePath||x.browseCurrentPath||"No folder selected yet."})]})]})}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.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:x.openBrowseDialog,children:"Select workspace…"}),t.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:()=>{x.resolvedWorkspacePath&&h(x.resolvedWorkspacePath)},disabled:!x.resolvedWorkspacePath||x.browseBusy,children:"Save as workspace"})]})]}),x.resolvedWorkspacePath&&t.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath})]})}),t.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[x.hasIdeOptions&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${x.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:()=>x.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${x.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:()=>x.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${x.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:()=>x.setActiveLauncherKind("acp"),children:"ACP"})]}),x.activeLauncherKind&&t.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[t.jsx("div",{className:"text-xs font-bold text-text-secondary",children:x.activeLauncherKind==="ide"?"Choose an IDE":x.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),t.jsx("div",{className:"grid grid-cols-1 gap-2",children:x.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(C=>t.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:B}=gs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspaceId:x.workspaceChoice!=="__custom__"?x.workspaceChoice:null,currentWorkspacePath:x.resolvedWorkspacePath});x.openLaunchConfirm({title:`Launch ${C.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:R,selectedWorkspaceKey:B,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:C.name}]},async()=>{const S=R.find(D=>D.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(S),y(C.type,{workspacePath:(S==null?void 0:S.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:C.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath||"Use selected workspace"})]},C.type)):(x.activeLauncherKind==="cli"?n:a).map(C=>t.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=x.activeLauncherKind==="cli"?"cli":"acp",{options:B,selectedKey:S}=gs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspaceId:x.workspaceChoice!=="__custom__"?x.workspaceChoice:null,currentWorkspacePath:x.resolvedWorkspacePath});x.openLaunchConfirm({title:`Launch ${C.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${R.toUpperCase()}`,workspaceOptions:B,selectedWorkspaceKey:S,details:[{label:"Mode",value:R.toUpperCase()},{label:"Provider",value:C.displayName}],showArgsInput:!0,showModelInput:R==="acp",initialArgs:"",initialModel:"",providerType:C.type},async()=>{const D=B.find(Y=>Y.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(D),_(R,C.type,{workspaceId:(D==null?void 0:D.workspaceId)??null,workspacePath:(D==null?void 0:D.workspacePath)??null,args:x.launchConfirmArgs,model:x.launchConfirmModel,resumeSessionId:x.launchConfirmResumeId||null})})},children:[t.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[C.icon?`${C.icon} `:"",C.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath||"Use selected workspace"})]},C.type))})]}),l.message&&t.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,x.canCreateMissingWorkspace&&t.jsx("div",{className:"mt-2",children:t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[34px] px-4 rounded-lg bg-surface-primary text-text-primary font-bold text-xs",onClick:()=>h(x.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[i&&t.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:b,children:[t.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),t.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:d,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),x.browseDialogOpen&&t.jsx(vn,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:x.browseCurrentPath,directories:x.browseDirectories,busy:x.browseBusy,error:x.browseError,confirmLabel:"Use this folder",onClose:()=>x.setBrowseDialogOpen(!1),onNavigate:C=>{x.loadBrowsePath(C)},onConfirm:C=>{x.chooseCustomWorkspacePath(C),x.setBrowseDialogOpen(!1)}}),x.launchConfirm&&t.jsx(so,{title:x.launchConfirm.title,description:x.launchConfirm.description,details:x.launchConfirm.details,workspaceOptions:x.launchConfirm.workspaceOptions,selectedWorkspaceKey:x.launchConfirmWorkspaceKey,onWorkspaceChange:x.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:x.launchConfirm.providerType?nn(!!x.launchConfirmResumeId):x.launchConfirm.confirmLabel,busyLabel:x.launchConfirm.providerType?void 0:x.launchConfirm.busyLabel,busy:x.launchConfirmBusy,showArgsInput:x.launchConfirm.showArgsInput,argsValue:x.launchConfirmArgs,onArgsChange:x.setLaunchConfirmArgs,showModelInput:x.launchConfirm.showModelInput,modelValue:x.launchConfirmModel,onModelChange:x.setLaunchConfirmModel,historyProviderNode:x.launchConfirm.providerType&&(x.launchConfirmSessionsLoading||x.launchConfirmSavedSessions.length>0)&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),x.launchConfirmSessionsLoading&&t.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:Wa()}),t.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[t.jsx("input",{type:"text",value:x.launchConfirmTextFilter,onChange:C=>x.setLaunchConfirmTextFilter(C.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:x.launchConfirmWorkspaceFilter,onChange:C=>x.setLaunchConfirmWorkspaceFilter(C.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:x.launchConfirmModelFilter,onChange:C=>x.setLaunchConfirmModelFilter(C.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsxs("select",{value:x.launchConfirmSortMode,onChange:C=>x.setLaunchConfirmSortMode(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"recent",children:"Most recent"}),t.jsx("option",{value:"oldest",children:"Oldest first"}),t.jsx("option",{value:"messages",children:"Most messages"})]})]}),t.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsx("input",{type:"checkbox",checked:x.launchConfirmResumableOnly,onChange:C=>x.setLaunchConfirmResumableOnly(C.target.checked),disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),"Resume-ready only"]}),t.jsxs("select",{value:x.launchConfirmResumeId,onChange:C=>x.setLaunchConfirmResumeId(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"",children:Zm()}),x.filteredLaunchConfirmSavedSessions.map(C=>t.jsxs("option",{value:C.providerSessionId,disabled:!C.canResume,children:[C.title||C.providerSessionId," ",C.canResume?"":"(workspace missing)"]},C.providerSessionId))]}),!x.launchConfirmSessionsLoading&&x.launchConfirmSavedSessions.length>0&&x.filteredLaunchConfirmSavedSessions.length===0&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),x.launchConfirmResumeId&&(()=>{const C=x.filteredLaunchConfirmSavedSessions.find(B=>B.providerSessionId===x.launchConfirmResumeId);if(!C)return null;const R=Zc(C);return t.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:[t.jsx("div",{className:"font-semibold text-text-primary truncate",children:R.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:R.providerSessionId}),t.jsx("div",{className:"mt-1",children:R.metaLine}),R.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:R.updatedLabel}),R.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:R.preview})]})})()]}),onConfirm:x.handleConfirmLaunch,onCancel:x.closeLaunchConfirm}),m&&t.jsx(Jc,{section:p,onSectionChange:g})]})}function tl(e){var r;const s=((r=e.p2p)==null?void 0:r.state)||"";return s==="connected"?"Connected":s==="connecting"||s==="new"||s==="checking"?"Connecting":"Offline"}function dh(e,s){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:ws(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):s.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var c,l,u,p,m;const a=mr(n)?"cli":Ls(n)?"acp":"ide",i=ws(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(mr(n)?n.cliName||n.type:Ls(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Ls(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((m=(p=(u=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:u.at)==null?void 0:p.call(u,-1))==null?void 0:m.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function uh(e,s){const r=new Map;for(const n of s){const a=os(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((f,g)=>g.timestamp-f.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=aa(n),u=a.filter(f=>f.unread||f.requiresAction).length,p=tl(n),m=[n.platform||"machine",p].filter(Boolean);return{id:n.id,label:_t(n,{fallbackId:n.id}),subtitle:m.join(" · "),unread:u,total:a.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?Um(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 Wr(e,s){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}`,s)}catch{}}function mh({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:m,onRequestedMachineConsumed:f,requestedMobileSection:g,onRequestedMobileSectionConsumed:w,setSelectedTabKey:A,setScreen:d,setSelectedMachineId:b,setSection:y,setMachineBackTarget:h,resetMachineAction:N,markNotificationTargetRead:_}){const k=o.useRef(null),I=o.useCallback(j=>{if(!(j!=null&&j.sessionId))return;const v=tn(j,c),x=Math.max(Date.now(),us(j),v.lastUpdated||0);Wr("mark_read:start",{tabKey:j.tabKey,sessionId:j.sessionId,displayPrimary:lt(j),inboxBucket:v.inboxBucket,unread:v.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,activityAt:us(j),readAt:x}),_({sessionId:j.sessionId,providerSessionId:j.providerSessionId,tabKey:j.tabKey,routeId:j.routeId},x),l(os(j)||j.routeId,"mark_session_seen",{sessionId:j.sessionId,seenAt:x}).then(E=>{Wr("mark_read:result",{tabKey:j.tabKey,sessionId:j.sessionId,result:E})}).catch(E=>{Wr("mark_read:error",{tabKey:j.tabKey,sessionId:j.sessionId,error:E instanceof Error?E.message:String(E)})})},[c,l]);return o.useEffect(()=>{var v;if(!n){d("inbox"),A(((v=e[0])==null?void 0:v.tabKey)||null),k.current=null;return}if(i!=="chat"){k.current=null;return}const j=`${n.tabKey}:${n.sessionId||""}`;k.current!==j&&(k.current=j,I(n))},[e,I,i,n,d,A]),o.useEffect(()=>{if(!u)return;const j=e.find(v=>v.tabKey===u);j&&(A(j.tabKey),d("chat"),p==null||p())},[e,p,u,d,A]),o.useEffect(()=>{if(!m)return;const j=s.find(v=>v.id===m);j&&(b(j.id),N(),y("machines"),h("inbox"),d("machine"),f==null||f())},[s,f,m,N,h,d,y,b]),o.useEffect(()=>{g&&(y(g),d("inbox"),w==null||w())},[w,g,d,y]),o.useEffect(()=>{const j=r.filter(v=>v.inboxBucket==="task_complete"||v.unread);j.length!==0&&Wr("inbox_state",{screen:i,selectedTabKey:a,items:j.map(v=>{const x=tn(v.conversation,c);return{liveState:x,tabKey:v.conversation.tabKey,sessionId:v.conversation.sessionId,displayPrimary:lt(v.conversation),serverBucket:x.inboxBucket,computedBucket:v.inboxBucket,serverUnread:x.unread,computedUnread:v.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,activityAt:us(v.conversation)}})})},[r,c,i,a]),{markConversationRead:I}}function ph(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function ii(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function fh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function hh({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[u,p]=o.useState(null),m=o.useCallback(()=>{i("idle"),l(""),p(null)},[]),f=o.useCallback(async(h,N,_)=>{var k;try{i("loading"),l(`Launching ${N}…`);const I={ideType:N,enableCdp:!0};(k=_==null?void 0:_.workspacePath)!=null&&k.trim()&&(I.workspace=_.workspacePath.trim()),await e(h,"launch_ide",I),i("done"),l(`${N} launch requested`)}catch(I){i("error"),l(I instanceof Error?I.message:"Launch IDE failed"),console.error("Launch IDE failed",I)}},[e]),g=o.useCallback(async(h,N,_)=>{if(N.trim())try{i("loading"),l(_!=null&&_.createIfMissing?"Creating folder…":"Saving workspace…");const k=await e(h,"workspace_add",{path:N.trim(),createIfMissing:(_==null?void 0:_.createIfMissing)===!0});if(k!=null&&k.success){i("done"),l(_!=null&&_.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((k==null?void 0:k.error)||"Could not save workspace")}catch(k){i("error"),l(k instanceof Error?k.message:"Could not save workspace")}},[e]),w=o.useCallback(async h=>{var N,_,k,I,j,v;try{i("loading"),l("Starting daemon upgrade…");const x=await e(h,"daemon_upgrade",{});if((N=x==null?void 0:x.result)!=null&&N.alreadyLatest){i("done"),l(`Already on v${((_=x==null?void 0:x.result)==null?void 0:_.version)||"latest"}.`);return}if((k=x==null?void 0:x.result)!=null&&k.upgraded||(I=x==null?void 0:x.result)!=null&&I.success){i("done"),l(`Upgrade to v${((j=x==null?void 0:x.result)==null?void 0:j.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((v=x==null?void 0:x.result)==null?void 0:v.error)||"Upgrade failed")}catch(x){i("error"),l(x instanceof Error?x.message:"Upgrade failed")}},[e]),A=o.useCallback(async(h,N,_,k)=>{var v,x,E;const I=Date.now(),j={machineId:h,kind:N,providerType:_,workspaceId:(k==null?void 0:k.workspaceId)||null,workspacePath:(k==null?void 0:k.workspacePath)||null,resumeSessionId:(k==null?void 0:k.resumeSessionId)||null,startedAt:I};try{i("loading"),l(`Launching ${_}…`),p(j);const T={cliType:_};(v=k==null?void 0:k.workspacePath)!=null&&v.trim()?T.dir=k.workspacePath.trim():k!=null&&k.workspaceId&&(T.workspaceId=k.workspaceId),k!=null&&k.resumeSessionId&&(T.resumeSessionId=k.resumeSessionId),(x=k==null?void 0:k.args)!=null&&x.trim()&&(T.cliArgs=k.args.trim().split(/\s+/).filter(Boolean)),(E=k==null?void 0:k.model)!=null&&E.trim()&&(T.initialModel=k.model.trim());const L=await e(h,"launch_cli",T),M=(L==null?void 0:L.result)||L,W=(M==null?void 0:M.sessionId)||(M==null?void 0:M.id);if(L!=null&&L.success&&W){p(null),i("done"),l(`${_} launched`),s(ns(W));return}if(L!=null&&L.success){i("loading"),l(`${_} launch requested — waiting for session…`);return}p(null),i("error"),l((L==null?void 0:L.error)||(M==null?void 0:M.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(T){if(fh(T)){i("loading"),l(`${_} launch requested — waiting for session…`);return}p(null),i("error"),l(T instanceof Error?T.message:`Could not launch ${N.toUpperCase()} workspace`)}},[s,e]),d=o.useCallback(async(h,N)=>{try{const _=await e(h,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),k=(_==null?void 0:_.result)??_;return Array.isArray(k==null?void 0:k.sessions)?k.sessions:[]}catch(_){return console.error("Failed to list saved sessions on mobile:",_),[]}},[e]),b=o.useCallback(async(h,N)=>yn(e,h,N),[e]);o.useEffect(()=>{if(!u)return;const h=ii(u.workspacePath),N=r.find(k=>{var T,L,M,W;if(!k||k.type==="adhdev-daemon"||ph(k.daemonId||k.id)!==u.machineId||(k.transport==="acp"?"acp":k.transport==="pty"?"cli":null)!==u.kind||String(k.agentType||k.type||"")!==u.providerType)return!1;const x=String(k.providerSessionId||"");if(u.resumeSessionId&&x)return x===u.resumeSessionId;if(h){const U=ii(k.workspace||k.runtimeWorkspaceLabel);return U?U===h:!1}return Number(k.lastUpdated||k._lastUpdate||k.timestamp||((W=(M=(L=(T=k.activeChat)==null?void 0:T.messages)==null?void 0:L.at)==null?void 0:M.call(L,-1))==null?void 0:W.timestamp)||0)>=u.startedAt-5e3});if(!N)return;const _=lc({entrySessionId:N.sessionId,entryInstanceId:N.instanceId,entryRouteId:N.id,conversations:n});_&&(p(null),i("done"),l(`${u.providerType} launched`),s(ns(_)))},[n,r,s,u]),o.useEffect(()=>{if(!u)return;const h=window.setTimeout(()=>{p(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(h)},[u]);const y=o.useCallback(async(h,N)=>{if(N.kind==="ide"&&N.providerType){await f(h,N.providerType,{workspacePath:N.workspace||null});return}(N.kind==="cli"||N.kind==="acp")&&N.providerType&&await A(h,N.kind,N.providerType,{workspacePath:N.workspace||null,resumeSessionId:N.providerSessionId||null})},[f,A]);return{machineAction:{state:a,message:c},resetMachineAction:m,handleLaunchDetectedIde:f,handleAddWorkspace:g,handleMachineUpgrade:w,handleLaunchWorkspaceProvider:A,handleListSavedSessions:d,handleBrowseDirectory:b,handleOpenRecent:y}}function xh({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:p}){const m=o.useCallback(y=>{i(y.tabKey),c("chat"),n(y)},[n,c,i]),f=o.useCallback(y=>{const h=e.find(N=>N.routeId===y.routeId&&N.streamSource==="native");h&&(i(h.tabKey),c("chat"),n(h))},[e,n,c,i]),g=o.useCallback(()=>{n(s),c("inbox")},[n,s,c]),w=o.useCallback((y,h="inbox")=>{l(y),a(),u("machines"),p(h),c("machine")},[a,p,c,u,l]),A=o.useCallback(y=>{const h=os(y);h&&w(h,"chat")},[w]),d=o.useCallback(()=>{a(),c(r)},[r,a,c]),b=o.useCallback(y=>{u(y),c("inbox")},[c,u]);return{openConversation:m,openNativeConversation:f,backFromConversation:g,openMachine:w,openConversationMachine:A,backFromMachine:d,changeMachineSection:b}}function bh(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function Or(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function gh({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,userName:u,requestedActiveTabKey:p,onRequestedActiveTabConsumed:m,requestedMachineId:f,onRequestedMachineConsumed:g,requestedMobileSection:w,onRequestedMobileSectionConsumed:A,onOpenHistory:d,onOpenRemote:b,onStopCli:y,wsStatus:h,isConnected:N,onShowHiddenConversation:_,onShowAllHiddenConversations:k,onHideConversation:I,onOpenNewSession:j,notificationStateBySessionId:v,liveSessionInboxState:x,onMarkNotificationTargetRead:E}){const[T,L]=o.useState(()=>{var Q;return((Q=e[0])==null?void 0:Q.tabKey)||null}),[M,W]=o.useState(()=>e[0]?"chat":"inbox"),[U,C]=o.useState("chats"),[R,B]=o.useState(null),[S,D]=o.useState("inbox"),Y=Us(),q="0.8.84",H=o.useMemo(()=>e.find(Q=>Q.tabKey===T)||e[0]||null,[e,T]),re=o.useMemo(()=>H?r.find(Q=>Q.id===H.routeId):void 0,[r,H]),ie=o.useMemo(()=>!H||Ze(H)||!tt(H)?null:Bs(H),[H]),Se=o.useMemo(()=>r.filter(Q=>Q.type==="adhdev-daemon").sort(Ta),[r]),X=o.useMemo(()=>Se.find(Q=>Q.id===R)||null,[Se,R]),fe=xn({sendDaemonCommand:a,activeConv:H||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),we=hh({sendDaemonCommand:a,navigate:Y,ides:r,conversations:e}),ce=o.useMemo(()=>e.map(Q=>{const Me=M==="chat"&&(H==null?void 0:H.tabKey)===Q.tabKey,We=fn(Q,x,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Me,notificationStateBySessionId:v}),Pe=us(Q),Ke=vc(Q);return{conversation:Q,timestamp:Pe,preview:Ke,unread:We.unread,requiresAction:We.requiresAction,isWorking:We.isWorking,inboxBucket:We.inboxBucket}}),[e,x,v,M,H]),{markConversationRead:he}=mh({conversations:e,machineEntries:Se,items:ce,selectedConversation:H,selectedTabKey:T,screen:M,liveSessionInboxState:x,sendDaemonCommand:a,requestedActiveTabKey:p,onRequestedActiveTabConsumed:m,requestedMachineId:f,onRequestedMachineConsumed:g,requestedMobileSection:w,onRequestedMobileSectionConsumed:A,setSelectedTabKey:L,setScreen:W,setSelectedMachineId:B,setSection:C,setMachineBackTarget:D,resetMachineAction:we.resetMachineAction,markNotificationTargetRead:E}),de=xh({conversations:e,selectedConversation:H,machineBackTarget:S,markConversationRead:he,resetMachineAction:we.resetMachineAction,setSelectedTabKey:L,setScreen:W,setSelectedMachineId:B,setSection:C,setMachineBackTarget:D}),z=o.useMemo(()=>Or(ce.filter(Q=>Q.requiresAction)),[ce]),ge=o.useMemo(()=>Or(ce.filter(Q=>Q.unread&&!Q.requiresAction)),[ce]),ae=o.useMemo(()=>Or(ce.filter(Q=>!Q.unread&&!Q.requiresAction&&Q.isWorking)),[ce]),oe=o.useMemo(()=>Or(ce.filter(Q=>!Q.unread&&!Q.requiresAction&&!Q.isWorking)),[ce]),ee=o.useMemo(()=>X?ce.filter(Q=>os(Q.conversation)===X.id):[],[ce,X]),ue=o.useMemo(()=>dh(X,r),[r,X]),se=(X==null?void 0:X.version)||null,ke=!!X&&!!se&&!0&&se!==q,ye=o.useMemo(()=>(X==null?void 0:X.availableProviders)||[],[X]),K=o.useMemo(()=>ye.filter(Q=>Q.category==="cli"&&Q.installed!==!1).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[ye]),V=o.useMemo(()=>ye.filter(Q=>Q.category==="acp"&&Q.installed!==!1).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[ye]),ve=o.useMemo(()=>uh(Se,ce),[ce,Se]),xe=o.useCallback(async Q=>{X&&await we.handleOpenRecent(X.id,Q)},[we,X]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:M==="chat"&&H?t.jsx(Jf,{selectedConversation:H,isAcp:Ze(H),isStandalone:l,selectedIdeEntry:re,actionLogs:n,userName:u,isSendingChat:fe.isSendingChat,sendFeedbackMessage:fe.sendFeedbackMessage,isFocusingAgent:fe.isFocusingAgent,handleModalButton:fe.handleModalButton,handleRelaunch:fe.handleRelaunch,onBack:de.backFromConversation,onOpenNativeConversation:de.openNativeConversation,onOpenMachine:de.openConversationMachine,onHideConversation:I,onOpenHistory:d,onOpenRemote:b,onStopCli:y,cliViewMode:ie,onSetCliViewMode:async Q=>{if(H&&ie!==Q)try{await a(os(H)||H.routeId,"set_cli_view_mode",{targetSessionId:H.sessionId,cliType:Bt(H),mode:Q})}catch(Me){const We=Qa(Me);Xa(Me)?console.warn(We?"CLI view mode result was lost after send; keeping optimistic mobile mode override:":"Skipped CLI view mode switch:",Me instanceof Error?Me.message:String(Me)):console.error("Failed to switch CLI view mode:",Me)}},handleSendChat:fe.handleSendChat,handleFocusAgent:fe.handleFocusAgent}):M==="machine"&&X?t.jsx(lh,{selectedMachineEntry:X,selectedMachineConversations:ee,selectedMachineRecentLaunches:ue,cliProviders:K,acpProviders:V,selectedMachineNeedsUpgrade:ke,appVersion:q,machineAction:we.machineAction,isStandalone:l,section:U,showBottomNav:S==="inbox",onBack:de.backFromMachine,onSectionChange:de.changeMachineSection,onOpenConversation:de.openConversation,onOpenRecent:xe,onOpenMachineDetails:()=>Y(`/machines/${X.id}`),onMachineUpgrade:()=>we.handleMachineUpgrade(X.id),onLaunchDetectedIde:(Q,Me)=>we.handleLaunchDetectedIde(X.id,Q,Me),onAddWorkspace:(Q,Me)=>we.handleAddWorkspace(X.id,Q,Me),onBrowseDirectory:Q=>we.handleBrowseDirectory(X.id,Q),onLaunchWorkspaceProvider:(Q,Me,We)=>we.handleLaunchWorkspaceProvider(X.id,Q,Me,We),onListSavedSessions:Q=>we.handleListSavedSessions(X.id,Q)}):t.jsx(eh,{section:U,attentionItems:z,unreadItems:ge,workingItems:ae,completedItems:oe,hiddenConversations:s,machineCards:ve,getAvatarText:bh,onOpenConversation:de.openConversation,onShowConversation:_,onShowAllHidden:k,onOpenNewSession:j,onOpenMachine:de.openMachine,onOpenSettings:()=>Y("/settings"),onSectionChange:C,wsStatus:h,isConnected:N,isStandalone:l})})}function Un(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function yh({conversations:e,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,u]=o.useState(!1),[p,m]=o.useState(null),f=o.useCallback(()=>{c.current=0,u(!1),m(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",f),window.addEventListener("drop",f),()=>{window.removeEventListener("dragend",f),window.removeEventListener("drop",f)}),[f]);const g=o.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),w=o.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!Un(s,r)){m("merge");return}const y=b.currentTarget.getBoundingClientRect(),h=b.clientX-y.left,N=y.width/3;h<N?m("split-left"):h>N*2?m("split-right"):m("merge")},[s,r]),A=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,u(!1),m(null))},[]),d=o.useCallback(b=>{c.current=0,u(!1);const y=b.dataTransfer.getData("text/tab-key"),h=y?e.some(_=>_.tabKey===y):!1,N=p;if(m(null),i(),!!y){if(b.preventDefault(),N==="split-left"&&Un(s,r)){r==null||r(y,"split-left");return}if(N==="split-right"&&Un(s,r)){r==null||r(y,"split-right");return}if(h){a(y);return}n==null||n(y)}},[e,p,s,r,n,a,i]);return{dragOver:l,dropAction:p,resetDragState:f,handleDragEnter:g,handleDragOver:w,handleDragLeave:A,handleDrop:d}}function vh(e,s){const r=new Set(s.map(i=>i.tabKey)),n=e.filter(i=>r.has(i)),a=s.filter(i=>!e.includes(i.tabKey)).map(i=>i.tabKey);return[...n,...a]}function wh({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(s??null),[l,u]=o.useState(r??[]),[p,m]=o.useState(null),f=o.useRef(null),g=o.useRef(null),w=o.useRef(n),A=o.useRef(a);o.useEffect(()=>{w.current=n},[n]),o.useEffect(()=>{A.current=a},[a]),o.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),o.useEffect(()=>{u(j=>{const v=vh(j,e);return v.length===j.length&&v.every((x,E)=>x===j[E])?j:v})},[e]);const d=o.useMemo(()=>{const j=p??l;if(j.length===0)return e;const v=new Map(j.map((x,E)=>[x,E]));return[...e].sort((x,E)=>{const T=v.get(x.tabKey)??999,L=v.get(E.tabKey)??999;return T-L})},[e,p,l]);o.useEffect(()=>{var v,x;if(d.length===0){i!==null&&(c(null),(v=w.current)==null||v.call(w,null));return}if(i&&d.some(E=>E.tabKey===i))return;const j=d[0].tabKey;j!==i&&(c(j),(x=w.current)==null||x.call(w,j))},[d,i]);const b=o.useMemo(()=>d.find(j=>j.tabKey===i),[d,i]),y=o.useCallback(j=>{var v;c(j),(v=w.current)==null||v.call(w,j)},[]),h=o.useCallback((j,v,x)=>{u(E=>{var W;const T=E.filter(U=>U!==j),L=T.indexOf(v);if(L<0)return E;const M=x==="left"?L:L+1;return T.splice(M,0,j),(W=A.current)==null||W.call(A,T),T}),m(null)},[]),N=o.useCallback((j,v,x)=>{const T=(l.length>0?l:e.map(W=>W.tabKey)).filter(W=>W!==j),L=T.indexOf(v);if(L<0)return;const M=x==="left"?L:L+1;T.splice(M,0,j),f.current=T,m(T)},[l,e]),_=o.useCallback(()=>{var v;const j=f.current;j&&(u(j),(v=A.current)==null||v.call(A,j))},[]),k=o.useCallback(()=>{f.current=null,m(null)},[]),I=o.useCallback(j=>{u(v=>{var E;const x=v.filter(T=>T!==j);return x.push(j),(E=A.current)==null||E.call(A,x),x})},[]);return{activeTabId:i,activeConv:b,sortedConversations:d,previewOrderRef:f,draggingTabRef:g,selectTab:y,handleTabReorder:h,updatePreviewOrder:N,commitPreviewOrder:_,clearPreviewOrder:k,moveTabToEnd:I,setDraggingTabKey:j=>{g.current=j}}}function jh({dropAction:e,canSplit:s}){return t.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[t.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:s?1:.45},children:t.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"})}),t.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:t.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"})}),t.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:s?1:.45},children:t.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 ro({conversationsCount:e,isSplitMode:s,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1}){if(a)return t.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const i=!r&&!n,c=r?"Waiting for your daemon":n?"No conversations yet":"Connect your machines",l=r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":n?"Your machines are connected. Open a machine, choose a workspace, then launch an IDE, CLI, or ACP session.":"Install ADHDev on a machine, sign in, and it will show up here.";return e===0&&!s?t.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[t.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),t.jsxs("div",{className:"text-center max-w-lg",children:[t.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:c}),t.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:l}),i&&t.jsx(Qc,{}),i&&t.jsx("div",{className:"mt-8",children:t.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 →"})})]})]}):t.jsx("div",{className:"text-sm text-text-muted opacity-50",children:s?"Move a tab here to view":"No active agent"})}const sl="adhdev-tab-shortcuts";function rl(){try{return JSON.parse(localStorage.getItem(sl)||"{}")}catch{return{}}}function nl({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>rl()),[l,u]=o.useState(null),p=o.useCallback(f=>{const g=[];return f.metaKey&&g.push(a?"⌘":"Meta"),f.ctrlKey&&g.push("Ctrl"),f.altKey&&g.push(a?"⌥":"Alt"),f.shiftKey&&g.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(g.push(f.key.length===1?f.key.toUpperCase():f.key),g.join("+"))},[a]),m=o.useCallback(f=>{c(f);try{localStorage.setItem(sl,JSON.stringify(f))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const f=g=>{if(g.preventDefault(),g.stopPropagation(),g.key==="Escape"){u(null);return}const w=p(g);if(!w)return;const A={...i};for(const[d,b]of Object.entries(A))b===w&&delete A[d];A[l]=w,m(A),u(null)};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[e,l,i,m,p]),o.useEffect(()=>{if(!e)return;const f=g=>{if(!(!g.ctrlKey&&!g.metaKey&&!g.altKey)){for(const[w,A]of Object.entries(i))if(s.includes(w)&&p(g)===A){g.preventDefault(),r(),n(w);return}}};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,i,s,r,n,p]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:u,saveShortcuts:m}}const kh=o.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:u,onSelectTab:p,onConversationActivated:m,onPreviewReorder:f,onReorderTab:g,onCommitPreviewOrder:w,onClearPreviewOrder:A,onDragStateReset:d,onDragTabKeyChange:b,onReceiveTab:y,onOpenContextMenu:h,longPressTimer:N,isGroupActive:_}){const k=zs(s),I=k.isGenerating?"agent-tab-generating":k.isWaiting?"agent-tab-waiting":"",j=k.isReconnecting,v=o.useCallback(R=>{l.current=s.tabKey,b(s.tabKey),R.dataTransfer.setData("text/tab-key",s.tabKey),R.dataTransfer.effectAllowed="move"},[s.tabKey,l,b]),x=o.useCallback(()=>{l.current=null,b(null),w(),A(),d()},[l,b,w,A,d]),E=o.useCallback(R=>{const B=l.current;if(!(!B||B===s.tabKey)&&R.dataTransfer.types.includes("text/tab-key")){R.preventDefault(),R.stopPropagation();const S=R.currentTarget.getBoundingClientRect(),D=R.clientX<S.left+S.width/2?"left":"right";f(B,s.tabKey,D)}},[s.tabKey,l,f]),T=o.useCallback(R=>{R.preventDefault(),R.stopPropagation();const B=R.dataTransfer.getData("text/tab-key");if(B&&B!==s.tabKey){const S=R.currentTarget.getBoundingClientRect(),D=R.clientX<S.left+S.width/2?"left":"right";c.includes(B)?g(B,s.tabKey,D):y&&y(B)}A()},[s.tabKey,c,g,y,A]),L=o.useCallback(R=>{R.stopPropagation(),u(),p(s.tabKey),m(s)},[s,m,u,p]),M=o.useCallback(R=>{R.preventDefault(),h(R.clientX,R.clientY,s.tabKey)},[s.tabKey,h]),W=o.useCallback(R=>{const B=R.touches[0];N.current=setTimeout(()=>{h(B.clientX,B.clientY,s.tabKey)},600)},[s.tabKey,N,h]),U=o.useCallback(()=>{N.current&&clearTimeout(N.current)},[N]),C=["adhdev-dockview-tab",I,r&&"is-active",_&&"is-group-active",j&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:C,draggable:!0,onDragStart:v,onDragEnd:x,onDragOver:E,onDrop:T,onClick:L,onContextMenu:M,onTouchStart:W,onTouchEnd:U,onTouchMove:U,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status",children:k.isGenerating?t.jsx("div",{className:"tab-spinner"}):k.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):k.isConnecting?t.jsx("div",{className:"tab-connecting-spinner"}):s.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("span",{className:"adhdev-dockview-tab-primary",title:lt(s),children:lt(s)}),t.jsx("span",{className:"adhdev-dockview-tab-meta",children:j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ps(s)}):k.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[ps(s),t.jsx("span",{className:"connecting-dots"})]}):ps(s)})]}),i&&t.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,s)=>e.conv===s.conv&&e.isActive===s.isActive&&e.isDraggedTab===s.isDraggedTab&&e.isTaskCompleteUnread===s.isTaskCompleteUnread&&e.shortcut===s.shortcut&&e.conversationKeys===s.conversationKeys&&e.isGroupActive===s.isGroupActive);function Sh({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:m,onClearPreviewOrder:f,onDragStateReset:g,onDragTabKeyChange:w,onReceiveTab:A,onHideTab:d,isGroupActive:b,allowTabShortcuts:y=!0}){const[h,N]=o.useState(null),_=o.useRef(null),k=o.useRef(null),I=o.useMemo(()=>e.map(M=>M.tabKey),[e]);xr("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(h==null?void 0:h.tabKey)||null});const{isMac:j,tabShortcuts:v,shortcutListening:x,setShortcutListening:E,saveShortcuts:T}=nl({enabled:y,sortedTabKeys:e.map(M=>M.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!h)return;const M=W=>{const U=document.querySelector("[data-pane-context-menu]");U&&U.contains(W.target)||N(null)};return window.addEventListener("mousedown",M,!0),()=>window.removeEventListener("mousedown",M,!0)},[h]),o.useEffect(()=>{const M=k.current;if(!M)return;const W=U=>{Math.abs(U.deltaY)<=Math.abs(U.deltaX)||(U.preventDefault(),M.scrollLeft+=U.deltaY)};return M.addEventListener("wheel",W,{passive:!1}),()=>M.removeEventListener("wheel",W)},[]);const L=o.useCallback((M,W,U)=>{N({x:M,y:W,tabKey:U})},[]);return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:t.jsxs("div",{ref:k,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(M=>t.jsx(kh,{conv:M,isActive:s===M.tabKey,isDraggedTab:a.current===M.tabKey,isTaskCompleteUnread:n.has(M.tabKey),shortcut:y?v[M.tabKey]:void 0,conversationKeys:I,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:m,onClearPreviewOrder:f,onDragStateReset:g,onDragTabKeyChange:w,onReceiveTab:A,onOpenContextMenu:L,longPressTimer:_,isGroupActive:b},M.tabKey)),e.length===0&&t.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),h&&t.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:h.x,top:h.y},children:[y&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:M=>{M.stopPropagation(),E(h.tabKey),N(null)},children:["⌨ ",v[h.tabKey]?`Change shortcut (${v[h.tabKey]})`:"Set shortcut"]}),v[h.tabKey]&&t.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 M={...v};delete M[h.tabKey],T(M),N(null)},children:"✕ Remove shortcut"})]}),d&&t.jsxs(t.Fragment,{children:[y&&t.jsx("div",{className:"border-t border-border-subtle my-1"}),t.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onClick:()=>{d(h.tabKey),N(null)},children:"🚫 Hide from Dashboard"})]})]}),y&&x&&t.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>E(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:M=>M.stopPropagation(),children:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",j?"⌘+1":"Ctrl+1",", ",j?"⌥+A":"Alt+A",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function Nh({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:u,userName:p,groupIndex:m,onFocus:f,isSplitMode:g,numGroups:w,onMoveTab:A,onReceiveTab:d,style:b,onActiveTabChange:y,initialActiveTabId:h,initialTabOrder:N,onTabOrderChange:_,onHideTab:k,isFocused:I,allowTabShortcuts:j=!0,notificationStateBySessionId:v,liveSessionInboxState:x}){const{sendCommand:E}=Pt(),T=o.useRef(null),{activeTabId:L,activeConv:M,sortedConversations:W,draggingTabRef:U,selectTab:C,handleTabReorder:R,updatePreviewOrder:B,commitPreviewOrder:S,clearPreviewOrder:D,moveTabToEnd:Y,setDraggingTabKey:q}=wh({conversations:e,initialActiveTabId:h,initialTabOrder:N,onActiveTabChange:y,onTabOrderChange:_}),H=xn({sendDaemonCommand:a,activeConv:M,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),{dragOver:re,dropAction:ie,resetDragState:Se,handleDragEnter:X,handleDragOver:fe,handleDragLeave:we,handleDrop:ce}=yh({conversations:e,numGroups:w,onMoveTab:A,onReceiveTab:d,onOwnTabDrop:Y,onClearPreviewOrder:D}),he=M&&!Ze(M)&&Bs(M)==="terminal",de=o.useMemo(()=>M?s.find(oe=>oe.id===M.routeId):void 0,[s,M]),z=o.useMemo(()=>M?n.filter(oe=>oe.routeId===M.tabKey):[],[n,M]),ge=o.useMemo(()=>new Set(W.filter(oe=>lu(oe,x,{isOpenConversation:oe.tabKey===L,notificationStateBySessionId:v})).map(oe=>oe.tabKey)),[L,x,W]);xr("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:L,dragOver:re});const ae=o.useCallback(oe=>{oe.streamSource==="agent-stream"&&oe.agentType&&E(oe.routeId,Xc(),{agentType:oe.agentType,...oe.sessionId&&{targetSessionId:oe.sessionId}}).catch(()=>{})},[E]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:f,style:{...b,outline:re?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(Sh,{conversations:W,activeTabId:L,groupIndex:m,numGroups:w,unreadTabKeys:ge,draggingTabRef:U,onFocus:f,onSelectTab:C,onConversationActivated:ae,onPreviewReorder:B,onReorderTab:R,onCommitPreviewOrder:S,onClearPreviewOrder:D,onDragStateReset:Se,onDragTabKeyChange:q,onMoveTab:A,onReceiveTab:d,onHideTab:k,isGroupActive:I??!1,allowTabShortcuts:j}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:X,onDragOver:fe,onDragLeave:we,onDrop:ce,children:[re&&t.jsx(jh,{dropAction:ie,canSplit:!!(w<4&&A)}),M?t.jsx(to,{activeConv:M,clearToken:r[M.tabKey]||0,isCliTerminal:!!he,ideEntry:de,terminalRef:T,handleModalButton:H.handleModalButton,handleRelaunch:H.handleRelaunch,handleSendChat:H.handleSendChat,isSendingChat:H.isSendingChat,sendFeedbackMessage:H.sendFeedbackMessage,handleFocusAgent:H.handleFocusAgent,isFocusingAgent:H.isFocusingAgent,actionLogs:z,userName:p,isInputActive:!g||!!I}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(ro,{conversationsCount:e.length,isSplitMode:g,isStandalone:l,hasRegisteredMachines:u})})]})]})}function Ch({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:p,setActionLogs:m,isStandalone:f,hasRegisteredMachines:g,userName:w,focusedGroup:A,setFocusedGroup:d,moveTabToGroup:b,splitTabRelative:y,closeGroup:h,handleResizeStart:N,groupActiveTabIds:_,setGroupActiveTabIds:k,groupTabOrders:I,setGroupTabOrders:j,toggleHiddenTab:v,allowTabShortcuts:x=!0,notificationStateBySessionId:E,liveSessionInboxState:T}){return t.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:a.map((L,M)=>{const W=s&&n.length===r?`${n[M]}%`:void 0;return t.jsxs(at.Fragment,{children:[s&&M>0&&t.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:U=>N(M-1,U),onDoubleClick:()=>h(M),title:"Drag to resize · Double-click to merge",children:t.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),t.jsx(Nh,{style:s?{flexBasis:W??`${100/r}%`,flexGrow:W?0:1,flexShrink:W?0:1}:void 0,conversations:L,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:p,setActionLogs:m,isStandalone:f,hasRegisteredMachines:g,userName:w,groupIndex:M,isFocused:s&&A===M,onFocus:()=>d(M),isSplitMode:s,numGroups:r,onMoveTab:(U,C)=>{C==="left"&&M>0?b(U,M-1):C==="right"&&M<r-1?b(U,M+1):C==="split-left"&&r<4?y(U,M,"left"):C==="split-right"&&r<4&&y(U,M,"right")},onReceiveTab:U=>b(U,M),onActiveTabChange:U=>k(C=>(C[M]??null)===(U??null)?C:{...C,[M]:U}),initialActiveTabId:_[M],initialTabOrder:I[M],onTabOrderChange:U=>j(C=>{const R=C[M]||[];return R.length===U.length&&R.every((B,S)=>B===U[S])?C:{...C,[M]:U}}),onHideTab:v,allowTabShortcuts:x,notificationStateBySessionId:E,liveSessionInboxState:T})]},M)})})}function al({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?ft.onScreenshot("ide-page",(m,f)=>{if(m!==e)return;const g=new FileReader;g.onload=()=>i(g.result),g.readAsDataURL(f)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var m;return e?((m=ft.onStatus)==null?void 0:m.call(ft,(f,g)=>{f===e&&g!=null&&g.screenshotUsage&&l(g.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,s]),o.useEffect(()=>{const p=e?ft.get(e):null;if(!(!p||r!=="connected"))return n!=="chat"&&s?p.startScreenshots(s):p.stopScreenshots(s),()=>{p.stopScreenshots(s)}},[n,r,s,e]);const u=o.useCallback(async(p,m)=>{const f=e?ft.get(e):null;return!f||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):f.sendInput(p,m,s)},[e,r,s]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:u}}const ol="adhdev-dashboard-action-shortcuts",Ih=1200,Ah={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Mh(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function nt(e,s){switch(e){case"openShortcutHelp":return"?";case"hideCurrentTab":return s?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return s?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return s?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return s?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return s?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return s?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return s?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return s?"⌘+⌥+=":"Ctrl+Alt+\\";case"splitActiveTabDown":return s?"⌘+⌥+-":"Ctrl+Alt+-";case"focusLeftPane":return s?"⌘+⌥+[":"Ctrl+Alt+←";case"focusRightPane":return s?"⌘+⌥+]":"Ctrl+Alt+→";case"focusUpPane":return s?"⌘+⌥+U":"Ctrl+Alt+↑";case"focusDownPane":return s?"⌘+⌥+J":"Ctrl+Alt+↓";case"moveActiveTabToLeftPane":return s?"⌘+⌥+,":"Ctrl+Alt+Shift+←";case"moveActiveTabToRightPane":return s?"⌘+⌥+.":"Ctrl+Alt+Shift+→";case"moveActiveTabToUpPane":return s?"⌘+⌥+I":"Ctrl+Alt+Shift+↑";case"moveActiveTabToDownPane":return s?"⌘+⌥+K":"Ctrl+Alt+Shift+↓";case"triggerPrimaryApprovalAction":return s?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return s?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return s?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return s?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return s?"⌥+[":"Ctrl+Alt+[";case"selectNextGroupTab":return s?"⌥+]":"Ctrl+Alt+]";case"toggleCliView":return s?"⌥+T":"Ctrl+Alt+T"}}function il(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:nt("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:nt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:nt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:nt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:nt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:nt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:nt("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:nt("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:nt("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:nt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:nt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:nt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:nt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:nt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:nt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:nt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:nt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:nt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:nt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:nt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:nt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:nt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:nt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:nt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:nt("toggleCliView",e)}]}function ba(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function cn(e){const s=Object.fromEntries(il(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(ol)||"{}"),n={...s,...r};for(const[a,i]of Object.entries(Ah))n[a]===i&&(n[a]=s[a]);return n}catch{return s}}function cl(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Th({enabled:e=!0,onTrigger:s}){const r=Mh(),[n,a]=o.useState(()=>cn(r)),[i,c]=o.useState(null),[l,u]=o.useState([]),p=o.useRef({parts:[],timer:null}),m=o.useCallback(d=>{const b=[];return d.metaKey&&b.push(r?"⌘":"Meta"),d.ctrlKey&&b.push("Ctrl"),d.altKey&&b.push(r?"⌥":"Alt"),d.shiftKey&&d.key.length!==1&&b.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(d.key)?null:(b.push(cl(d.key)),b.join("+"))},[r]),f=o.useCallback(d=>{a(d);try{localStorage.setItem(ol,JSON.stringify(d))}catch{}},[]);o.useEffect(()=>{const d=cn(r),b=Object.entries(n),y=Object.entries(d);b.length===y.length&&b.every(([h,N])=>d[h]===N)||f(d)},[n,r,f]);const g=o.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),w=o.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},Ih))},[]);o.useEffect(()=>{if(!i)return;const d=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){c(null),u([]);return}const y=m(b);if(!y)return;const N=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(y);if(l.length===0&&N){u([y]);return}const k=[...l,y].slice(0,2).join(" "),I={...n};for(const[j,v]of Object.entries(I))v===k&&delete I[j];I[i]=k,f(I),c(null),u([])};return window.addEventListener("keydown",d,!0),()=>window.removeEventListener("keydown",d,!0)},[n,m,f,i,l]),o.useEffect(()=>{if(!e||i)return;const d=b=>{if(b.defaultPrevented)return;const y=m(b);if(!y)return;const h=b.metaKey||b.ctrlKey||b.altKey;if(ba(b.target)&&!h)return;const N=p.current.parts,_=h?[y]:[...N.slice(-1),y].slice(-2),k=_.join(" "),I=_[_.length-1],j=Object.entries(n).filter(([,L])=>!!L),v=j.find(([,L])=>L===k);if(v){b.preventDefault(),g(),s(v[0]);return}if(j.some(([,L])=>L.startsWith(`${k} `))){b.preventDefault(),p.current.parts=_,w();return}const E=j.find(([,L])=>L===I);if(E){b.preventDefault(),g(),s(E[0]);return}if(j.some(([,L])=>L.startsWith(`${I} `))){b.preventDefault(),p.current.parts=[I],w();return}g()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n,w,e,m,s,g,i]),o.useEffect(()=>()=>g(),[g]);const A=o.useMemo(()=>il(r),[r]);return{isMac:r,actionDefinitions:A,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:f}}function Lh({isTabInPopout:e,isTabFloating:s,tabShortcut:r,actionShortcuts:n}){const a=[];return e?(s&&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})):s?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 _h(e){return e.some(s=>s.type!=="adhdev-daemon")||e.some(s=>s.type==="adhdev-daemon"&&!!s.machine)}function ci({hasStoredLayout:e,initialDataLoaded:s,visibleConversationCount:r,ides:n}){return!e||r>0?!1:s?!_h(n):!0}const ll=o.createContext(null);function wn(){const e=o.useContext(ll);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Qr(e){return lt(e)||e.tabKey}function Rh(e){return`remote:${e}`}function Zt(e){return e.startsWith("remote:")}function li(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Fn(e){var r,n,a,i,c;const s=e==null?void 0:e.defaultView;if(s)try{s.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=s.requestAnimationFrame)==null||c.call(s,()=>{var l,u;try{s.focus(),(u=(l=e==null?void 0:e.body)==null?void 0:l.focus)==null||u.call(l)}catch{}})}catch{}}function Hr(e,s){e.classList.remove(ta.className,sa.className),e.classList.add(s==="light"?ta.className:sa.className)}function di(e){return e?Array.from(new Set(e.groups.map(s=>{var r,n;return(n=(r=s.element)==null?void 0:r.ownerDocument)==null?void 0:n.defaultView}).filter(s=>!!s&&s!==window))):[]}function Ph(e){const[,s]=o.useState(0);o.useEffect(()=>{const r=()=>s(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 Dh(e,s,r){var c;const n=[s];let a;for(const l of n){let u;for(const p of l){const m=e.addPanel({id:p.tabKey,component:"conversation",title:Qr(p),params:{kind:"conversation",tabKey:p.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});u||(u=m.id)}a=u??a}return r??((c=s[0])==null?void 0:c.tabKey)??null}function ui(e,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...e.panels])Zt(n.id)||r.has(n.id)||e.removePanel(n);for(const n of s){const a=e.getPanel(n.tabKey);if(a){a.update({params:{tabKey:n.tabKey}}),a.title!==Qr(n)&&a.api.setTitle(Qr(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:Qr(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 mi(e,s,r){var u,p;const n=r?Rh(r):null;for(const m of[...e.panels])Zt(m.id)&&(!n||m.id!==n)&&e.removePanel(m);if(!r||!n)return;const a=Ot(s,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=kc(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)??((p=e.panels.find(m=>!Zt(m.id)))==null?void 0:p.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function Eh({params:e,api:s}){var f;const r=wn(),n=o.useRef(null),[a,i]=o.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=xn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(s.isActive);const g=[s.onDidActiveChange(w=>i(w.isActive)),s.onDidActiveGroupChange(w=>{if(!s.isActive&&!w.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const w of g)w.dispose()}},[s]);const u=o.useMemo(()=>c?r.ides.find(g=>g.id===c.routeId):void 0,[r.ides,c]),p=o.useMemo(()=>c?r.actionLogs.filter(g=>g.routeId===c.tabKey):[],[r.actionLogs,c]);if(!c)return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:t.jsx(ro,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,suppressGuide:r.hasDetachedConversationPanels})});const m=!Ze(c)&&Bs(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(to,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:m,ideEntry:u,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:p,userName:r.userName,scrollToBottomRequestNonce:((f=r.scrollToBottomRequest)==null?void 0:f.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a})})}function $h({params:e}){var u;const s=wn(),r=o.useMemo(()=>Ot([...s.conversationsByTabKey.values()],e.routeId),[s.conversationsByTabKey,e.routeId]),n=o.useMemo(()=>s.ides.find(p=>p.id===e.routeId),[s.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}=al({doId:a,targetSessionId:r?oc(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?t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:t.jsx(Hi,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:c,transportType:r.transport,onAction:l})}):t.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 Kh(){const e=wn();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(ro,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,suppressGuide:e.hasDetachedConversationPanels})})}function Bh(e){var w,A;Ph(e);const s=wn(),r=o.useCallback(d=>{"button"in d&&d.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const d=Ot([...s.conversationsByTabKey.values()],e.params.routeId),b=((w=e.api.group.activePanel)==null?void 0:w.id)===e.api.id,y=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${b?" is-active":""}${y?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(d==null?void 0:d.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:d!=null&&d.machineName?t.jsxs(t.Fragment,{children:[t.jsx("span",{children:"Live remote view"}),t.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),t.jsx("span",{className:"adhdev-dockview-tab-machine",children:d.machineName})]}):t.jsx("span",{children:"Live remote view"})})]})]})}const n=s.conversationsByTabKey.get(e.params.tabKey);if(!n)return t.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:t.jsx("div",{className:"adhdev-dockview-tab-copy",children:t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const a=((A=e.api.group.activePanel)==null?void 0:A.id)===e.api.id,i=e.api.isGroupActive,c=fn(n,s.liveSessionInboxState,{isOpenConversation:a,notificationStateBySessionId:s.notificationStateBySessionId}),l=c.isReconnecting,u=c.isConnecting,p=c.isGenerating,m=c.isWaiting,f=c.unread,g=s.tabShortcuts[n.tabKey];return t.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:lt(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:d=>{var b;d.preventDefault(),r(d),s.openTabContextMenu({x:d.clientX,y:d.clientY,tabKey:n.tabKey,sourceDocument:((b=d.target)==null?void 0:b.ownerDocument)??document})},children:[f&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:p?t.jsx("div",{className:"tab-spinner"}):m?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):u?t.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:lt(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ps(n)}):u?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ps(n)}):t.jsx("span",{children:ps(n)})})]}),g&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:g,children:g})]})}function Wh({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:u,initialDataLoaded:p,userName:m,toggleHiddenTab:f,actionShortcuts:g,registerActionHandlers:w,onActiveTabChange:A,requestedActiveTabKey:d,requestedRemoteIdeId:b,onRequestedActiveTabConsumed:y,scrollToBottomRequest:h,notificationStateBySessionId:N,liveSessionInboxState:_}){var Tt,J,Re;const{theme:k}=za(),{sendCommand:I}=Pt(),j=o.useRef(null),v=o.useRef(null),x=o.useRef(!1),E=o.useRef(!1),T=o.useRef(!1),L=o.useRef(null),M=o.useRef([]),[W,U]=o.useState(null),[C,R]=o.useState(!1),[B,S]=o.useState(!1),[D,Y]=o.useState(0),q=o.useRef(null),H=o.useMemo(()=>zc(typeof window<"u"?window.innerWidth:1280),[]),re=o.useRef(typeof window>"u"?{}:vf(H)),ie=o.useMemo(()=>new Map(e.map(P=>[P.tabKey,P])),[e]),Se=o.useMemo(()=>{const P=j.current;return P?P.groups.some(O=>{try{const F=O.model.location.type;return F!=="floating"&&F!=="popout"?!1:O.panels.some(G=>ie.has(G.id))}catch{return!1}}):!1},[ie,D,e]),X=o.useCallback(()=>{var P;(P=j.current)==null||P.focus()},[]),fe=o.useCallback(P=>{const O=document,F=P.document;for(const Ae of O.querySelectorAll('link[rel="stylesheet"]')){const Oe=F.createElement("link");Oe.rel="stylesheet",Oe.href=Ae.href,Ae.crossOrigin&&(Oe.crossOrigin=Ae.crossOrigin),F.head.appendChild(Oe)}for(const Ae of O.querySelectorAll("style")){const Oe=F.createElement("style");Oe.textContent=Ae.textContent,F.head.appendChild(Oe)}const G=[];for(const Ae of O.styleSheets)try{for(const Oe of Ae.cssRules)Oe instanceof CSSStyleRule&&(Oe.selectorText===":root"||Oe.selectorText==="html")&&G.push(Oe.cssText)}catch{}if(G.length>0){const Ae=F.createElement("style");Ae.textContent=G.join(`
44
44
  `),F.head.appendChild(Ae)}const ne=O.documentElement.getAttribute("data-theme");ne&&F.documentElement.setAttribute("data-theme",ne),F.documentElement.style.colorScheme=ne==="light"?"light":"dark",F.body.className=O.body.className;const Ie=O.documentElement.getAttribute("style");Ie&&F.documentElement.setAttribute("style",Ie);const _e=F.getElementById("dv-popout-window");_e instanceof HTMLElement&&(_e.classList.add("adhdev-dockview"),Hr(_e,k))},[k]),we=o.useCallback(()=>{var O;const P=j.current;if(P)for(const F of P.groups)try{const G=(O=F.element)==null?void 0:O.ownerDocument;if(!G||G===document)continue;const ne=G.getElementById("dv-popout-window");ne instanceof HTMLElement&&(ne.classList.add("adhdev-dockview"),Hr(ne,k));const Ie=document.documentElement.getAttribute("data-theme");Ie&&G.documentElement.setAttribute("data-theme",Ie),G.documentElement.style.colorScheme=Ie==="light"?"light":"dark",G.body.className=document.body.className;const _e=document.documentElement.getAttribute("style");_e?G.documentElement.setAttribute("style",_e):G.documentElement.removeAttribute("style")}catch{}},[k]),ce=o.useCallback(()=>{var O;const P=j.current;if(P)for(const F of P.groups)try{const G=(O=F.element)==null?void 0:O.ownerDocument;if(!G||G===document)continue;const ne=G.getElementById("dv-popout-window");if(!(ne instanceof HTMLElement))continue;ne.classList.add("adhdev-dockview"),Hr(ne,k),ne.classList.toggle("is-showing-dockview-overlay",B),ne.classList.toggle("is-dragging-dockview",C)}catch{}},[C,B,k]),he=o.useCallback(P=>{const O=j.current;if(!O)return;const F=O.getPanel(P);F&&O.addPopoutGroup(F,{popoutUrl:"/popout.html",onDidOpen:({window:G})=>{fe(G),ke();const ne=ie.get(P);G.document.title=ne?`${lt(ne)} — ADHDev`:"ADHDev — Popout"}})},[ie,fe]),de=o.useCallback(P=>{const O=j.current,F=O==null?void 0:O.getPanel(P);if(!O||!F)return;const G=O.groups.filter(ne=>{var Ie;try{return((Ie=ne.element)==null?void 0:Ie.ownerDocument)===document}catch{return!0}});G.length>0?F.api.moveTo({group:G[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),z=o.useCallback(P=>{var G;const O=j.current;if(!O)return!1;const F=O.getPanel(P);if(!F)return!1;try{return((G=F.group.element)==null?void 0:G.ownerDocument)!==document}catch{return!1}},[]),ge=o.useCallback(P=>{z(P)&&de(P),f(P)},[z,de,f]),ae=o.useCallback(P=>{const O=j.current,F=O==null?void 0:O.getPanel(P);!O||!F||O.addFloatingGroup(F,{width:600,height:500})},[]),oe=o.useCallback(P=>{var F;const O=(F=j.current)==null?void 0:F.getPanel(P);if(!O)return!1;try{return O.group.model.location.type==="floating"}catch{return!1}},[]),ee=o.useCallback(()=>{var O,F;const P=(F=(O=j.current)==null?void 0:O.activePanel)==null?void 0:F.id;return!P||Zt(P)?null:ie.has(P)?P:null},[ie]),ue=o.useCallback(P=>{const O=j.current,F=O==null?void 0:O.getPanel(P);if(!O||!F)return;const G=O.groups.filter(ne=>{try{return ne.model.location.type==="grid"}catch{return!0}});G.length>0?F.api.moveTo({group:G[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),se=o.useCallback(()=>{var Ie;const P=j.current;if(!P)return;const F=P.groups.filter(_e=>{var Ae;try{return((Ae=_e.element)==null?void 0:Ae.ownerDocument)===document&&_e.model.location.type==="grid"}catch{return!1}})[0]||null,G=[...P.panels];for(const _e of G){const Ae=(Ie=_e.group.element)==null?void 0:Ie.ownerDocument,Oe=_e.group.model.location.type;Ae===document&&Oe==="grid"||(F&&F.id!==_e.group.id?_e.api.moveTo({group:F,position:"center"}):_e.api.moveTo({position:"center"}))}const ne=P.activePanel;ne&&(ne.group.model.openPanel(ne),ne.api.setActive()),Fn(document)},[]),ke=o.useCallback(()=>{var O,F;const P=j.current;if(P)for(const G of P.groups){const ne=(O=G.element)==null?void 0:O.ownerDocument;if(!ne||ne===document)continue;const Ie=ne.getElementById("dv-popout-window");if(!(Ie instanceof HTMLElement))continue;let _e=null,Ae=ne.title||"ADHDev",Oe="Popout workspace";const De=G.activePanel;if(De)if(_e=De.id,Zt(De.id)){const je=((F=De.params)==null?void 0:F.routeId)||De.id.slice(7),Be=Ot([...ie.values()],je);Ae=kc(Be),Oe=Be!=null&&Be.machineName?`Remote view · ${Be.machineName}`:"Remote view"}else{const je=ie.get(De.id);Ae=je?lt(je):De.title||De.id,Oe=je?ps(je):"Dockview panel"}ne.title=`${Ae} — ADHDev`;let Qe=ne.getElementById("adhdev-popout-header");Qe instanceof HTMLElement||(Qe=ne.createElement("div"),Qe.id="adhdev-popout-header",ne.body.appendChild(Qe)),Qe.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(";")),Qe.innerHTML=`
45
45
  <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
46
46
  <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
@@ -71,9 +71,9 @@ This will disconnect CDP and optionally kill the process.`))try{const D=await r(
71
71
 
72
72
  `)}function Lx({daemonLogs:e,trace:s,webEvents:r,daemonLogKind:n,daemonFetchError:a,traceFetchError:i,searchQuery:c}){const l=yl(e,c),u=vl(s,c),p=wl(r,c),m=l.filter(w=>w.level==="warn"||w.level==="error").map(w=>({source:"daemon",level:w.level,timestamp:w.timestamp,label:"daemon",detail:w.message})),f=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:hr(w.payload,320)||`${w.category}.${w.stage}`})),g=[...m,...f].sort((w,A)=>A.timestamp-w.timestamp);return{daemonCount:l.length,traceCount:u.length,webCount:p.length,issueCount:g.length,latestIssue:g[0]||null,hasAnyData:n==="text"||l.length>0||u.length>0||p.length>0,hasBlockingError:!!(a||i)}}function yi(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function vi(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 Yn(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 _x({machineId:e,sendDaemonCommand:s}){var ye,K;const[r,n]=o.useState([]),[a,i]=o.useState("empty"),[c,l]=o.useState(""),[u,p]=o.useState([]),[m,f]=o.useState([]),[g,w]=o.useState(0),[A,d]=o.useState(0),[b,y]=o.useState(null),[h,N]=o.useState(!0),[_,k]=o.useState("info"),[I,j]=o.useState("info"),[v,x]=o.useState("all"),[E,T]=o.useState(""),[L,M]=o.useState(!0),[W,U]=o.useState(!0),[C,R]=o.useState(""),[B,S]=o.useState(""),[D,Y]=o.useState(0),[q,H]=o.useState({daemon:!0,trace:!1,web:!1}),re=o.useRef(null),ie=o.useRef(!1),Se=o.useMemo(()=>Nx(u,v),[u,v]),X=o.useMemo(()=>yl(r,E),[r,E]),fe=o.useMemo(()=>Ax(c,E),[c,E]),we=o.useMemo(()=>vl(Se,E),[Se,E]),ce=o.useMemo(()=>wl(m,E),[m,E]),he=o.useMemo(()=>I==="issues"?X.filter(V=>V.level==="warn"||V.level==="error"):I==="info"?X.filter(V=>V.level!=="debug"):X,[X,I]),de=o.useMemo(()=>I==="all"?fe:[],[fe,I]),z=o.useMemo(()=>I==="issues"?we.filter(V=>V.level==="warn"||V.level==="error"):I==="info"?we.filter(V=>V.level!=="debug"):we,[we,I]),ge=o.useMemo(()=>I==="issues"?[]:ce,[ce,I]),ae=o.useMemo(()=>Mx({daemonLogs:X,daemonRawLines:fe,trace:we,webEvents:ce}),[X,fe,we,ce]),oe=o.useMemo(()=>Lx({daemonLogs:r,trace:Se,webEvents:m,daemonLogKind:a,daemonFetchError:C,traceFetchError:B,searchQuery:E}),[C,a,r,Se,E,B,m]),ee=o.useCallback(async()=>{if(!e)return;const[V,ve]=await Promise.allSettled([s(e,"get_logs",{count:200,minLevel:_,since:g}),s(e,"get_debug_trace",Sx({count:120,since:A,category:v}))]);if(V.status==="fulfilled"){const xe=V.value,Q=(xe==null?void 0:xe.result)||xe,Me=Ix(Q);if(M(!1),R((xe==null?void 0:xe.success)===!1?String((xe==null?void 0:xe.error)||"Could not load daemon logs"):""),i(Me.kind),l(Me.rawText),Me.entries.length>0){n(Pe=>(g>0?[...Pe,...Me.entries]:Me.entries).slice(-300));const We=Me.entries.reduce((Pe,Ke)=>Math.max(Pe,Number(Ke.timestamp||0)),g);We>g&&w(We)}else Me.kind!=="structured"&&g===0&&n([])}else M(!1),R(V.reason instanceof Error?V.reason.message:"Could not load daemon logs");if(ve.status==="fulfilled"){const xe=ve.value,Q=(xe==null?void 0:xe.result)||xe;if((xe==null?void 0:xe.success)===!1)S(String((xe==null?void 0:xe.error)||"Could not load daemon trace"));else if(Array.isArray(Q==null?void 0:Q.trace)){S(""),p(Q.trace.slice(-120));const Me=Q.trace.reduce((We,Pe)=>Math.max(We,Number(Pe.ts||0)),A);Me>A&&d(Me)}else S(""),p([]);U(!1)}else U(!1),S(ve.reason instanceof Error?ve.reason.message:"Could not load daemon trace");f(Ds.list({limit:120})),y(Date.now())},[g,A,_,e,s,v]);o.useEffect(()=>{if(!e||(ee(),!h))return;const V=setInterval(()=>{ee()},3e3);return()=>clearInterval(V)},[h,ee,e,D]),o.useEffect(()=>{if(h&&(he.length>0||de.length>0||z.length>0||ge.length>0)){const V=ie.current?"smooth":"instant";setTimeout(()=>{var ve;(ve=re.current)==null||ve.scrollIntoView({behavior:V}),ie.current=!0},50)}},[he.length,de.length,z.length,ge.length,h]),o.useEffect(()=>{p([]),d(0),U(!0)},[v]);const ue=((ye=oe.latestIssue)==null?void 0:ye.level)==="error"?"danger":((K=oe.latestIssue)==null?void 0:K.level)==="warn"?"warning":"good",se=C||B?"danger":h?"good":"neutral",ke=o.useCallback(async()=>{var ve;const V=Tx({daemonLogs:he,daemonRawLines:de,trace:z,webEvents:ge});if(!V.trim()){st.showToast("복사할 visible logs가 없습니다.","info");return}try{await((ve=navigator.clipboard)==null?void 0:ve.writeText(V)),st.showToast("Visible logs를 클립보드에 복사했습니다.","success")}catch(xe){st.showToast(xe instanceof Error?xe.message:"Could not copy visible logs","warning")}},[he,de,z,ge]);return t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"Level"}),["debug","info","warn","error"].map(V=>t.jsx("button",{onClick:()=>{k(V),n([]),l(""),i("empty"),w(0),M(!0)},className:`machine-btn text-[10px] px-2 py-0.5 ${_===V?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:V.toUpperCase()},V)),t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider ml-3 mr-1",children:"Trace"}),kx.map(V=>t.jsx("button",{onClick:()=>x(V.value),className:`machine-btn text-[10px] px-2 py-0.5 ${v===V.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:V.label},V.value))]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${ae.info})`},{id:"issues",label:`Issues (${ae.issues})`},{id:"all",label:`All (${ae.all})`}].map(V=>t.jsx("button",{type:"button",onClick:()=>j(V.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${I===V.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:V.label},V.id))}),t.jsx("input",{value:E,onChange:V=>T(V.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"}),t.jsx("button",{onClick:()=>{ke()},className:"machine-btn",children:"Copy visible"}),t.jsx("button",{onClick:()=>N(V=>!V),className:`machine-btn ${h?"text-green-500 border-green-500/30":""}`,children:h?"⏸ Pause":"▶ Resume"}),t.jsx("button",{onClick:()=>Y(V=>V+1),className:"machine-btn",children:"↻ Refresh"}),t.jsx("button",{onClick:()=>{n([]),l(""),i("empty"),p([]),f([]),w(0),d(0),y(null),R(""),S(""),M(!0),U(!0),Ds.clear()},className:"machine-btn",children:"Clear"})]})]}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[t.jsxs("div",{className:`rounded-xl border p-3 ${Yn(oe.issueCount>0?"warning":"good")}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Visible signals"}),t.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:["daemon ",he.length+de.length," · trace ",z.length," · web ",ge.length]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:E.trim()?`Filtered by “${E.trim()}”`:"Showing the latest buffered entries"})]}),t.jsxs("div",{className:`rounded-xl border p-3 ${Yn(ue)}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Attention needed"}),oe.latestIssue?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[oe.latestIssue.source," · ",oe.latestIssue.label]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:oe.latestIssue.detail}),t.jsxs("div",{className:"text-[10px] text-text-muted mt-2",children:[oe.issueCount," warn/error signal(s) · ",yi(oe.latestIssue.timestamp)]})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No recent warn/error signal"}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use search or lower the log level if you need more context."})]})]}),t.jsxs("div",{className:`rounded-xl border p-3 ${Yn(se)}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Fetch status"}),t.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:C||B?"Needs attention":h?"Live polling every 3s":"Paused"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",yi(b)]}),(C||B)&&t.jsxs("div",{className:"text-[11px] text-red-300 mt-2 space-y-1",children:[C&&t.jsxs("div",{children:["Daemon logs: ",C]}),B&&t.jsxs("div",{children:["Daemon trace: ",B]})]})]})]}),t.jsxs("div",{className:"grid gap-3",children:[t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>H(V=>({...V,daemon:!V.daemon})),children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Daemon logs"}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:a==="text"?`${de.length} visible raw line(s) from file fallback`:`${he.length} visible structured line(s)`})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:q.daemon?"Hide":"Show"})]}),q.daemon&&t.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:[L&&!oe.hasAnyData&&!C&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!L&&C&&a==="empty"&&t.jsx("div",{className:"p-6 text-center text-red-300",children:C}),!L&&a==="empty"&&!C&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),a==="text"&&de.length===0&&c&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:I==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),a==="structured"&&he.length===0&&r.length>0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),a==="text"&&de.map((V,ve)=>t.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:V},`raw-${ve}`)),a!=="text"&&he.map((V,ve)=>t.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${vi(V.level)}`,children:[t.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(V.timestamp).toLocaleTimeString()}),t.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:V.level==="error"?"ERR":V.level==="warn"?"WRN":V.level==="debug"?"DBG":"INF"}),t.jsx("span",{className:"break-words",children:V.message})]},`log-${ve}`))]})]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>H(V=>({...V,trace:!V.trace})),children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Structured daemon trace",v==="session_host"?" · session_host only":""]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[z.length," visible trace event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:q.trace?"Hide":"Show"})]}),q.trace&&t.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:[W&&z.length===0&&!B&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!W&&B&&z.length===0&&t.jsx("div",{className:"p-6 text-center text-red-300",children:B}),!W&&z.length===0&&!B&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:E.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."}),z.map(V=>t.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${vi(V.level)}`,children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:new Date(V.ts).toLocaleTimeString()}),t.jsx("span",{children:V.level.toUpperCase()}),t.jsxs("span",{children:[V.category,".",V.stage]}),V.interactionId&&t.jsxs("span",{children:["ix=",V.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:hr(V.payload,360)||"No payload"})]},V.id))]})]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>H(V=>({...V,web:!V.web})),children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Browser debug events"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[ge.length," visible browser event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:q.web?"Hide":"Show"})]}),q.web&&t.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:[ge.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:E.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),ge.map(V=>t.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:new Date(V.ts).toLocaleTimeString()}),t.jsx("span",{children:V.kind}),V.topic&&t.jsxs("span",{children:["topic=",V.topic]}),V.interactionId&&t.jsxs("span",{children:["ix=",V.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:hr(V.payload,360)||"No payload"})]},V.id))]})]})]}),t.jsx("div",{ref:re})]})}function Xn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Qn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function wi(e){if(!e)return"unknown";const s=Date.now()-e,r=Math.max(0,Math.round(s/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 Rx(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Px(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 Dx(e){var r;const s=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}`;s.set(i,(s.get(i)||0)+1)}return Array.from(s.values()).filter(n=>n>1).length}function Ex({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,u]=o.useState(!1),p=Wc(e,{enabled:!!e,includeSessions:!0,limit:12,intervalMs:8e3}),m=p.diagnostics,f=p.loading,g=p.applyDiagnostics,w=o.useMemo(()=>Fh({diagnostics:m,loading:f,refreshing:l,error:n}),[m,f,l,n]),A=o.useMemo(()=>new Map(s.map(T=>[T.sessionId||T.id,T])),[s]),d=o.useCallback(async()=>{if(e){u(!0);try{const T=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:12}),L=Xn(T);if(!(L!=null&&L.success))throw new Error((L==null?void 0:L.error)||"Could not load hosted runtime diagnostics");g(L.diagnostics||L.result||null),a("")}catch(T){const L=T instanceof Error?T.message:"Could not load hosted runtime diagnostics";a(L)}finally{u(!1)}}},[g,e,r]);o.useEffect(()=>{!e||m||f||l||d()},[m,f,e,d,l]);const b=o.useCallback(async(T,L)=>{const M=`${T}:${L.sessionId}`;if(!(T==="session_host_stop_session"&&!window.confirm(`Stop ${L.displayName}?
73
73
  This will terminate the hosted runtime.`))){c(M);try{const W=await r(e,T,{sessionId:L.sessionId}),U=Xn(W);if(!(U!=null&&U.success))throw new Error((U==null?void 0:U.error)||"Session host action failed");const C=T==="session_host_resume_session"?"resumed":T==="session_host_restart_session"?"restarted":"stopped";st.showToast(`Session host ${C}: ${L.displayName}`,"success"),await d()}catch(W){const U=W instanceof Error?W.message:"Session host action failed";st.showToast(U,"warning"),a(U)}finally{c(W=>W===M?null:W)}}},[e,d,r]),y=o.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
74
- The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){c("session_host_prune_duplicate_sessions");try{const L=await r(e,"session_host_prune_duplicate_sessions",{}),M=Xn(L);if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Duplicate prune failed");const W=M.result||{},U=Array.isArray(W.prunedSessionIds)?W.prunedSessionIds.length:0,C=typeof W.duplicateGroupCount=="number"?W.duplicateGroupCount:0;st.showToast(`Pruned ${U} duplicate runtime(s) across ${C} group(s)`,"success"),await d()}catch(L){const M=L instanceof Error?L.message:"Duplicate prune failed";st.showToast(M,"warning"),a(M)}finally{c(L=>L==="session_host_prune_duplicate_sessions"?null:L)}}},[e,d,r]),h=o.useMemo(()=>[...(m==null?void 0:m.sessions)||[]].sort((T,L)=>(L.lastActivityAt||0)-(T.lastActivityAt||0)),[m==null?void 0:m.sessions]),N=o.useMemo(()=>m!=null&&m.liveRuntimes||m!=null&&m.recoverySnapshots||m!=null&&m.inactiveRecords?{liveRuntimes:(m==null?void 0:m.liveRuntimes)||[],recoverySnapshots:(m==null?void 0:m.recoverySnapshots)||[],inactiveRecords:(m==null?void 0:m.inactiveRecords)||[]}:hl(h),[m==null?void 0:m.inactiveRecords,m==null?void 0:m.liveRuntimes,m==null?void 0:m.recoverySnapshots,h]),_=N.liveRuntimes,k=N.recoverySnapshots,I=N.inactiveRecords,j=o.useMemo(()=>Dx(_),[_]),v=o.useMemo(()=>[...(m==null?void 0:m.recentTransitions)||[]].slice(-6).reverse(),[m==null?void 0:m.recentTransitions]),x=o.useMemo(()=>[...(m==null?void 0:m.recentLogs)||[]].reverse().find(T=>T.level==="warn"||T.level==="error")||null,[m==null?void 0:m.recentLogs]),E=(T,L)=>{var Y;const M=i===`session_host_resume_session:${T.sessionId}`,W=i===`session_host_restart_session:${T.sessionId}`,U=i===`session_host_stop_session:${T.sessionId}`,C=no(T.meta),R=A.get(T.sessionId),B=T.attachedClients.length===1?"1 client":`${T.attachedClients.length} clients`,S=L==="recovery"?"Recover":"Resume",D=xl(L);return t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:T.displayName||(R==null?void 0:R.cliName)||T.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Px(T.lifecycle)}`,children:T.lifecycle}),C&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:C})]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:"text-text-primary/90",children:T.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||T.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:T.runtimeKey}),T.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",T.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((Y=T.writeOwner)==null?void 0:Y.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Rx(T.writeOwner)}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[t.jsx(ka,{size:11})," ",B]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",wi(T.lastActivityAt)]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-sky-200",children:["Next: ",D]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[L==="recovery"&&(T.lifecycle==="interrupted"||T.lifecycle==="failed"||T.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{b("session_host_resume_session",T)},children:M?`${S}ing…`:S}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{b("session_host_restart_session",T)},children:W?"Restarting…":"Restart"}),L==="live"&&(T.lifecycle==="running"||T.lifecycle==="starting"||T.lifecycle==="interrupted")&&t.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:()=>{b("session_host_stop_session",T)},children:U?"Stopping…":"Stop"})]})]})},T.sessionId)};return t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[t.jsx(Xt,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:tp()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[j>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{y()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${j})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${w.toneClass}`,children:w.label}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{d()},disabled:f||l,children:[t.jsx(Fs,{size:13}),f||l?"Refreshing…":"Refresh"]})]})]}),n&&!m&&t.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:t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(vs,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),t.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),m&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:m.runtimeCount})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:k.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:m.recentRequests.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),t.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:wi(m.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Qn(m.hostStartedAt)})]})]}),x&&t.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:[t.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[t.jsx(vs,{size:13})," Latest host warning"]}),t.jsx("div",{className:"text-text-primary leading-relaxed",children:x.message}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Qn(x.timestamp),x.sessionId?` · ${x.sessionId}`:""]})]}),t.jsxs("div",{className:"mb-4 space-y-4",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[t.jsx(un,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ps("live")}),_.length===0?t.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."}):t.jsx("div",{className:"space-y-2",children:_.map(T=>E(T,"live"))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[t.jsx(Xt,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ps("recovery")}),k.length===0?t.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."}):t.jsx("div",{className:"space-y-2",children:k.map(T=>E(T,"recovery"))})]}),I.length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ps("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:I.map(T=>E(T,"inactive"))})]})]}),t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),v.length===0?t.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."}):t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:v.map(T=>{var M;const L=h.find(W=>W.sessionId===T.sessionId);return t.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-text-primary font-medium",children:(L==null?void 0:L.displayName)||((M=A.get(T.sessionId))==null?void 0:M.cliName)||T.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[T.action,T.lifecycle?` · ${T.lifecycle}`:"",T.detail?` · ${T.detail}`:"",T.error?` · ${T.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${T.success===!1?"text-red-300":"text-text-secondary"}`,children:Qn(T.timestamp)})]},`${T.sessionId}:${T.timestamp}:${T.action}`)})})]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",t.jsx("span",{className:"font-mono text-text-primary",children:m.endpoint||"unknown"}),n?t.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function $x({machine:e,launchPick:s,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return t.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:t.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:[t.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),t.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."}),t.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?t.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=>t.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:s.cliType,workspaceId:i.id,argsStr:s.argsStr,model:s.model})},children:[t.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),t.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),n({cliType:s.cliType,useDefaultWorkspace:!0,argsStr:s.argsStr,model:s.model})},children:"Default workspace"}),t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{a(null),n({cliType:s.cliType,useHome:!0,argsStr:s.argsStr,model:s.model})},children:"Home directory"}),t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>a(null),children:"Cancel"})]})]})})}function Jn({icon:e,children:s}){return t.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,t.jsx("span",{children:s})]})}function Zn({children:e,className:s=""}){return t.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${s}`,children:e})}function Kx({machineEntry:e,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),u=r.slice(0,4),m=or(e,"0.8.83");return t.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&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Jn,{icon:t.jsx(Qt,{size:13}),children:"Current Chats"}),t.jsx(Zn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(f=>{const g=ia(f);return t.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(f),children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:lt(f)}),g>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:pn(g)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ks(f)})]},f.tabKey)})})})]}),u.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Jn,{icon:t.jsx(Ki,{size:13}),children:"Recent Launches"}),t.jsx(Zn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(f=>{const{metaText:g,updatedLabel:w}=el(f);return t.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(f),children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:f.label}),w&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:w})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:g})]},f.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Jn,{icon:t.jsx(vs,{size:13}),children:"Daemon Update"}),t.jsx(Zn,{className:"border-amber-500/20 bg-amber-500/5",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:m?"Daemon update required":"Version mismatch detected"}),t.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:m?"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."}),t.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:[t.jsx(Fs,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Bx(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const Wx={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 Fr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ea({category:e,machine:s,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:p}){const m=Us(),{handleLaunchIde:f,handleStopCli:g,handleRestartIde:w,handleStopIde:A,handleDetectIdes:d,launchingIde:b,launchingAgentType:y,addLog:h}=c,[N,_]=o.useState(null),k=o.useCallback($=>{$&&m(ns($))},[m]),I=Wx[e],j=e==="ide",v=e==="acp",x=o.useMemo(()=>n.filter($=>$.category===e&&(e==="ide"||$.installed!==!1)),[e,n]),E=o.useMemo(()=>new Map(x.map($=>[$.type,$.displayName||$.type])),[x]),[T,L]=o.useState(""),[M,W]=o.useState(""),[U,C]=o.useState([]),[R,B]=o.useState(""),[S,D]=o.useState(""),[Y,q]=o.useState([]),[H,re]=o.useState(!1),[ie,Se]=o.useState(!1),[X,fe]=o.useState(""),[we,ce]=o.useState(!1),[he,de]=o.useState(()=>jt()),[z,ge]=o.useState(null),[ae,oe]=o.useState(p?"__custom__":u||s.defaultWorkspaceId||""),[ee,ue]=o.useState(p||""),[se,ke]=o.useState([]),[ye,K]=o.useState(!1),[V,ve]=o.useState(""),[xe,Q]=o.useState([]),[Me,We]=o.useState(!1),[Pe,Ke]=o.useState(""),Je=o.useRef(null),[Ge,ut]=o.useState(null),it=o.useRef("__home__"),[ht,ze]=o.useState("__home__"),[xt,bt]=o.useState(!1),ct=o.useRef(0),Te=se.filter($=>!a.some(Z=>Z.type===$&&Ct(Z.status)!=="stopped")),Xe=o.useRef({});o.useEffect(()=>{s.defaultWorkspaceId&&!ae&&oe(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),o.useEffect(()=>{if(p){oe("__custom__"),ue(p);return}u&&(oe(u),ue(""))},[u,p]),o.useEffect(()=>{j||T&&(x.some($=>$.type===T)||(L(""),D("")))},[x,j,T]);const Ue=(()=>{if(ae==="__custom__")return ee.trim();if(!ae)return"";const $=(s.workspaces||[]).find(Z=>Z.id===ae);return($==null?void 0:$.path)||""})(),Fe=o.useCallback($=>{const Z=Xe.current[$];Z&&(clearTimeout(Z),delete Xe.current[$]),ke(me=>me.includes($)?me.filter(Ee=>Ee!==$):me)},[]),kt=o.useRef(new Set),yt=o.useCallback(async $=>{if(l){We(!0),Ke("");try{const Z=await yn(l,r,$);ve(Z.path),ue(Z.path),Q(Z.directories)}catch(Z){Ke(Z instanceof Error?Z.message:"Could not load folder")}finally{We(!1)}}},[r,l]),wt=o.useCallback(()=>{if(!l)return;oe("__custom__"),K(!0);const $=a.map(me=>me.workspace),Z=gn(s.platform,bn(ee.trim(),Ue,p,$,s.defaultWorkspacePath,(s.workspaces||[]).map(me=>me.path)));yt(Z)},[ee,p,yt,s.defaultWorkspacePath,s.platform,s.workspaces,a,Ue,l]),St=o.useCallback($=>{const Z=String($.workspace||"").trim();if(!Z)return;const me=(s.workspaces||[]).find(Ee=>Fr(Ee.path)===Fr(Z));if(me){oe(me.id),ue("");return}oe("__custom__"),ue(Z)},[s.workspaces]),Ht=o.useCallback($=>{const Z=String($.workspace||"").trim();if(!Z)return{workspaceId:null,workspacePath:"",useHome:!0};const me=(s.workspaces||[]).find(Ee=>Fr(Ee.path)===Fr(Z));return me?{workspaceId:me.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:Z,useHome:!1}},[s.workspaces]),Mt=o.useCallback(async $=>{if(!l||!$||e!=="cli"){q([]),re(!1),Se(!1),fe("");return}const Z=ct.current+1;ct.current=Z,re(!0),fe("");try{const me=await l(r,"list_saved_sessions",{providerType:$,kind:"cli",limit:30});if(ct.current!==Z)return;const Ee=(me==null?void 0:me.result)??me;q(Array.isArray(Ee==null?void 0:Ee.sessions)?Ee.sessions:[])}catch(me){if(ct.current!==Z)return;q([]),fe(me instanceof Error?me.message:"Could not load saved sessions")}finally{ct.current===Z&&(re(!1),Se(!0))}},[e,r,l]),Tt=o.useMemo(()=>{if(e!=="cli"||!T)return null;const $=E.get(T)||T;return{routeId:r,daemonId:r,providerSessionId:S||void 0,transport:"pty",mode:"chat",agentName:$,agentType:T,status:"idle",title:$,messages:[],ideType:T,workspaceName:Ue,displayPrimary:$,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${T}`}},[e,r,E,Ue,S,T]),J=o.useCallback($=>{if(e==="ide"||!$){C([]);return}C(pl(r,$))},[e,r]);o.useEffect(()=>{ct.current+=1,D(""),J(T),Se(!1),q([]),fe(""),re(!1)},[e,J,Mt,T]);const Re=o.useMemo(()=>Y.find($=>$.providerSessionId===S)||null,[Y,S]);o.useEffect(()=>{if(!S)return;const $=Y.find(Z=>Z.providerSessionId===S);$!=null&&$.canResume||D("")},[Y,S]);const P=o.useCallback(($,Z)=>{Je.current=Z,it.current=$.selectedWorkspaceKey||"__home__",ze($.selectedWorkspaceKey||"__home__"),ut($)},[]),O=o.useCallback(()=>{Je.current&&(bt(!0),Je.current().finally(()=>{Je.current=null,bt(!1),ut(null)}))},[]),F=o.useCallback($=>{if(!$)return;ke(me=>me.includes($)?me:[...me,$]);const Z=Xe.current[$];Z&&clearTimeout(Z),Xe.current[$]=setTimeout(()=>{ke(me=>me.includes($)?me.filter(Ee=>Ee!==$):me),delete Xe.current[$]},2e4)},[]);o.useEffect(()=>{for(const Z of a)Ct(Z.status)!=="stopped"&&(se.includes(Z.type)&&!kt.current.has(Z.type)&&(kt.current.add(Z.type),h("info",`${E.get(Z.type)||Z.type} launched`,!0)),Fe(Z.type));const $=new Set(a.filter(Z=>Ct(Z.status)!=="stopped").map(Z=>Z.type));kt.current.forEach(Z=>{!se.includes(Z)&&!$.has(Z)&&kt.current.delete(Z)})},[h,Fe,a,se,E]),o.useEffect(()=>()=>{Object.values(Xe.current).forEach(clearTimeout),Xe.current={}},[]);const[G,ne]=o.useState({}),[Ie,_e]=o.useState(null);o.useEffect(()=>{if(!j||!r||!l)return;(async()=>{try{const Z=await l(r,"get_ide_extensions",{}),me=(Z==null?void 0:Z.result)||Z;me!=null&&me.success&&(me!=null&&me.ideExtensions)&&ne(me.ideExtensions)}catch{}})()},[j,r,l]);const Ae=$=>j?ot($.type):e==="cli"?$.cliName:$.acpName,Oe=j?s.detectedIdes||[]:[],De=o.useCallback(async $=>{const Z=($==null?void 0:$.type)||T,me=($==null?void 0:$.workspacePath)??Ue;if(j){await f(Z,me?{workspace:me}:void 0)&&F(Z);return}const Ee=await c.runLaunchCliCore({cliType:Z,dir:$!=null&&$.workspaceId?void 0:me||void 0,workspaceId:($==null?void 0:$.workspaceId)||void 0,useHome:($==null?void 0:$.useHome)||!($!=null&&$.workspaceId)&&!me,argsStr:($==null?void 0:$.argsStr)??(M||void 0),model:($==null?void 0:$.model)??(v&&R||void 0),resumeSessionId:($==null?void 0:$.resumeSessionId)||!v&&e==="cli"&&Z===T&&S||void 0});if(Ee.success||Ee.pending){const Le=($==null?void 0:$.argsStr)??M;!j&&(Le!=null&&Le.trim())&&(fl(r,Z,Le),J(Z)),F(Z),Ee.success&&Ee.sessionId&&k(Ee.sessionId)}},[c,f,v,j,M,R,J,F,r,k,Ue,S,T]),Qe=Nc(j?"ide":v?"acp":"cli",!j&&!v&&!!S),Ve=Cc(j?"ide":v?"acp":"cli",!j&&!v&&!!S),te=()=>{var Le;const $=j?ot(T):E.get(T)||T,Z=!j&&!v&&!!S,{options:me,selectedKey:Ee}=gs({machine:s,currentWorkspaceId:ae&&ae!=="__custom__"?ae:null,currentWorkspacePath:Ue});P({title:Z?Oa($):fs("start-fresh",$),description:Z?Ha():hs("start-fresh"),confirmLabel:Qe,busyLabel:Ve,workspaceOptions:me,selectedWorkspaceKey:Ee,details:[{label:"Mode",value:I.label},{label:"Provider",value:$},...!j&&e==="cli"&&S?[{label:"Resume",value:((Le=Y.find(Ne=>Ne.providerSessionId===S))==null?void 0:Le.title)||S}]:[],...!j&&M.trim()?[{label:"Arguments",value:M.trim()}]:[],...v&&R.trim()?[{label:"Model",value:R.trim()}]:[]]},async()=>{const Ne=me.find(et=>et.key===it.current);Ne!=null&&Ne.workspaceId?(oe(Ne.workspaceId),ue("")):Ne!=null&&Ne.workspacePath?(oe("__custom__"),ue(Ne.workspacePath)):(oe(""),ue("")),await De({workspaceId:(Ne==null?void 0:Ne.workspaceId)??null,workspacePath:(Ne==null?void 0:Ne.workspacePath)??"",useHome:!(Ne!=null&&Ne.workspaceId)&&!(Ne!=null&&Ne.workspacePath)})})},je=$=>{j?A($):g($.type,$.workspace,$.id)},Be=o.useCallback(async($,Z,me=!1)=>{if($.mode===Z){me&&$.sessionId&&k($.sessionId);return}if(!l||!$.sessionId){me&&$.sessionId&&k($.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:$.sessionId,cliType:$.type,mode:Z}),me&&k($.sessionId)}catch(Ee){const Le=Qa(Ee);Xa(Ee)?console.warn(Le?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Ee instanceof Error?Ee.message:String(Ee)):console.error("Failed to switch CLI view mode:",Ee)}},[r,k,l]),rt=t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:ae,onChange:$=>{const Z=$.target.value;if(oe(Z),Z==="__custom__"&&l){wt();return}Z!=="__custom__"&&ue("")},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:(s.workspaces||[]).length>0?t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(s.workspaces||[]).map($=>t.jsxs("option",{value:$.id,children:[$.id===s.defaultWorkspaceId?"⭐ ":"",hn($.path,$.label)]},$.id)),t.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]}):t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),t.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]})}),ae==="__custom__"&&(l?t.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:wt,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:ee,onChange:$=>ue($.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}))]}),t.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:ae==="__custom__"?Ue?t.jsx("span",{className:"font-mono truncate block",title:Ue,children:Ue}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":Ue?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:ae===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:Ue,children:Ue})]}):"No workspace selected. This launches in the home directory."})]});return t.jsxs("div",{children:[t.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${I.accent} relative overflow-hidden`,children:[t.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[t.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",I.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:j?Oe.length>0?Oe.map($=>{const Z=a.find(et=>(et.type||"").toLowerCase()===($.type||"").toLowerCase()&&Ct(et.status)!=="stopped"),me=$.running||!!Z,Ee=!!Z&&Z.cdpConnected,Le=se.includes($.type||$.id||""),Ne=T===($.type||"");return t.jsxs("button",{onClick:()=>{if(Ee&&Z){const et=Z.sessionId;et?m(ns(et),{state:{openRemoteForTabKey:et}}):m("/dashboard",{state:{openRemoteForTabKey:Z.id}});return}Le||L(et=>et===($.type||"")?"":$.type||"")},disabled:!!b||Le,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Ee?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Ne?"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:b&&b!==$.type?.4:1},children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i($.type)}),me&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Ee?"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"}`})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:$.name||ot($.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Ee?"text-green-400":Le?"text-orange-400":Ne?"text-accent-primary":"text-text-muted"}`,children:Ee?"Open Session":Le?"Starting...":Ne?"Configure":"Select"})]})]},$.type)}):t.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.",t.jsxs("button",{onClick:d,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:[t.jsx(Nd,{size:14})," Scan System"]})]}):x.length>0?x.map($=>{const Z=T===$.type,me=se.includes($.type),Le=!!a.find(Ne=>Ne.type===$.type&&Ct(Ne.status)!=="stopped");return t.jsxs("button",{onClick:()=>L(Ne=>Ne===$.type?"":$.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Z?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:$.icon}),Le&&t.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)]"})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:$.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${me?"text-orange-400":Z?"text-accent-primary":"text-text-muted"}`,children:me?"Starting...":Z?"Configure":"Select"})]})]},$.type)}):t.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.",t.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."})]})}),T&&(j?Oe.find($=>$.type===T):x.find($=>$.type===T))&&t.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:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[t.jsx("span",{children:"Launch Settings"}),t.jsx("span",{className:"text-accent-primary font-bold",children:j?ot(T):E.get(T)||T})]}),rt,!j&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!v&&e==="cli"&&t.jsx(gl,{busy:!!y||!!b||se.includes(T),savedSessionsLoading:H,savedSessionsError:X,selectedSession:Re,onRefresh:()=>void Mt(T),onOpenHistory:()=>{T&&(ce(!0),bl({hasLoadedInitialResults:ie,isLoading:H})&&Mt(T))},onClearSelection:()=>D("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[v&&t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),t.jsx("input",{type:"text",placeholder:"Leave empty for default",value:R,onChange:$=>B($.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"})]}),t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),t.jsx("input",{type:"text",placeholder:"Optional flags...",value:M,onChange:$=>W($.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"}),U.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:U.map($=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>W($),title:$,children:$},$))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:te,disabled:!!y||!!b||se.includes(T),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:y===T||b===T?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+se.filter($=>!a.some(Z=>Z.type===$&&Ct(Z.status)!=="stopped")).length,")"]}),a.length===0&&Te.length===0?t.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",I.plural," running"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Te.map($=>t.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:t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:i($)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:j?ot($):E.get($)||$}),t.jsx("div",{className:"text-[11px] text-text-muted",children:y===$?"Launching process...":"Waiting for process and session to register..."})]})]}),t.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 Z=j?$:null,me=!j&&!v?$:null,Ee=Ct($.status);return t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex justify-between items-center mb-2",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:i($.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Ae($),(Z==null?void 0:Z.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",Z.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[t.jsx("span",{children:$.workspace||"—"}),(me==null?void 0:me.mode)&&t.jsx("span",{className:me.mode==="chat"?"text-violet-400":"text-text-secondary",children:me.mode==="chat"?"Chat view":"Terminal view"})]}),me&&(me.runtimeKey||me.runtimeWriteOwner)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[me.runtimeKey&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),t.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",me.runtimeKey]}),t.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 Le;(Le=navigator.clipboard)==null||Le.writeText(`adhdev attach ${me.runtimeKey}`),_(me.runtimeKey||null),window.setTimeout(()=>{_(Ne=>Ne===me.runtimeKey?null:Ne)},1200)},children:N===me.runtimeKey?"Copied":"Copy"})]}),me.runtimeWriteOwner&&t.jsx("span",{style:{color:me.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:me.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Bx(me.runtimeWriteOwner)})]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Ee==="stopped"?"bg-red-500/[0.08] text-red-500":Ee==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Ee}),j&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const Le=$.sessionId;if(Le){m(ns(Le),{state:{openRemoteForTabKey:Le}});return}m("/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:t.jsx(Rt,{size:13})}),t.jsx("button",{onClick:()=>{const Le=$.workspace||"",{options:Ne,selectedKey:et}=gs({machine:s,currentWorkspacePath:Le});P({title:fs("restart-ide",ot($.type)),description:hs("restart-ide"),confirmLabel:Os("restart-ide"),busyLabel:Hs("restart-ide"),workspaceOptions:Ne,selectedWorkspaceKey:et,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:ot($.type)}]},async()=>{const $e=Ne.find(Jt=>Jt.key===it.current),mt=($e==null?void 0:$e.workspacePath)??"";if(mt&&mt!==Le){await De({type:$.type,workspacePath:mt});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:t.jsx(Fs,{size:14})})]}),v&&t.jsx("button",{onClick:()=>{const Le=$.sessionId;Le&&k(Le)},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:t.jsx(Qt,{size:14})}),me&&Ee!=="stopped"&&t.jsxs(t.Fragment,{children:[me.mode&&t.jsx(Ka,{mode:me.mode,onChange:Le=>void Be(me,Le,!1),compact:!0}),t.jsx("button",{onClick:()=>{const Le=$.sessionId;Le&&k(Le)},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:me.mode==="chat"?t.jsx(Qt,{size:14}):t.jsx(Rt,{size:13})})]}),Ee==="stopped"?t.jsx("button",{onClick:()=>{const Le=$.workspace||"",Ne=j?ot($.type):Ae($),{options:et,selectedKey:$e}=gs({machine:s,currentWorkspacePath:Le});P({title:fs("restart-stopped",Ne),description:hs("restart-stopped"),confirmLabel:Os("restart-stopped"),busyLabel:Hs("restart-stopped"),workspaceOptions:et,selectedWorkspaceKey:$e,details:[{label:"Mode",value:I.label},{label:"Provider",value:Ne}]},async()=>{const mt=et.find(Jt=>Jt.key===it.current);await De({type:$.type,workspaceId:(mt==null?void 0:mt.workspaceId)??null,workspacePath:(mt==null?void 0:mt.workspacePath)??"",useHome:!(mt!=null&&mt.workspaceId)&&!(mt!=null&&mt.workspacePath)})})},disabled:se.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:se.includes($.type)?"⏳":t.jsx(Na,{size:14})}):t.jsx("button",{onClick:()=>je($),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:t.jsx(At,{size:14})})]})]}),Z&&Z.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:Z.aiAgents.map(Le=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${qi(Le.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Le.name," · ",Ct(Le.status)]},Le.id))}),Z&&(G[Z.type]||[]).length>0&&l&&t.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[t.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:(G[Z.type]||[]).map(Le=>t.jsxs("button",{disabled:Ie===`${Z.type}.${Le.type}`,onClick:async()=>{const Ne=`${Z.type}.${Le.type}`;_e(Ne);try{await l(r,"set_ide_extension",{ideType:Z.type,extensionType:Le.type,enabled:!Le.enabled}),ne(et=>({...et,[Z.type]:(et[Z.type]||[]).map($e=>$e.type===Le.type?{...$e,enabled:!$e.enabled}:$e)}))}catch(et){console.error("Extension toggle failed:",et)}finally{_e(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 ${Le.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Le.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Le.name,t.jsx("span",{className:"text-[9px] font-normal",children:Le.enabled?"ON":"OFF"})]},Le.type))})]})]},$.id)})]}),ye&&l&&t.jsx(vn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:V,directories:xe,busy:Me,error:Pe,confirmLabel:"Use this folder",onClose:()=>K(!1),onNavigate:$=>{yt($)},onConfirm:$=>{ue($),oe("__custom__"),K(!1)}}),Ge&&t.jsx(so,{title:Ge.title,description:Ge.description,details:Ge.details,workspaceOptions:Ge.workspaceOptions,selectedWorkspaceKey:ht,onWorkspaceChange:$=>{it.current=$,ze($)},confirmLabel:Ge.confirmLabel,busyLabel:Ge.busyLabel,busy:xt,onConfirm:O,onCancel:()=>{Je.current=null,ut(null)}}),we&&Tt&&t.jsx(Ua,{activeConv:Tt,ides:[],isCreatingChat:!1,isRefreshingHistory:H,savedSessions:Y,isSavedSessionsLoading:H,isResumingSavedSessionId:z,savedHistoryFilters:he,onSavedHistoryFiltersChange:de,onClose:()=>ce(!1),onNewChat:()=>{D(""),ce(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Mt(T)},onResumeSavedSession:$=>{if(!$.canResume||z)return;const Z=Ht($);D($.providerSessionId),St($),ge($.providerSessionId),ce(!1),De({type:$.providerType,workspaceId:Z.workspaceId,workspacePath:Z.workspacePath,useHome:Z.useHome,resumeSessionId:$.providerSessionId}).finally(()=>{ge(me=>me===$.providerSessionId?null:me)})}})]})}const ji=[{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 Ox({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:u="ide",initialWorkspaceId:p,initialWorkspacePath:m,sendDaemonCommand:f}){var d;const[g,w]=o.useState(u);o.useEffect(()=>{w(u)},[u]);const A=o.useMemo(()=>({ide:n.length,cli:a.length,acp:i.length}),[n.length,a.length,i.length]);return t.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[t.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),t.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),t.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[t.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:ji.map(b=>t.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${g===b.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>w(b.id),children:[t.jsx("span",{children:b.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${g===b.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:A[b.id]})]},b.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(d=ji.find(b=>b.id===g))==null?void 0:d.helper})]}),g==="ide"&&t.jsx(ea,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m}),g==="cli"&&t.jsx(ea,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m}),g==="acp"&&t.jsx(ea,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m})]})}function Hx({onNicknameSynced:e}={}){var z,ge,ae,oe,ee,ue,se,ke,ye;const{id:s}=rd(),r=Us(),n=wa(),{sendCommand:a}=Pt(),i=yr(),c=bc(),l=c.ides||[],u=c.initialLoaded??!0,p=l.find(K=>K.id===s&&K.type==="adhdev-daemon"),m=l.some(K=>K.type==="adhdev-daemon"),[f,g]=o.useState("workspace"),[w,A]=o.useState("ide"),d=o.useRef(null),[b,y]=o.useState(null),h=o.useRef("__home__"),[N,_]=o.useState("__home__"),[k,I]=o.useState(!1),j=o.useRef(null);o.useEffect(()=>{!s||!p||!(!p.workspaces||!p.availableProviders||!p.detectedIdes||!p.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,p,s]),Vp(s&&f==="overview"?[s]:[],{enabled:f==="overview",intervalMs:15e3});const v=()=>{if(m){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},x=fx({machineId:s,registeredMachineId:(p==null?void 0:p.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:j});o.useEffect(()=>st.onToast(V=>{c.setToasts(xe=>{if(xe.some(We=>We.message===V.message&&V.timestamp-We.timestamp<3e3))return xe;const Me={id:V.id,message:V.message,type:V.type,timestamp:V.timestamp,targetKey:V.targetKey,actions:V.actions};return[...xe.slice(-4),Me]});const ve=V.duration||5e3;setTimeout(()=>c.setToasts(xe=>xe.filter(Q=>Q.id!==V.id)),ve)}),[c]);const E=(p==null?void 0:p.availableProviders)||[],T={};for(const K of E)T[K.type]=K.icon;const L=K=>T[K]||"",M=p?{id:p.id,hostname:Yi(p,{fallbackId:p.id}),platform:((z=p.machine)==null?void 0:z.platform)||"unknown",arch:((ge=p.machine)==null?void 0:ge.arch)||"",cpus:((ae=p.machine)==null?void 0:ae.cpus)||0,totalMem:((oe=p.machine)==null?void 0:oe.totalMem)||0,freeMem:(ee=p.machine)==null?void 0:ee.freeMem,availableMem:(ue=p.machine)==null?void 0:ue.availableMem,loadavg:(se=p.machine)==null?void 0:se.loadavg,uptime:(ke=p.machine)==null?void 0:ke.uptime,release:((ye=p.machine)==null?void 0:ye.release)||"",cdpConnected:!!p.cdpConnected,machineNickname:p.machineNickname||null,p2p:p.p2p?{screenshotActive:!1,...p.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:p.detectedIdes||[],workspaces:p.workspaces||[],defaultWorkspaceId:p.defaultWorkspaceId??p.activeWorkspaceId??null,defaultWorkspacePath:p.defaultWorkspacePath??p.activeWorkspacePath??null}:null,W=l.filter(K=>K.daemonId===s&&K.type!=="adhdev-daemon").filter(K=>!mr(K)&&!Ls(K)).map(K=>({id:K.id,sessionId:K.sessionId,type:K.type,version:K.version||"",instanceId:K.instanceId||"",status:K.status,workspace:K.workspace||null,terminals:K.terminals||0,aiAgents:yu(K.aiAgents||(K.agents||[]).map(V=>({id:V.name,name:V.name,status:V.status,version:V.version}))),activeChat:K.activeChat||null,chats:K.chats||[],childSessions:K.childSessions||[],cdpConnected:K.cdpConnected||!1,daemonId:s})),U=l.filter(K=>K.daemonId===s&&mr(K)).map(K=>({id:K.id,sessionId:K.sessionId,type:K.type,cliName:K.cliName||K.type,status:K.status,workspace:K.workspace||"",activeChat:K.activeChat||null,providerSessionId:K.providerSessionId,mode:K.mode,runtimeKey:K.runtimeKey,runtimeDisplayName:K.runtimeDisplayName,runtimeWorkspaceLabel:K.runtimeWorkspaceLabel,runtimeWriteOwner:K.runtimeWriteOwner||null,runtimeAttachedClients:K.runtimeAttachedClients||[],daemonId:s})),C=l.filter(K=>K.daemonId===s&&Ls(K)).map(K=>({id:K.id,sessionId:K.sessionId,type:K.type,acpName:K.cliName||K.type,status:K.status,workspace:K.workspace||"",activeChat:K.activeChat||null,providerSessionId:K.providerSessionId,daemonId:s})),R=p?_t(p,{fallbackId:s}):"",B="workspace",S=n.state,D=S==null?void 0:S.initialMachineTab,Y=S==null?void 0:S.initialWorkspaceCategory,q=S==null?void 0:S.initialWorkspaceId,H=S==null?void 0:S.initialWorkspacePath,re=D==="ides"||D==="clis"||D==="acps"?"workspace":D||B,ie=D==="ides"?"ide":D==="clis"?"cli":D==="acps"?"acp":Y,Se=[...W.map(K=>{var V,ve,xe,Q,Me;return{id:`ide:${K.type}:${K.workspace||""}`,label:((V=K.activeChat)==null?void 0:V.title)||K.type,kind:"ide",providerType:K.type,subtitle:K.workspace||void 0,workspace:K.workspace||void 0,lastLaunchedAt:((Me=(Q=(xe=(ve=K.activeChat)==null?void 0:ve.messages)==null?void 0:xe.at)==null?void 0:Q.call(xe,-1))==null?void 0:Me.timestamp)||0}}),...U.map(K=>{var V,ve,xe,Q,Me;return{id:`cli:${K.type}:${K.workspace||""}`,label:((V=K.activeChat)==null?void 0:V.title)||K.cliName,kind:"cli",providerType:K.type,providerSessionId:K.providerSessionId,subtitle:K.workspace||void 0,workspace:K.workspace||void 0,lastLaunchedAt:((Me=(Q=(xe=(ve=K.activeChat)==null?void 0:ve.messages)==null?void 0:xe.at)==null?void 0:Q.call(xe,-1))==null?void 0:Me.timestamp)||0}}),...C.map(K=>{var V,ve,xe,Q,Me;return{id:`acp:${K.type}:${K.workspace||""}`,label:((V=K.activeChat)==null?void 0:V.title)||K.acpName,kind:"acp",providerType:K.type,providerSessionId:K.providerSessionId,subtitle:ws(K.summaryMetadata)||K.workspace||void 0,workspace:K.workspace||void 0,lastLaunchedAt:((Me=(Q=(xe=(ve=K.activeChat)==null?void 0:ve.messages)==null?void 0:xe.at)==null?void 0:Q.call(xe,-1))==null?void 0:Me.timestamp)||0}})].sort((K,V)=>(V.lastLaunchedAt||0)-(K.lastLaunchedAt||0)),X=((p==null?void 0:p.recentLaunches)||[]).length>0?((p==null?void 0:p.recentLaunches)||[]).map(K=>({id:K.id,label:K.title||K.providerName||K.providerType,kind:K.kind,providerType:K.providerType,providerSessionId:K.providerSessionId,subtitle:ws(K.summaryMetadata)||K.workspace||void 0,workspace:K.workspace,summaryMetadata:K.summaryMetadata,lastLaunchedAt:K.lastLaunchedAt})):Se,fe=o.useMemo(()=>{var V;const K=((V=c.connectionStates)==null?void 0:V[s||""])||void 0;return l.filter(ve=>ve.daemonId===s&&ve.type!=="adhdev-daemon").flatMap(ve=>Fa(ve,{},{connectionStates:s&&K?{[s]:K}:void 0,defaultConnectionState:K})).filter(ve=>!(ve.transport==="pty"&&ve.mode==="terminal")).sort((ve,xe)=>ia(xe)-ia(ve))},[l,c.connectionStates,s]),we=o.useCallback(K=>{const V=Pa(K);V&&r(ns(V))},[r]),ce=o.useCallback(()=>{d.current&&(I(!0),d.current().finally(()=>{d.current=null,I(!1),y(null)}))},[]),he=o.useCallback(K=>{if(!M)return;const{options:V,selectedKey:ve}=gs({machine:M,currentWorkspacePath:K.workspace}),xe=async()=>{A(K.kind),g("workspace")};d.current=async()=>{const Q=V.find(Pe=>Pe.key===h.current),Me=(Q==null?void 0:Q.workspacePath)??null,We=(Q==null?void 0:Q.workspaceId)??null;if(K.kind==="ide"&&K.providerType){await x.handleLaunchIde(K.providerType,Me?{workspace:Me}:void 0);return}if((K.kind==="cli"||K.kind==="acp")&&K.providerType){await x.runLaunchCliCore({cliType:K.providerType,dir:We?void 0:Me||"",workspaceId:We||void 0,model:K.kind==="acp"&&Qi(K.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:K.providerSessionId});return}await xe()},h.current=ve,_(ve),y({title:K.kind==="ide"?fs("restart-ide",K.label):K.providerSessionId?Oa(K.label):fs("start-fresh",K.label),description:K.kind==="ide"?hs("restart-ide"):K.providerSessionId?Ha():hs("start-fresh"),confirmLabel:K.kind==="ide"?Os("restart-ide"):K.providerSessionId?nn(!0):Os("start-fresh"),busyLabel:K.kind==="ide"?Hs("restart-ide"):K.providerSessionId?Ba(!0):Hs("start-fresh"),workspaceOptions:V,details:[{label:"Mode",value:K.kind.toUpperCase()},...K.providerType?[{label:"Provider",value:K.providerType}]:[]]})},[x,M]);if(o.useEffect(()=>{g(re)},[B,re,s]),o.useEffect(()=>{ie&&A(ie)},[ie,s]),!M)return u?t.jsxs("div",{className:"p-10 text-center text-text-muted",children:[t.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),t.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),t.jsx("button",{onClick:v,className:"machine-btn-back",children:"← Back"})]}):t.jsx("div",{className:"p-10 text-center text-text-muted",children:t.jsx("p",{children:"⏳ Loading machine..."})});const de=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Rt,{size:14})," Workspace"]}),count:W.length+U.length+C.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Xt,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(dn,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Cd,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(kd,{size:14})," Logs"]})}];return t.jsxs("div",{className:"flex flex-col h-full",children:[t.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:[t.jsx("div",{className:"flex items-center justify-between w-full",children:t.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[t.jsx("button",{onClick:v,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:"←"}),t.jsxs("div",{className:"flex flex-col min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[x.editingNickname?t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsx("input",{autoFocus:!0,value:x.nicknameInput,onChange:K=>x.setNicknameInput(K.target.value),onKeyDown:K=>{K.key==="Enter"&&x.handleSaveNickname(),K.key==="Escape"&&x.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]"}),t.jsx("button",{onClick:x.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"}),t.jsx("button",{onClick:()=>x.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"})]}):t.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{x.setEditingNickname(!0),x.setNicknameInput(M.machineNickname||"")},title:"Click to set nickname",children:R}),t.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"})]}),t.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:[t.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[M.platform," · ",M.arch]}),t.jsxs("span",{children:[M.cpus," cores"]}),(p==null?void 0:p.version)&&t.jsxs("span",{children:["v",p.version]}),M.p2p.available&&t.jsxs("span",{children:["P2P ",M.p2p.state==="connected"?"connected":M.p2p.state]}),M.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:M.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:de.map(K=>t.jsxs("button",{onClick:()=>g(K.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${f===K.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[K.label,K.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${f===K.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:K.count})]},K.id))})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:t.jsx("div",{className:"max-w-7xl mx-auto h-full",children:t.jsxs("div",{className:"h-full",children:[f==="workspace"&&t.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[t.jsx(Kx,{machineEntry:p,providers:E,recentLaunches:X,currentConversations:fe,onUpgradeDaemon:async()=>{try{await a(s,"daemon_upgrade",{})}catch{}},onOpenRecent:he,onOpenConversation:we}),t.jsx(Ox,{machine:M,machineId:s,providers:E,ideSessions:W,cliSessions:U,acpSessions:C,actions:x,getIcon:L,initialCategory:w,initialWorkspaceId:q,initialWorkspacePath:H,sendDaemonCommand:a})]}),f==="providers"&&t.jsx(jx,{machineId:s,providers:E,sendDaemonCommand:a}),f==="overview"&&t.jsx(hx,{machineId:s,machine:M,ideSessions:W,cliSessions:U,acpSessions:C,actions:x,sendDaemonCommand:a}),f==="session-host"&&t.jsx(Ex,{machineId:s,cliSessions:U,sendDaemonCommand:a}),f==="logs"&&t.jsx(_x,{machineId:s,sendDaemonCommand:a})]})})}),x.launchPick&&M&&t.jsx($x,{machine:M,launchPick:x.launchPick,actions:x}),b&&t.jsx(so,{title:b.title,description:b.description,details:b.details,workspaceOptions:b.workspaceOptions,selectedWorkspaceKey:N,onWorkspaceChange:K=>{h.current=K,_(K)},confirmLabel:b.confirmLabel,busyLabel:b.busyLabel,busy:k,onConfirm:ce,onCancel:()=>{d.current=null,y(null)}}),t.jsx(Ic,{toasts:c.toasts||[],onDismiss:K=>c.setToasts(V=>V.filter(ve=>ve.id!==K)),onClickToast:K=>{K.targetKey&&r(ns(K.targetKey))}}),t.jsx("style",{children:`
74
+ The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){c("session_host_prune_duplicate_sessions");try{const L=await r(e,"session_host_prune_duplicate_sessions",{}),M=Xn(L);if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Duplicate prune failed");const W=M.result||{},U=Array.isArray(W.prunedSessionIds)?W.prunedSessionIds.length:0,C=typeof W.duplicateGroupCount=="number"?W.duplicateGroupCount:0;st.showToast(`Pruned ${U} duplicate runtime(s) across ${C} group(s)`,"success"),await d()}catch(L){const M=L instanceof Error?L.message:"Duplicate prune failed";st.showToast(M,"warning"),a(M)}finally{c(L=>L==="session_host_prune_duplicate_sessions"?null:L)}}},[e,d,r]),h=o.useMemo(()=>[...(m==null?void 0:m.sessions)||[]].sort((T,L)=>(L.lastActivityAt||0)-(T.lastActivityAt||0)),[m==null?void 0:m.sessions]),N=o.useMemo(()=>m!=null&&m.liveRuntimes||m!=null&&m.recoverySnapshots||m!=null&&m.inactiveRecords?{liveRuntimes:(m==null?void 0:m.liveRuntimes)||[],recoverySnapshots:(m==null?void 0:m.recoverySnapshots)||[],inactiveRecords:(m==null?void 0:m.inactiveRecords)||[]}:hl(h),[m==null?void 0:m.inactiveRecords,m==null?void 0:m.liveRuntimes,m==null?void 0:m.recoverySnapshots,h]),_=N.liveRuntimes,k=N.recoverySnapshots,I=N.inactiveRecords,j=o.useMemo(()=>Dx(_),[_]),v=o.useMemo(()=>[...(m==null?void 0:m.recentTransitions)||[]].slice(-6).reverse(),[m==null?void 0:m.recentTransitions]),x=o.useMemo(()=>[...(m==null?void 0:m.recentLogs)||[]].reverse().find(T=>T.level==="warn"||T.level==="error")||null,[m==null?void 0:m.recentLogs]),E=(T,L)=>{var Y;const M=i===`session_host_resume_session:${T.sessionId}`,W=i===`session_host_restart_session:${T.sessionId}`,U=i===`session_host_stop_session:${T.sessionId}`,C=no(T.meta),R=A.get(T.sessionId),B=T.attachedClients.length===1?"1 client":`${T.attachedClients.length} clients`,S=L==="recovery"?"Recover":"Resume",D=xl(L);return t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:T.displayName||(R==null?void 0:R.cliName)||T.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Px(T.lifecycle)}`,children:T.lifecycle}),C&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:C})]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:"text-text-primary/90",children:T.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||T.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:T.runtimeKey}),T.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",T.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((Y=T.writeOwner)==null?void 0:Y.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Rx(T.writeOwner)}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[t.jsx(ka,{size:11})," ",B]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",wi(T.lastActivityAt)]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-sky-200",children:["Next: ",D]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[L==="recovery"&&(T.lifecycle==="interrupted"||T.lifecycle==="failed"||T.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{b("session_host_resume_session",T)},children:M?`${S}ing…`:S}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{b("session_host_restart_session",T)},children:W?"Restarting…":"Restart"}),L==="live"&&(T.lifecycle==="running"||T.lifecycle==="starting"||T.lifecycle==="interrupted")&&t.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:()=>{b("session_host_stop_session",T)},children:U?"Stopping…":"Stop"})]})]})},T.sessionId)};return t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[t.jsx(Xt,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:tp()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[j>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{y()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${j})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${w.toneClass}`,children:w.label}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{d()},disabled:f||l,children:[t.jsx(Fs,{size:13}),f||l?"Refreshing…":"Refresh"]})]})]}),n&&!m&&t.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:t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(vs,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),t.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),m&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:m.runtimeCount})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:k.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:m.recentRequests.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),t.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:wi(m.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Qn(m.hostStartedAt)})]})]}),x&&t.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:[t.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[t.jsx(vs,{size:13})," Latest host warning"]}),t.jsx("div",{className:"text-text-primary leading-relaxed",children:x.message}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Qn(x.timestamp),x.sessionId?` · ${x.sessionId}`:""]})]}),t.jsxs("div",{className:"mb-4 space-y-4",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[t.jsx(un,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ps("live")}),_.length===0?t.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."}):t.jsx("div",{className:"space-y-2",children:_.map(T=>E(T,"live"))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[t.jsx(Xt,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ps("recovery")}),k.length===0?t.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."}):t.jsx("div",{className:"space-y-2",children:k.map(T=>E(T,"recovery"))})]}),I.length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ps("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:I.map(T=>E(T,"inactive"))})]})]}),t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),v.length===0?t.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."}):t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:v.map(T=>{var M;const L=h.find(W=>W.sessionId===T.sessionId);return t.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-text-primary font-medium",children:(L==null?void 0:L.displayName)||((M=A.get(T.sessionId))==null?void 0:M.cliName)||T.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[T.action,T.lifecycle?` · ${T.lifecycle}`:"",T.detail?` · ${T.detail}`:"",T.error?` · ${T.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${T.success===!1?"text-red-300":"text-text-secondary"}`,children:Qn(T.timestamp)})]},`${T.sessionId}:${T.timestamp}:${T.action}`)})})]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",t.jsx("span",{className:"font-mono text-text-primary",children:m.endpoint||"unknown"}),n?t.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function $x({machine:e,launchPick:s,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return t.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:t.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:[t.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),t.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."}),t.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?t.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=>t.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:s.cliType,workspaceId:i.id,argsStr:s.argsStr,model:s.model})},children:[t.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),t.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),n({cliType:s.cliType,useDefaultWorkspace:!0,argsStr:s.argsStr,model:s.model})},children:"Default workspace"}),t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{a(null),n({cliType:s.cliType,useHome:!0,argsStr:s.argsStr,model:s.model})},children:"Home directory"}),t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>a(null),children:"Cancel"})]})]})})}function Jn({icon:e,children:s}){return t.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,t.jsx("span",{children:s})]})}function Zn({children:e,className:s=""}){return t.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${s}`,children:e})}function Kx({machineEntry:e,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),u=r.slice(0,4),m=or(e,"0.8.84");return t.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&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Jn,{icon:t.jsx(Qt,{size:13}),children:"Current Chats"}),t.jsx(Zn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(f=>{const g=ia(f);return t.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(f),children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:lt(f)}),g>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:pn(g)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ks(f)})]},f.tabKey)})})})]}),u.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Jn,{icon:t.jsx(Ki,{size:13}),children:"Recent Launches"}),t.jsx(Zn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(f=>{const{metaText:g,updatedLabel:w}=el(f);return t.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(f),children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:f.label}),w&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:w})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:g})]},f.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Jn,{icon:t.jsx(vs,{size:13}),children:"Daemon Update"}),t.jsx(Zn,{className:"border-amber-500/20 bg-amber-500/5",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:m?"Daemon update required":"Version mismatch detected"}),t.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:m?"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."}),t.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:[t.jsx(Fs,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Bx(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const Wx={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 Fr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ea({category:e,machine:s,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:p}){const m=Us(),{handleLaunchIde:f,handleStopCli:g,handleRestartIde:w,handleStopIde:A,handleDetectIdes:d,launchingIde:b,launchingAgentType:y,addLog:h}=c,[N,_]=o.useState(null),k=o.useCallback($=>{$&&m(ns($))},[m]),I=Wx[e],j=e==="ide",v=e==="acp",x=o.useMemo(()=>n.filter($=>$.category===e&&(e==="ide"||$.installed!==!1)),[e,n]),E=o.useMemo(()=>new Map(x.map($=>[$.type,$.displayName||$.type])),[x]),[T,L]=o.useState(""),[M,W]=o.useState(""),[U,C]=o.useState([]),[R,B]=o.useState(""),[S,D]=o.useState(""),[Y,q]=o.useState([]),[H,re]=o.useState(!1),[ie,Se]=o.useState(!1),[X,fe]=o.useState(""),[we,ce]=o.useState(!1),[he,de]=o.useState(()=>jt()),[z,ge]=o.useState(null),[ae,oe]=o.useState(p?"__custom__":u||s.defaultWorkspaceId||""),[ee,ue]=o.useState(p||""),[se,ke]=o.useState([]),[ye,K]=o.useState(!1),[V,ve]=o.useState(""),[xe,Q]=o.useState([]),[Me,We]=o.useState(!1),[Pe,Ke]=o.useState(""),Je=o.useRef(null),[Ge,ut]=o.useState(null),it=o.useRef("__home__"),[ht,ze]=o.useState("__home__"),[xt,bt]=o.useState(!1),ct=o.useRef(0),Te=se.filter($=>!a.some(Z=>Z.type===$&&Ct(Z.status)!=="stopped")),Xe=o.useRef({});o.useEffect(()=>{s.defaultWorkspaceId&&!ae&&oe(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),o.useEffect(()=>{if(p){oe("__custom__"),ue(p);return}u&&(oe(u),ue(""))},[u,p]),o.useEffect(()=>{j||T&&(x.some($=>$.type===T)||(L(""),D("")))},[x,j,T]);const Ue=(()=>{if(ae==="__custom__")return ee.trim();if(!ae)return"";const $=(s.workspaces||[]).find(Z=>Z.id===ae);return($==null?void 0:$.path)||""})(),Fe=o.useCallback($=>{const Z=Xe.current[$];Z&&(clearTimeout(Z),delete Xe.current[$]),ke(me=>me.includes($)?me.filter(Ee=>Ee!==$):me)},[]),kt=o.useRef(new Set),yt=o.useCallback(async $=>{if(l){We(!0),Ke("");try{const Z=await yn(l,r,$);ve(Z.path),ue(Z.path),Q(Z.directories)}catch(Z){Ke(Z instanceof Error?Z.message:"Could not load folder")}finally{We(!1)}}},[r,l]),wt=o.useCallback(()=>{if(!l)return;oe("__custom__"),K(!0);const $=a.map(me=>me.workspace),Z=gn(s.platform,bn(ee.trim(),Ue,p,$,s.defaultWorkspacePath,(s.workspaces||[]).map(me=>me.path)));yt(Z)},[ee,p,yt,s.defaultWorkspacePath,s.platform,s.workspaces,a,Ue,l]),St=o.useCallback($=>{const Z=String($.workspace||"").trim();if(!Z)return;const me=(s.workspaces||[]).find(Ee=>Fr(Ee.path)===Fr(Z));if(me){oe(me.id),ue("");return}oe("__custom__"),ue(Z)},[s.workspaces]),Ht=o.useCallback($=>{const Z=String($.workspace||"").trim();if(!Z)return{workspaceId:null,workspacePath:"",useHome:!0};const me=(s.workspaces||[]).find(Ee=>Fr(Ee.path)===Fr(Z));return me?{workspaceId:me.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:Z,useHome:!1}},[s.workspaces]),Mt=o.useCallback(async $=>{if(!l||!$||e!=="cli"){q([]),re(!1),Se(!1),fe("");return}const Z=ct.current+1;ct.current=Z,re(!0),fe("");try{const me=await l(r,"list_saved_sessions",{providerType:$,kind:"cli",limit:30});if(ct.current!==Z)return;const Ee=(me==null?void 0:me.result)??me;q(Array.isArray(Ee==null?void 0:Ee.sessions)?Ee.sessions:[])}catch(me){if(ct.current!==Z)return;q([]),fe(me instanceof Error?me.message:"Could not load saved sessions")}finally{ct.current===Z&&(re(!1),Se(!0))}},[e,r,l]),Tt=o.useMemo(()=>{if(e!=="cli"||!T)return null;const $=E.get(T)||T;return{routeId:r,daemonId:r,providerSessionId:S||void 0,transport:"pty",mode:"chat",agentName:$,agentType:T,status:"idle",title:$,messages:[],ideType:T,workspaceName:Ue,displayPrimary:$,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${T}`}},[e,r,E,Ue,S,T]),J=o.useCallback($=>{if(e==="ide"||!$){C([]);return}C(pl(r,$))},[e,r]);o.useEffect(()=>{ct.current+=1,D(""),J(T),Se(!1),q([]),fe(""),re(!1)},[e,J,Mt,T]);const Re=o.useMemo(()=>Y.find($=>$.providerSessionId===S)||null,[Y,S]);o.useEffect(()=>{if(!S)return;const $=Y.find(Z=>Z.providerSessionId===S);$!=null&&$.canResume||D("")},[Y,S]);const P=o.useCallback(($,Z)=>{Je.current=Z,it.current=$.selectedWorkspaceKey||"__home__",ze($.selectedWorkspaceKey||"__home__"),ut($)},[]),O=o.useCallback(()=>{Je.current&&(bt(!0),Je.current().finally(()=>{Je.current=null,bt(!1),ut(null)}))},[]),F=o.useCallback($=>{if(!$)return;ke(me=>me.includes($)?me:[...me,$]);const Z=Xe.current[$];Z&&clearTimeout(Z),Xe.current[$]=setTimeout(()=>{ke(me=>me.includes($)?me.filter(Ee=>Ee!==$):me),delete Xe.current[$]},2e4)},[]);o.useEffect(()=>{for(const Z of a)Ct(Z.status)!=="stopped"&&(se.includes(Z.type)&&!kt.current.has(Z.type)&&(kt.current.add(Z.type),h("info",`${E.get(Z.type)||Z.type} launched`,!0)),Fe(Z.type));const $=new Set(a.filter(Z=>Ct(Z.status)!=="stopped").map(Z=>Z.type));kt.current.forEach(Z=>{!se.includes(Z)&&!$.has(Z)&&kt.current.delete(Z)})},[h,Fe,a,se,E]),o.useEffect(()=>()=>{Object.values(Xe.current).forEach(clearTimeout),Xe.current={}},[]);const[G,ne]=o.useState({}),[Ie,_e]=o.useState(null);o.useEffect(()=>{if(!j||!r||!l)return;(async()=>{try{const Z=await l(r,"get_ide_extensions",{}),me=(Z==null?void 0:Z.result)||Z;me!=null&&me.success&&(me!=null&&me.ideExtensions)&&ne(me.ideExtensions)}catch{}})()},[j,r,l]);const Ae=$=>j?ot($.type):e==="cli"?$.cliName:$.acpName,Oe=j?s.detectedIdes||[]:[],De=o.useCallback(async $=>{const Z=($==null?void 0:$.type)||T,me=($==null?void 0:$.workspacePath)??Ue;if(j){await f(Z,me?{workspace:me}:void 0)&&F(Z);return}const Ee=await c.runLaunchCliCore({cliType:Z,dir:$!=null&&$.workspaceId?void 0:me||void 0,workspaceId:($==null?void 0:$.workspaceId)||void 0,useHome:($==null?void 0:$.useHome)||!($!=null&&$.workspaceId)&&!me,argsStr:($==null?void 0:$.argsStr)??(M||void 0),model:($==null?void 0:$.model)??(v&&R||void 0),resumeSessionId:($==null?void 0:$.resumeSessionId)||!v&&e==="cli"&&Z===T&&S||void 0});if(Ee.success||Ee.pending){const Le=($==null?void 0:$.argsStr)??M;!j&&(Le!=null&&Le.trim())&&(fl(r,Z,Le),J(Z)),F(Z),Ee.success&&Ee.sessionId&&k(Ee.sessionId)}},[c,f,v,j,M,R,J,F,r,k,Ue,S,T]),Qe=Nc(j?"ide":v?"acp":"cli",!j&&!v&&!!S),Ve=Cc(j?"ide":v?"acp":"cli",!j&&!v&&!!S),te=()=>{var Le;const $=j?ot(T):E.get(T)||T,Z=!j&&!v&&!!S,{options:me,selectedKey:Ee}=gs({machine:s,currentWorkspaceId:ae&&ae!=="__custom__"?ae:null,currentWorkspacePath:Ue});P({title:Z?Oa($):fs("start-fresh",$),description:Z?Ha():hs("start-fresh"),confirmLabel:Qe,busyLabel:Ve,workspaceOptions:me,selectedWorkspaceKey:Ee,details:[{label:"Mode",value:I.label},{label:"Provider",value:$},...!j&&e==="cli"&&S?[{label:"Resume",value:((Le=Y.find(Ne=>Ne.providerSessionId===S))==null?void 0:Le.title)||S}]:[],...!j&&M.trim()?[{label:"Arguments",value:M.trim()}]:[],...v&&R.trim()?[{label:"Model",value:R.trim()}]:[]]},async()=>{const Ne=me.find(et=>et.key===it.current);Ne!=null&&Ne.workspaceId?(oe(Ne.workspaceId),ue("")):Ne!=null&&Ne.workspacePath?(oe("__custom__"),ue(Ne.workspacePath)):(oe(""),ue("")),await De({workspaceId:(Ne==null?void 0:Ne.workspaceId)??null,workspacePath:(Ne==null?void 0:Ne.workspacePath)??"",useHome:!(Ne!=null&&Ne.workspaceId)&&!(Ne!=null&&Ne.workspacePath)})})},je=$=>{j?A($):g($.type,$.workspace,$.id)},Be=o.useCallback(async($,Z,me=!1)=>{if($.mode===Z){me&&$.sessionId&&k($.sessionId);return}if(!l||!$.sessionId){me&&$.sessionId&&k($.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:$.sessionId,cliType:$.type,mode:Z}),me&&k($.sessionId)}catch(Ee){const Le=Qa(Ee);Xa(Ee)?console.warn(Le?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Ee instanceof Error?Ee.message:String(Ee)):console.error("Failed to switch CLI view mode:",Ee)}},[r,k,l]),rt=t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:ae,onChange:$=>{const Z=$.target.value;if(oe(Z),Z==="__custom__"&&l){wt();return}Z!=="__custom__"&&ue("")},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:(s.workspaces||[]).length>0?t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(s.workspaces||[]).map($=>t.jsxs("option",{value:$.id,children:[$.id===s.defaultWorkspaceId?"⭐ ":"",hn($.path,$.label)]},$.id)),t.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]}):t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),t.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]})}),ae==="__custom__"&&(l?t.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:wt,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:ee,onChange:$=>ue($.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}))]}),t.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:ae==="__custom__"?Ue?t.jsx("span",{className:"font-mono truncate block",title:Ue,children:Ue}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":Ue?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:ae===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:Ue,children:Ue})]}):"No workspace selected. This launches in the home directory."})]});return t.jsxs("div",{children:[t.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${I.accent} relative overflow-hidden`,children:[t.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[t.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",I.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:j?Oe.length>0?Oe.map($=>{const Z=a.find(et=>(et.type||"").toLowerCase()===($.type||"").toLowerCase()&&Ct(et.status)!=="stopped"),me=$.running||!!Z,Ee=!!Z&&Z.cdpConnected,Le=se.includes($.type||$.id||""),Ne=T===($.type||"");return t.jsxs("button",{onClick:()=>{if(Ee&&Z){const et=Z.sessionId;et?m(ns(et),{state:{openRemoteForTabKey:et}}):m("/dashboard",{state:{openRemoteForTabKey:Z.id}});return}Le||L(et=>et===($.type||"")?"":$.type||"")},disabled:!!b||Le,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Ee?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Ne?"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:b&&b!==$.type?.4:1},children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i($.type)}),me&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Ee?"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"}`})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:$.name||ot($.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Ee?"text-green-400":Le?"text-orange-400":Ne?"text-accent-primary":"text-text-muted"}`,children:Ee?"Open Session":Le?"Starting...":Ne?"Configure":"Select"})]})]},$.type)}):t.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.",t.jsxs("button",{onClick:d,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:[t.jsx(Nd,{size:14})," Scan System"]})]}):x.length>0?x.map($=>{const Z=T===$.type,me=se.includes($.type),Le=!!a.find(Ne=>Ne.type===$.type&&Ct(Ne.status)!=="stopped");return t.jsxs("button",{onClick:()=>L(Ne=>Ne===$.type?"":$.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Z?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:$.icon}),Le&&t.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)]"})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:$.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${me?"text-orange-400":Z?"text-accent-primary":"text-text-muted"}`,children:me?"Starting...":Z?"Configure":"Select"})]})]},$.type)}):t.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.",t.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."})]})}),T&&(j?Oe.find($=>$.type===T):x.find($=>$.type===T))&&t.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:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[t.jsx("span",{children:"Launch Settings"}),t.jsx("span",{className:"text-accent-primary font-bold",children:j?ot(T):E.get(T)||T})]}),rt,!j&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!v&&e==="cli"&&t.jsx(gl,{busy:!!y||!!b||se.includes(T),savedSessionsLoading:H,savedSessionsError:X,selectedSession:Re,onRefresh:()=>void Mt(T),onOpenHistory:()=>{T&&(ce(!0),bl({hasLoadedInitialResults:ie,isLoading:H})&&Mt(T))},onClearSelection:()=>D("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[v&&t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),t.jsx("input",{type:"text",placeholder:"Leave empty for default",value:R,onChange:$=>B($.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"})]}),t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),t.jsx("input",{type:"text",placeholder:"Optional flags...",value:M,onChange:$=>W($.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"}),U.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:U.map($=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>W($),title:$,children:$},$))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:te,disabled:!!y||!!b||se.includes(T),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:y===T||b===T?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+se.filter($=>!a.some(Z=>Z.type===$&&Ct(Z.status)!=="stopped")).length,")"]}),a.length===0&&Te.length===0?t.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",I.plural," running"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Te.map($=>t.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:t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:i($)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:j?ot($):E.get($)||$}),t.jsx("div",{className:"text-[11px] text-text-muted",children:y===$?"Launching process...":"Waiting for process and session to register..."})]})]}),t.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 Z=j?$:null,me=!j&&!v?$:null,Ee=Ct($.status);return t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex justify-between items-center mb-2",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:i($.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Ae($),(Z==null?void 0:Z.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",Z.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[t.jsx("span",{children:$.workspace||"—"}),(me==null?void 0:me.mode)&&t.jsx("span",{className:me.mode==="chat"?"text-violet-400":"text-text-secondary",children:me.mode==="chat"?"Chat view":"Terminal view"})]}),me&&(me.runtimeKey||me.runtimeWriteOwner)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[me.runtimeKey&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),t.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",me.runtimeKey]}),t.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 Le;(Le=navigator.clipboard)==null||Le.writeText(`adhdev attach ${me.runtimeKey}`),_(me.runtimeKey||null),window.setTimeout(()=>{_(Ne=>Ne===me.runtimeKey?null:Ne)},1200)},children:N===me.runtimeKey?"Copied":"Copy"})]}),me.runtimeWriteOwner&&t.jsx("span",{style:{color:me.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:me.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Bx(me.runtimeWriteOwner)})]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Ee==="stopped"?"bg-red-500/[0.08] text-red-500":Ee==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Ee}),j&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const Le=$.sessionId;if(Le){m(ns(Le),{state:{openRemoteForTabKey:Le}});return}m("/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:t.jsx(Rt,{size:13})}),t.jsx("button",{onClick:()=>{const Le=$.workspace||"",{options:Ne,selectedKey:et}=gs({machine:s,currentWorkspacePath:Le});P({title:fs("restart-ide",ot($.type)),description:hs("restart-ide"),confirmLabel:Os("restart-ide"),busyLabel:Hs("restart-ide"),workspaceOptions:Ne,selectedWorkspaceKey:et,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:ot($.type)}]},async()=>{const $e=Ne.find(Jt=>Jt.key===it.current),mt=($e==null?void 0:$e.workspacePath)??"";if(mt&&mt!==Le){await De({type:$.type,workspacePath:mt});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:t.jsx(Fs,{size:14})})]}),v&&t.jsx("button",{onClick:()=>{const Le=$.sessionId;Le&&k(Le)},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:t.jsx(Qt,{size:14})}),me&&Ee!=="stopped"&&t.jsxs(t.Fragment,{children:[me.mode&&t.jsx(Ka,{mode:me.mode,onChange:Le=>void Be(me,Le,!1),compact:!0}),t.jsx("button",{onClick:()=>{const Le=$.sessionId;Le&&k(Le)},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:me.mode==="chat"?t.jsx(Qt,{size:14}):t.jsx(Rt,{size:13})})]}),Ee==="stopped"?t.jsx("button",{onClick:()=>{const Le=$.workspace||"",Ne=j?ot($.type):Ae($),{options:et,selectedKey:$e}=gs({machine:s,currentWorkspacePath:Le});P({title:fs("restart-stopped",Ne),description:hs("restart-stopped"),confirmLabel:Os("restart-stopped"),busyLabel:Hs("restart-stopped"),workspaceOptions:et,selectedWorkspaceKey:$e,details:[{label:"Mode",value:I.label},{label:"Provider",value:Ne}]},async()=>{const mt=et.find(Jt=>Jt.key===it.current);await De({type:$.type,workspaceId:(mt==null?void 0:mt.workspaceId)??null,workspacePath:(mt==null?void 0:mt.workspacePath)??"",useHome:!(mt!=null&&mt.workspaceId)&&!(mt!=null&&mt.workspacePath)})})},disabled:se.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:se.includes($.type)?"⏳":t.jsx(Na,{size:14})}):t.jsx("button",{onClick:()=>je($),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:t.jsx(At,{size:14})})]})]}),Z&&Z.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:Z.aiAgents.map(Le=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${qi(Le.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Le.name," · ",Ct(Le.status)]},Le.id))}),Z&&(G[Z.type]||[]).length>0&&l&&t.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[t.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:(G[Z.type]||[]).map(Le=>t.jsxs("button",{disabled:Ie===`${Z.type}.${Le.type}`,onClick:async()=>{const Ne=`${Z.type}.${Le.type}`;_e(Ne);try{await l(r,"set_ide_extension",{ideType:Z.type,extensionType:Le.type,enabled:!Le.enabled}),ne(et=>({...et,[Z.type]:(et[Z.type]||[]).map($e=>$e.type===Le.type?{...$e,enabled:!$e.enabled}:$e)}))}catch(et){console.error("Extension toggle failed:",et)}finally{_e(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 ${Le.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Le.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Le.name,t.jsx("span",{className:"text-[9px] font-normal",children:Le.enabled?"ON":"OFF"})]},Le.type))})]})]},$.id)})]}),ye&&l&&t.jsx(vn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:V,directories:xe,busy:Me,error:Pe,confirmLabel:"Use this folder",onClose:()=>K(!1),onNavigate:$=>{yt($)},onConfirm:$=>{ue($),oe("__custom__"),K(!1)}}),Ge&&t.jsx(so,{title:Ge.title,description:Ge.description,details:Ge.details,workspaceOptions:Ge.workspaceOptions,selectedWorkspaceKey:ht,onWorkspaceChange:$=>{it.current=$,ze($)},confirmLabel:Ge.confirmLabel,busyLabel:Ge.busyLabel,busy:xt,onConfirm:O,onCancel:()=>{Je.current=null,ut(null)}}),we&&Tt&&t.jsx(Ua,{activeConv:Tt,ides:[],isCreatingChat:!1,isRefreshingHistory:H,savedSessions:Y,isSavedSessionsLoading:H,isResumingSavedSessionId:z,savedHistoryFilters:he,onSavedHistoryFiltersChange:de,onClose:()=>ce(!1),onNewChat:()=>{D(""),ce(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Mt(T)},onResumeSavedSession:$=>{if(!$.canResume||z)return;const Z=Ht($);D($.providerSessionId),St($),ge($.providerSessionId),ce(!1),De({type:$.providerType,workspaceId:Z.workspaceId,workspacePath:Z.workspacePath,useHome:Z.useHome,resumeSessionId:$.providerSessionId}).finally(()=>{ge(me=>me===$.providerSessionId?null:me)})}})]})}const ji=[{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 Ox({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:u="ide",initialWorkspaceId:p,initialWorkspacePath:m,sendDaemonCommand:f}){var d;const[g,w]=o.useState(u);o.useEffect(()=>{w(u)},[u]);const A=o.useMemo(()=>({ide:n.length,cli:a.length,acp:i.length}),[n.length,a.length,i.length]);return t.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[t.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),t.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),t.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[t.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:ji.map(b=>t.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${g===b.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>w(b.id),children:[t.jsx("span",{children:b.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${g===b.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:A[b.id]})]},b.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(d=ji.find(b=>b.id===g))==null?void 0:d.helper})]}),g==="ide"&&t.jsx(ea,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m}),g==="cli"&&t.jsx(ea,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m}),g==="acp"&&t.jsx(ea,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m})]})}function Hx({onNicknameSynced:e}={}){var z,ge,ae,oe,ee,ue,se,ke,ye;const{id:s}=rd(),r=Us(),n=wa(),{sendCommand:a}=Pt(),i=yr(),c=bc(),l=c.ides||[],u=c.initialLoaded??!0,p=l.find(K=>K.id===s&&K.type==="adhdev-daemon"),m=l.some(K=>K.type==="adhdev-daemon"),[f,g]=o.useState("workspace"),[w,A]=o.useState("ide"),d=o.useRef(null),[b,y]=o.useState(null),h=o.useRef("__home__"),[N,_]=o.useState("__home__"),[k,I]=o.useState(!1),j=o.useRef(null);o.useEffect(()=>{!s||!p||!(!p.workspaces||!p.availableProviders||!p.detectedIdes||!p.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,p,s]),Vp(s&&f==="overview"?[s]:[],{enabled:f==="overview",intervalMs:15e3});const v=()=>{if(m){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},x=fx({machineId:s,registeredMachineId:(p==null?void 0:p.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:j});o.useEffect(()=>st.onToast(V=>{c.setToasts(xe=>{if(xe.some(We=>We.message===V.message&&V.timestamp-We.timestamp<3e3))return xe;const Me={id:V.id,message:V.message,type:V.type,timestamp:V.timestamp,targetKey:V.targetKey,actions:V.actions};return[...xe.slice(-4),Me]});const ve=V.duration||5e3;setTimeout(()=>c.setToasts(xe=>xe.filter(Q=>Q.id!==V.id)),ve)}),[c]);const E=(p==null?void 0:p.availableProviders)||[],T={};for(const K of E)T[K.type]=K.icon;const L=K=>T[K]||"",M=p?{id:p.id,hostname:Yi(p,{fallbackId:p.id}),platform:((z=p.machine)==null?void 0:z.platform)||"unknown",arch:((ge=p.machine)==null?void 0:ge.arch)||"",cpus:((ae=p.machine)==null?void 0:ae.cpus)||0,totalMem:((oe=p.machine)==null?void 0:oe.totalMem)||0,freeMem:(ee=p.machine)==null?void 0:ee.freeMem,availableMem:(ue=p.machine)==null?void 0:ue.availableMem,loadavg:(se=p.machine)==null?void 0:se.loadavg,uptime:(ke=p.machine)==null?void 0:ke.uptime,release:((ye=p.machine)==null?void 0:ye.release)||"",cdpConnected:!!p.cdpConnected,machineNickname:p.machineNickname||null,p2p:p.p2p?{screenshotActive:!1,...p.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:p.detectedIdes||[],workspaces:p.workspaces||[],defaultWorkspaceId:p.defaultWorkspaceId??p.activeWorkspaceId??null,defaultWorkspacePath:p.defaultWorkspacePath??p.activeWorkspacePath??null}:null,W=l.filter(K=>K.daemonId===s&&K.type!=="adhdev-daemon").filter(K=>!mr(K)&&!Ls(K)).map(K=>({id:K.id,sessionId:K.sessionId,type:K.type,version:K.version||"",instanceId:K.instanceId||"",status:K.status,workspace:K.workspace||null,terminals:K.terminals||0,aiAgents:yu(K.aiAgents||(K.agents||[]).map(V=>({id:V.name,name:V.name,status:V.status,version:V.version}))),activeChat:K.activeChat||null,chats:K.chats||[],childSessions:K.childSessions||[],cdpConnected:K.cdpConnected||!1,daemonId:s})),U=l.filter(K=>K.daemonId===s&&mr(K)).map(K=>({id:K.id,sessionId:K.sessionId,type:K.type,cliName:K.cliName||K.type,status:K.status,workspace:K.workspace||"",activeChat:K.activeChat||null,providerSessionId:K.providerSessionId,mode:K.mode,runtimeKey:K.runtimeKey,runtimeDisplayName:K.runtimeDisplayName,runtimeWorkspaceLabel:K.runtimeWorkspaceLabel,runtimeWriteOwner:K.runtimeWriteOwner||null,runtimeAttachedClients:K.runtimeAttachedClients||[],daemonId:s})),C=l.filter(K=>K.daemonId===s&&Ls(K)).map(K=>({id:K.id,sessionId:K.sessionId,type:K.type,acpName:K.cliName||K.type,status:K.status,workspace:K.workspace||"",activeChat:K.activeChat||null,providerSessionId:K.providerSessionId,daemonId:s})),R=p?_t(p,{fallbackId:s}):"",B="workspace",S=n.state,D=S==null?void 0:S.initialMachineTab,Y=S==null?void 0:S.initialWorkspaceCategory,q=S==null?void 0:S.initialWorkspaceId,H=S==null?void 0:S.initialWorkspacePath,re=D==="ides"||D==="clis"||D==="acps"?"workspace":D||B,ie=D==="ides"?"ide":D==="clis"?"cli":D==="acps"?"acp":Y,Se=[...W.map(K=>{var V,ve,xe,Q,Me;return{id:`ide:${K.type}:${K.workspace||""}`,label:((V=K.activeChat)==null?void 0:V.title)||K.type,kind:"ide",providerType:K.type,subtitle:K.workspace||void 0,workspace:K.workspace||void 0,lastLaunchedAt:((Me=(Q=(xe=(ve=K.activeChat)==null?void 0:ve.messages)==null?void 0:xe.at)==null?void 0:Q.call(xe,-1))==null?void 0:Me.timestamp)||0}}),...U.map(K=>{var V,ve,xe,Q,Me;return{id:`cli:${K.type}:${K.workspace||""}`,label:((V=K.activeChat)==null?void 0:V.title)||K.cliName,kind:"cli",providerType:K.type,providerSessionId:K.providerSessionId,subtitle:K.workspace||void 0,workspace:K.workspace||void 0,lastLaunchedAt:((Me=(Q=(xe=(ve=K.activeChat)==null?void 0:ve.messages)==null?void 0:xe.at)==null?void 0:Q.call(xe,-1))==null?void 0:Me.timestamp)||0}}),...C.map(K=>{var V,ve,xe,Q,Me;return{id:`acp:${K.type}:${K.workspace||""}`,label:((V=K.activeChat)==null?void 0:V.title)||K.acpName,kind:"acp",providerType:K.type,providerSessionId:K.providerSessionId,subtitle:ws(K.summaryMetadata)||K.workspace||void 0,workspace:K.workspace||void 0,lastLaunchedAt:((Me=(Q=(xe=(ve=K.activeChat)==null?void 0:ve.messages)==null?void 0:xe.at)==null?void 0:Q.call(xe,-1))==null?void 0:Me.timestamp)||0}})].sort((K,V)=>(V.lastLaunchedAt||0)-(K.lastLaunchedAt||0)),X=((p==null?void 0:p.recentLaunches)||[]).length>0?((p==null?void 0:p.recentLaunches)||[]).map(K=>({id:K.id,label:K.title||K.providerName||K.providerType,kind:K.kind,providerType:K.providerType,providerSessionId:K.providerSessionId,subtitle:ws(K.summaryMetadata)||K.workspace||void 0,workspace:K.workspace,summaryMetadata:K.summaryMetadata,lastLaunchedAt:K.lastLaunchedAt})):Se,fe=o.useMemo(()=>{var V;const K=((V=c.connectionStates)==null?void 0:V[s||""])||void 0;return l.filter(ve=>ve.daemonId===s&&ve.type!=="adhdev-daemon").flatMap(ve=>Fa(ve,{},{connectionStates:s&&K?{[s]:K}:void 0,defaultConnectionState:K})).filter(ve=>!(ve.transport==="pty"&&ve.mode==="terminal")).sort((ve,xe)=>ia(xe)-ia(ve))},[l,c.connectionStates,s]),we=o.useCallback(K=>{const V=Pa(K);V&&r(ns(V))},[r]),ce=o.useCallback(()=>{d.current&&(I(!0),d.current().finally(()=>{d.current=null,I(!1),y(null)}))},[]),he=o.useCallback(K=>{if(!M)return;const{options:V,selectedKey:ve}=gs({machine:M,currentWorkspacePath:K.workspace}),xe=async()=>{A(K.kind),g("workspace")};d.current=async()=>{const Q=V.find(Pe=>Pe.key===h.current),Me=(Q==null?void 0:Q.workspacePath)??null,We=(Q==null?void 0:Q.workspaceId)??null;if(K.kind==="ide"&&K.providerType){await x.handleLaunchIde(K.providerType,Me?{workspace:Me}:void 0);return}if((K.kind==="cli"||K.kind==="acp")&&K.providerType){await x.runLaunchCliCore({cliType:K.providerType,dir:We?void 0:Me||"",workspaceId:We||void 0,model:K.kind==="acp"&&Qi(K.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:K.providerSessionId});return}await xe()},h.current=ve,_(ve),y({title:K.kind==="ide"?fs("restart-ide",K.label):K.providerSessionId?Oa(K.label):fs("start-fresh",K.label),description:K.kind==="ide"?hs("restart-ide"):K.providerSessionId?Ha():hs("start-fresh"),confirmLabel:K.kind==="ide"?Os("restart-ide"):K.providerSessionId?nn(!0):Os("start-fresh"),busyLabel:K.kind==="ide"?Hs("restart-ide"):K.providerSessionId?Ba(!0):Hs("start-fresh"),workspaceOptions:V,details:[{label:"Mode",value:K.kind.toUpperCase()},...K.providerType?[{label:"Provider",value:K.providerType}]:[]]})},[x,M]);if(o.useEffect(()=>{g(re)},[B,re,s]),o.useEffect(()=>{ie&&A(ie)},[ie,s]),!M)return u?t.jsxs("div",{className:"p-10 text-center text-text-muted",children:[t.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),t.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),t.jsx("button",{onClick:v,className:"machine-btn-back",children:"← Back"})]}):t.jsx("div",{className:"p-10 text-center text-text-muted",children:t.jsx("p",{children:"⏳ Loading machine..."})});const de=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Rt,{size:14})," Workspace"]}),count:W.length+U.length+C.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Xt,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(dn,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Cd,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(kd,{size:14})," Logs"]})}];return t.jsxs("div",{className:"flex flex-col h-full",children:[t.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:[t.jsx("div",{className:"flex items-center justify-between w-full",children:t.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[t.jsx("button",{onClick:v,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:"←"}),t.jsxs("div",{className:"flex flex-col min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[x.editingNickname?t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsx("input",{autoFocus:!0,value:x.nicknameInput,onChange:K=>x.setNicknameInput(K.target.value),onKeyDown:K=>{K.key==="Enter"&&x.handleSaveNickname(),K.key==="Escape"&&x.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]"}),t.jsx("button",{onClick:x.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"}),t.jsx("button",{onClick:()=>x.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"})]}):t.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{x.setEditingNickname(!0),x.setNicknameInput(M.machineNickname||"")},title:"Click to set nickname",children:R}),t.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"})]}),t.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:[t.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[M.platform," · ",M.arch]}),t.jsxs("span",{children:[M.cpus," cores"]}),(p==null?void 0:p.version)&&t.jsxs("span",{children:["v",p.version]}),M.p2p.available&&t.jsxs("span",{children:["P2P ",M.p2p.state==="connected"?"connected":M.p2p.state]}),M.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:M.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:de.map(K=>t.jsxs("button",{onClick:()=>g(K.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${f===K.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[K.label,K.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${f===K.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:K.count})]},K.id))})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:t.jsx("div",{className:"max-w-7xl mx-auto h-full",children:t.jsxs("div",{className:"h-full",children:[f==="workspace"&&t.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[t.jsx(Kx,{machineEntry:p,providers:E,recentLaunches:X,currentConversations:fe,onUpgradeDaemon:async()=>{try{await a(s,"daemon_upgrade",{})}catch{}},onOpenRecent:he,onOpenConversation:we}),t.jsx(Ox,{machine:M,machineId:s,providers:E,ideSessions:W,cliSessions:U,acpSessions:C,actions:x,getIcon:L,initialCategory:w,initialWorkspaceId:q,initialWorkspacePath:H,sendDaemonCommand:a})]}),f==="providers"&&t.jsx(jx,{machineId:s,providers:E,sendDaemonCommand:a}),f==="overview"&&t.jsx(hx,{machineId:s,machine:M,ideSessions:W,cliSessions:U,acpSessions:C,actions:x,sendDaemonCommand:a}),f==="session-host"&&t.jsx(Ex,{machineId:s,cliSessions:U,sendDaemonCommand:a}),f==="logs"&&t.jsx(_x,{machineId:s,sendDaemonCommand:a})]})})}),x.launchPick&&M&&t.jsx($x,{machine:M,launchPick:x.launchPick,actions:x}),b&&t.jsx(so,{title:b.title,description:b.description,details:b.details,workspaceOptions:b.workspaceOptions,selectedWorkspaceKey:N,onWorkspaceChange:K=>{h.current=K,_(K)},confirmLabel:b.confirmLabel,busyLabel:b.busyLabel,busy:k,onConfirm:ce,onCancel:()=>{d.current=null,y(null)}}),t.jsx(Ic,{toasts:c.toasts||[],onDismiss:K=>c.setToasts(V=>V.filter(ve=>ve.id!==K)),onClickToast:K=>{K.targetKey&&r(ns(K.targetKey))}}),t.jsx("style",{children:`
75
75
  @keyframes toast-in {
76
76
  from { opacity: 0; transform: translateX(40px); }
77
77
  to { opacity: 1; transform: translateX(0); }
78
78
  }
79
- `})]})}function oo(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function Ux(e){if(typeof window>"u")return e;const s=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),r=oo();return r&&!s.searchParams.has("token")&&s.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?s.toString():`${s.pathname}${s.search}${s.hash}`}async function es(e,s){return await fetch(Ux(e),{credentials:"same-origin",...s})}function jl(){if(typeof window>"u")return;const e=new URL(window.location.href);e.searchParams.has("token")&&(e.searchParams.delete("token"),window.history.replaceState({},"",`${e.pathname}${e.search}${e.hash}`))}class Fx{constructor(){Ye(this,"adapters",new Map);Ye(this,"states",new Map);Ye(this,"runtimeListeners",new Map);Ye(this,"screenshotCallbacks",new Map);Ye(this,"statusCallbacks",new Set)}resolveDaemonId(s){if(this.adapters.has(s))return s;if(s.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(s,r){this.adapters.set(s,r),this.states.set(s,r.connectionState)}unregister(s){this.adapters.delete(s),this.states.delete(s)}setState(s,r){this.states.set(s,r)}retryConnection(s){}get(s){const r=this.resolveDaemonId(s);return r?this.adapters.get(r):void 0}getState(s){const r=this.resolveDaemonId(s);return r&&this.states.get(r)||"disconnected"}sendData(s,r){return!1}sendPtyInput(s,r,n){return!1}onScreenshot(s,r){return this.screenshotCallbacks.set(s,r),()=>{this.screenshotCallbacks.delete(s)}}emitScreenshot(s,r){this.screenshotCallbacks.forEach(n=>n(s,r))}onStatus(s){return this.statusCallbacks.add(s),()=>{this.statusCallbacks.delete(s)}}emitStatus(s,r){this.statusCallbacks.forEach(n=>n(s,r))}emitRuntimeSnapshot(s,r,n=0,a=!1){this.emitRuntimeEvent(s,{type:"runtime_snapshot",sessionId:s,seq:n,text:r,truncated:a})}emitSessionOutput(s,r,n){!s||typeof r!="string"||!r||this.emitRuntimeEvent(s,{type:"session_output",sessionId:s,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(s,r){const n=this.runtimeListeners.get(s)||new Set;return n.add(r),this.runtimeListeners.set(s,n),()=>{const a=this.runtimeListeners.get(s);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(s))}}async requestRuntimeSnapshot(s,r){if(!r)return;const n=await es(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`);if(!n.ok)return;const a=await n.json();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})}emitRuntimeEvent(s,r){var n;(n=this.runtimeListeners.get(s))==null||n.forEach(a=>a(r))}}const Gt=new Fx;function zx(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=oo();return r?`${s}?token=${encodeURIComponent(r)}`:s}const zr=zx(),ki=3e3,Vx=3e4;let Ft=null,Gx=0;const ln=new Map;let ls=null,cr=null;function Si(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function er(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function qx(e){return e==="connected"?"connected":e}async function Jr(e,s,r){const n=pp(e,r||{}),a=Ft;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++Gx}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{ln.delete(i),l(new Error(`WS command timeout: ${s}`))},3e4);ln.set(i,{resolve:p=>{clearTimeout(u),c(p)},reject:p=>{clearTimeout(u),l(p)}}),a.send(JSON.stringify({type:"command",requestId:i,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function ga(e,s){const r=Ft;if(!r||r.readyState!==WebSocket.OPEN||!s||s.type!=="subscribe"&&s.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class Yx{constructor(s){Ye(this,"daemonId");Ye(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Ft==null?void 0:Ft.readyState)===WebSocket.OPEN}get connectionState(){return(Ft==null?void 0:Ft.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return Jr(this.daemonId,s,r)}async sendInput(s,r){return Jr(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,ls&&(clearInterval(ls),ls=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Jr(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());Gt.emitScreenshot(this.daemonId,a)}}catch{}};r(),ls=setInterval(r,2e3)}stopScreenshots(s){ls&&(clearInterval(ls),ls=null)}}let Kt=null;function Xx(e){return(!Kt||Kt.daemonId!==e)&&(Kt=new Yx(e)),Kt}function Qx({children:e}){const s=o.useRef(en()),r=en();s.current=r;const{setUserName:n}=ys(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),u=o.useCallback((d,b)=>{l(d),cr==null||cr(d,b)},[]),p=o.useRef(null),m=o.useRef(),f=o.useRef(ki),g=o.useRef(!0),w=o.useRef(!1),A=o.useRef("initial_connect");return o.useEffect(()=>{g.current=!0,w.current=!1;function d(){var h,N;if(!g.current||((h=p.current)==null?void 0:h.readyState)===WebSocket.OPEN||((N=p.current)==null?void 0:N.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${zr}...`),er("connect_attempt",{url:zr,reason:A.current,delayMs:f.current});let y;try{y=new WebSocket(zr)}catch(_){console.error("[Standalone WS] Failed to create WebSocket:",_),b();return}p.current=y,y.onopen=()=>{if(!g.current){y.close();return}u("connected"),f.current=ki,er("open",{url:zr,reason:A.current}),as.resubscribeAll({sendData:ga}),console.log("[Standalone WS] Connected")},Ft=y,y.onmessage=_=>{var k,I;try{const j=JSON.parse(_.data);if((j.type==="command_result"||j.type==="error")&&j.requestId){const v=ln.get(j.requestId);v&&(ln.delete(j.requestId),j.type==="error"?v.reject(new Error(((k=j.data)==null?void 0:k.message)||"Command failed")):v.resolve(j.data));return}if(j.type==="session_output"){const v=j.sessionId||j.cliId||j.cliType;v&&Gt.emitSessionOutput(v,typeof j.data=="string"?j.data:"",typeof j.seq=="number"?j.seq:void 0);return}if(j.type==="runtime_snapshot"){Gt.emitRuntimeSnapshot(j.sessionId,typeof j.text=="string"?j.text:"",typeof j.seq=="number"?j.seq:0,!!j.truncated);return}if(j.type==="topic_update"){const v=j.update;v&&as.publish(v);return}if(j.type==="status"||j.type==="initial_state"){const v=j.data;if(!v)return;const{injectEntries:x,markLoaded:E,getIdes:T}=s.current,L=v.instanceId||"standalone",M=T().find(C=>C.id===L),W=Xx(L);Gt.register(L,W),Gt.setState(L,"connected"),u("connected",L),Gt.emitStatus(L,v);const U=rn(v,{daemonId:L,existingDaemon:M,existingEntries:T()});Si("ws_status",{type:j.type,daemonId:L,sessions:(v.sessions||[]).map(C=>({id:C.id,parentId:C.parentId,providerType:C.providerType,kind:C.kind,transport:C.transport,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,title:C.title})),recentLaunches:(v.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),Si("entries",{daemonId:L,entries:U.filter(C=>C.type!=="adhdev-daemon").map(C=>({id:C.id,type:C.type,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,sessionId:C.sessionId}))}),U.length>0&&x(U,{authoritativeDaemonIds:[L]}),E(),c.current!==L&&((I=i.current)==null||I.call(i),c.current=L,i.current=as.subscribe({sendData:ga},L,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${L}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const R=s.current.getIdes(),B=R.find(D=>D.id===L),S=rn(C.status,{daemonId:L,existingDaemon:B,existingEntries:R,timestamp:C.timestamp});S.length>0&&s.current.injectEntries(S),C.userName&&a.current&&a.current(C.userName)}))}}catch(j){console.error("[Standalone WS] Parse error:",j)}},y.onclose=_=>{g.current&&(Kt==null||Kt.stopScreenshots(),Kt&&Gt.setState(Kt.daemonId,"disconnected"),u("disconnected"),p.current=null,A.current=`close:${_.code}${_.wasClean?":clean":":unclean"}`,er("close",{code:_.code,reason:_.reason||"",wasClean:_.wasClean}),b())},y.onerror=_=>{w.current||!g.current||(A.current="error",er("error",{message:_ instanceof Event?"event":String(_),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",_))}}function b(){if(!g.current)return;clearTimeout(m.current);const y=f.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),er("schedule_reconnect",{reason:A.current,delayMs:y}),m.current=setTimeout(()=>{f.current=Math.min(f.current*1.5,Vx),d()},y)}return d(),()=>{var y;g.current=!1,w.current=!0,(y=i.current)==null||y.call(i),i.current=null,c.current=null,clearTimeout(m.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,Ft=null),Kt&&(Kt.stopScreenshots(),Gt.unregister(Kt.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function Jx({children:e}){const[s,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(cr=(c,l)=>{r(c),l&&a(l)},()=>{cr=null}),[]);const i=o.useMemo(()=>{const c=s==="connected",l=qx(s),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:s,isConnected:c,connectionStates:u}},[s,n]);return t.jsx(pd,{connectionOverrides:i,children:t.jsx(Qx,{children:e})})}const Zx=[{id:"dashboard",path:"/dashboard",icon:t.jsx(Ri,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(Xt,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx(dn,{}),label:"Settings"}];function eb({children:e}){const s=Us(),r=wa(),[n,a]=o.useState(!1),[i,c]=o.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),l=m=>{s(m),a(!1)},u=()=>{c(m=>{const f=!m;try{localStorage.setItem("sidebar-collapsed",f?"1":"0")}catch{}return f})},p=m=>`nav-item${r.pathname.startsWith(m)?" active":""} cursor-pointer ${i?"justify-center py-2.5 px-0":""}`;return t.jsxs("div",{className:`app-layout${n?" mobile-menu-open":""}${i?" sidebar-collapsed":""}`,children:[t.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:()=>a(!0),children:[t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"})]}),n&&t.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:()=>a(!1),onKeyDown:m=>m.key==="Escape"&&a(!1)}),t.jsxs("aside",{className:`sidebar ${n?"sidebar-open":""}`,children:[t.jsxs("div",{className:"sidebar-header",children:[t.jsxs("div",{className:`sidebar-logo ${i?"justify-center gap-0":""}`,children:[t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&t.jsx("span",{children:"ADHDev"})]}),t.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:()=>a(!1),children:t.jsx(At,{size:16})})]}),t.jsx("nav",{className:"sidebar-nav",children:Zx.map(m=>t.jsxs("div",{className:p(m.path),id:`nav-${m.id}`,onClick:()=>l(m.path),title:i?m.label:void 0,children:[t.jsx("span",{className:"nav-icon",children:m.icon}),!i&&m.label]},m.id))}),t.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":""}`,id:"nav-docs",onClick:()=>window.open("https://docs.adhf.dev","_blank"),title:i?"Docs":void 0,children:[t.jsx("span",{className:"nav-icon",children:t.jsx(Pi,{})}),!i&&t.jsxs(t.Fragment,{children:["Docs",t.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]})]}),t.jsxs("div",{className:`nav-item cursor-pointer${r.pathname==="/about"?" active":""} ${i?"justify-center py-2.5 px-0":""}`,id:"nav-about",onClick:()=>s("/about"),title:i?"About":void 0,children:[t.jsx("span",{className:"nav-icon",children:t.jsx(Di,{})}),!i&&"About"]}),!i&&t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.83"]}),t.jsx(Np,{collapsed:i}),t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:u,title:i?"Expand sidebar":"Collapse sidebar",children:[t.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&t.jsx("span",{className:"text-xs",children:"Collapse"})]})]})]}),t.jsx("main",{className:"main-content relative",children:t.jsx("div",{className:"main-content-inner",children:e})})]})}const tb=[{icon:t.jsx(Xt,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(Qt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(Ei,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(Rt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(dr,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(Pi,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],sb=[{icon:t.jsx(Md,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(Ri,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(mn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(jd,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(ka,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(Sd,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],rb=[{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 nb(){return t.jsxs(Rc,{icon:t.jsx(Di,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:t.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.8.83"]}),children:[t.jsx(Lt,{children:t.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[t.jsxs("div",{className:"max-w-2xl",children:[t.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),t.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."}),t.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."})]}),t.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[t.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 ↗"}),t.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 ↗"}),t.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 ↗"})]})]})}),t.jsx(Lt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:t.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:tb.map(e=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[t.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[t.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]}),t.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),t.jsx(Lt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:t.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:Tc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:_c.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Lc.map(e=>`${e.icon} ${e.name}`)}].map(e=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[t.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),t.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(s=>t.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:s},s))})]},e.label))})}),t.jsx(Lt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:t.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:sb.map(e=>t.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[t.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[t.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]}),t.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),t.jsx(Lt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:t.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:t.jsxs("table",{className:"w-full text-[13px]",children:[t.jsx("thead",{children:t.jsxs("tr",{className:"bg-bg-secondary",children:[t.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),t.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),t.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),t.jsx("tbody",{children:rb.map((e,s)=>t.jsxs("tr",{className:s%2===0?"bg-bg-glass":"bg-transparent",children:[t.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e.feature}),t.jsx("td",{className:"px-4 py-2.5 text-center",children:e.selfhost?t.jsx("span",{className:"text-emerald-500",children:"✓"}):t.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),t.jsx("td",{className:"px-4 py-2.5 text-center",children:t.jsx("span",{className:"text-emerald-500",children:"✓"})})]},e.feature))})]})})}),t.jsx(Pc,{icon:t.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:t.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[t.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),t.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[t.jsx(Bd,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function ab(){const{ides:e}=ys(),s=e.find(B=>B.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=Pt(),{userName:a}=ys(),[i,c]=o.useState(a||""),[l,u]=o.useState(null),[p,m]=o.useState(null),[f,g]=o.useState("127.0.0.1"),[w,A]=o.useState(""),[d,b]=o.useState(""),[y,h]=o.useState(""),[N,_]=o.useState(""),[k,I]=o.useState(""),[j,v]=o.useState(!1),x=async()=>{const S=await(await es("/auth/session")).json();u(S)},E=async()=>{const S=await(await es("/api/v1/standalone/preferences")).json();m(S),g(S.standaloneBindHost)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([x(),E()]).catch(B=>{_(B instanceof Error?B.message:String(B))})},[]);const T=B=>{const S=B.target.value.trim();s!=null&&s.id&&S!==a&&n(s.id,"set_user_name",{userName:S}).catch(console.error)},[L,M]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),W=B=>{M(B);try{localStorage.setItem("adhdev_sound",B?"1":"0")}catch{}},U=async()=>{_(""),I(""),v(!0);try{const B=await es("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:f})}),S=await B.json();if(!B.ok)throw new Error((S==null?void 0:S.error)||"Failed to save standalone network preference");m(S),g(S.standaloneBindHost),I(S.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(B){_(B instanceof Error?B.message:String(B))}finally{v(!1)}},C=async()=>{if(_(""),I(""),d.trim().length<4){_("Password must be at least 4 characters.");return}if(d!==y){_("New password and confirmation do not match.");return}v(!0);try{const B=await es("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,newPassword:d})}),S=await B.json();if(!B.ok)throw new Error((S==null?void 0:S.error)||"Failed to save password");u(S),await E(),A(""),b(""),h(""),I(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),jl()}catch(B){_(B instanceof Error?B.message:String(B))}finally{v(!1)}},R=async()=>{_(""),I(""),v(!0);try{const B=await es("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,clear:!0})}),S=await B.json();if(!B.ok)throw new Error((S==null?void 0:S.error)||"Failed to clear password");u(S),await E(),A(""),b(""),h(""),I("Standalone password disabled.")}catch(B){_(B instanceof Error?B.message:String(B))}finally{v(!1)}};return t.jsxs(Rc,{icon:t.jsx(dn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(Pr,{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)&&t.jsx(Pr,{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."}),t.jsx(Lt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:t.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[t.jsx("span",{className:"text-text-muted",children:"Version"}),t.jsxs("span",{className:"font-mono text-xs",children:["v","0.8.83"]}),t.jsx("span",{className:"text-text-muted",children:"Status"}),t.jsx("span",{className:s?"text-green-400":"text-yellow-400",children:s?"● Running":"○ Not connected"}),t.jsx("span",{className:"text-text-muted",children:"Current bind"}),t.jsx("span",{className:"font-mono text-xs",children:(p==null?void 0:p.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Default bind"}),t.jsx("span",{className:"font-mono text-xs",children:(p==null?void 0:p.standaloneBindHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Auth"}),t.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),t.jsx(Lt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.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."}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[t.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:[t.jsx("input",{type:"radio",name:"standalone-bind-host",checked:f==="127.0.0.1",onChange:()=>g("127.0.0.1")}),t.jsxs("span",{children:[t.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),t.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."})]})]}),t.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:[t.jsx("input",{type:"radio",name:"standalone-bind-host",checked:f==="0.0.0.0",onChange:()=>g("0.0.0.0")}),t.jsxs("span",{children:[t.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),t.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."})]})]})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",onClick:()=>{U()},disabled:j,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:j?"Saving…":"Save default network mode"}),t.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(p==null?void 0:p.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),t.jsx(Lt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.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."}),N&&t.jsx(Pr,{variant:"error",children:N}),k&&t.jsx(Pr,{variant:"success",children:k}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[t.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:w,onChange:B=>A(B.target.value)}),t.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:d,onChange:B=>b(B.target.value)}),t.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:y,onChange:B=>h(B.target.value)})]}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",onClick:()=>{C()},disabled:j,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:j?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&t.jsx("button",{type:"button",onClick:()=>{R()},disabled:j,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"})]})]})}),t.jsx(Lt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?t.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):t.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(B=>t.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:`w-2 h-2 rounded-full ${B.running?"bg-green-400":"bg-text-muted/30"}`}),t.jsx("span",{className:"text-sm font-medium",children:B.name})]}),t.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:B.type})]},B.type))})}),t.jsx(Lt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(Mp,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),t.jsx(Lt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode and theme.",children:t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),t.jsx(Rp,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),t.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."}),t.jsx(Op,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),t.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."}),t.jsx(Fp,{})]})]})}),t.jsx(Lt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(Cp,{}),t.jsx(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Kd,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:L,onChange:W})]})}),t.jsx(Lt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:t.jsx("div",{className:"flex flex-col gap-3",children:t.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:[t.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[t.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[t.jsx(wd,{size:16,className:"text-text-secondary"})," Display Name"]}),t.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),t.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:B=>c(B.target.value),onBlur:T,onKeyDown:B=>{B.key==="Enter"&&B.currentTarget.blur()}})]})})})]})}Sp();Bp();const ob=Ti({baseUrl:"",getToken:oo});function ib({children:e}){const[s,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,u]=o.useState(""),[p,m]=o.useState(!1),f=async()=>{a(!0),u("");try{const A=await(await es("/auth/session")).json();r(A)}catch(w){u(w instanceof Error?w.message:String(w))}finally{a(!1)}};o.useEffect(()=>{f()},[]);const g=async w=>{w.preventDefault(),m(!0),u("");try{const A=await es("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),d=await A.json();if(!A.ok)throw new Error((d==null?void 0:d.error)||"Login failed");r(d),c(""),jl()}catch(A){u(A instanceof Error?A.message:String(A))}finally{m(!1)}};return n?t.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):s?!s.required||s.authenticated?t.jsx(t.Fragment,{children:e}):t.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:t.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:[t.jsxs("div",{children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),t.jsx("p",{className:"text-sm text-text-muted mt-1",children:s.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."})]}),s.hasPasswordAuth?t.jsxs("form",{className:"flex flex-col gap-3",onSubmit:g,children:[t.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}),t.jsx("button",{type:"submit",disabled:p||!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:p?"Signing in…":"Unlock dashboard"})]}):t.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&&t.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})]})}):t.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 Ni(){const{ides:e,initialLoaded:s}=ys();if(!s)return t.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?t.jsx(ra,{to:`/machines/${r.id}`,replace:!0}):t.jsx(ra,{to:"/dashboard",replace:!0})}function cb(){const e=o.useMemo(()=>({sendCommand:Jr,sendData:ga}),[]);return t.jsx(nd,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(xd,{client:ob,children:t.jsx(ib,{children:t.jsx(Jx,{children:t.jsx(gd,{value:e,children:t.jsx(eb,{children:t.jsxs(ad,{children:[t.jsx(is,{path:"/dashboard",element:t.jsx(px,{})}),t.jsx(is,{path:"/machine",element:t.jsx(Ni,{})}),t.jsx(is,{path:"/machines/:id",element:t.jsx(Hx,{})}),t.jsx(is,{path:"/machines",element:t.jsx(Ni,{})}),t.jsx(is,{path:"/about",element:t.jsx(nb,{})}),t.jsx(is,{path:"/settings",element:t.jsx(ab,{})}),t.jsx(is,{path:"*",element:t.jsx(ra,{to:"/dashboard",replace:!0})})]})})})})})})})}Bm({connectionManager:Gt});od(document.getElementById("root")).render(t.jsx(cb,{}));
79
+ `})]})}function oo(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function Ux(e){if(typeof window>"u")return e;const s=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),r=oo();return r&&!s.searchParams.has("token")&&s.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?s.toString():`${s.pathname}${s.search}${s.hash}`}async function es(e,s){return await fetch(Ux(e),{credentials:"same-origin",...s})}function jl(){if(typeof window>"u")return;const e=new URL(window.location.href);e.searchParams.has("token")&&(e.searchParams.delete("token"),window.history.replaceState({},"",`${e.pathname}${e.search}${e.hash}`))}class Fx{constructor(){Ye(this,"adapters",new Map);Ye(this,"states",new Map);Ye(this,"runtimeListeners",new Map);Ye(this,"screenshotCallbacks",new Map);Ye(this,"statusCallbacks",new Set)}resolveDaemonId(s){if(this.adapters.has(s))return s;if(s.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(s,r){this.adapters.set(s,r),this.states.set(s,r.connectionState)}unregister(s){this.adapters.delete(s),this.states.delete(s)}setState(s,r){this.states.set(s,r)}retryConnection(s){}get(s){const r=this.resolveDaemonId(s);return r?this.adapters.get(r):void 0}getState(s){const r=this.resolveDaemonId(s);return r&&this.states.get(r)||"disconnected"}sendData(s,r){return!1}sendPtyInput(s,r,n){return!1}onScreenshot(s,r){return this.screenshotCallbacks.set(s,r),()=>{this.screenshotCallbacks.delete(s)}}emitScreenshot(s,r){this.screenshotCallbacks.forEach(n=>n(s,r))}onStatus(s){return this.statusCallbacks.add(s),()=>{this.statusCallbacks.delete(s)}}emitStatus(s,r){this.statusCallbacks.forEach(n=>n(s,r))}emitRuntimeSnapshot(s,r,n=0,a=!1){this.emitRuntimeEvent(s,{type:"runtime_snapshot",sessionId:s,seq:n,text:r,truncated:a})}emitSessionOutput(s,r,n){!s||typeof r!="string"||!r||this.emitRuntimeEvent(s,{type:"session_output",sessionId:s,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(s,r){const n=this.runtimeListeners.get(s)||new Set;return n.add(r),this.runtimeListeners.set(s,n),()=>{const a=this.runtimeListeners.get(s);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(s))}}async requestRuntimeSnapshot(s,r){if(!r)return;const n=await es(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`);if(!n.ok)return;const a=await n.json();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})}emitRuntimeEvent(s,r){var n;(n=this.runtimeListeners.get(s))==null||n.forEach(a=>a(r))}}const Gt=new Fx;function zx(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=oo();return r?`${s}?token=${encodeURIComponent(r)}`:s}const zr=zx(),ki=3e3,Vx=3e4;let Ft=null,Gx=0;const ln=new Map;let ls=null,cr=null;function Si(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function er(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function qx(e){return e==="connected"?"connected":e}async function Jr(e,s,r){const n=pp(e,r||{}),a=Ft;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++Gx}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{ln.delete(i),l(new Error(`WS command timeout: ${s}`))},3e4);ln.set(i,{resolve:p=>{clearTimeout(u),c(p)},reject:p=>{clearTimeout(u),l(p)}}),a.send(JSON.stringify({type:"command",requestId:i,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function ga(e,s){const r=Ft;if(!r||r.readyState!==WebSocket.OPEN||!s||s.type!=="subscribe"&&s.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class Yx{constructor(s){Ye(this,"daemonId");Ye(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Ft==null?void 0:Ft.readyState)===WebSocket.OPEN}get connectionState(){return(Ft==null?void 0:Ft.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return Jr(this.daemonId,s,r)}async sendInput(s,r){return Jr(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,ls&&(clearInterval(ls),ls=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Jr(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());Gt.emitScreenshot(this.daemonId,a)}}catch{}};r(),ls=setInterval(r,2e3)}stopScreenshots(s){ls&&(clearInterval(ls),ls=null)}}let Kt=null;function Xx(e){return(!Kt||Kt.daemonId!==e)&&(Kt=new Yx(e)),Kt}function Qx({children:e}){const s=o.useRef(en()),r=en();s.current=r;const{setUserName:n}=ys(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),u=o.useCallback((d,b)=>{l(d),cr==null||cr(d,b)},[]),p=o.useRef(null),m=o.useRef(),f=o.useRef(ki),g=o.useRef(!0),w=o.useRef(!1),A=o.useRef("initial_connect");return o.useEffect(()=>{g.current=!0,w.current=!1;function d(){var h,N;if(!g.current||((h=p.current)==null?void 0:h.readyState)===WebSocket.OPEN||((N=p.current)==null?void 0:N.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${zr}...`),er("connect_attempt",{url:zr,reason:A.current,delayMs:f.current});let y;try{y=new WebSocket(zr)}catch(_){console.error("[Standalone WS] Failed to create WebSocket:",_),b();return}p.current=y,y.onopen=()=>{if(!g.current){y.close();return}u("connected"),f.current=ki,er("open",{url:zr,reason:A.current}),as.resubscribeAll({sendData:ga}),console.log("[Standalone WS] Connected")},Ft=y,y.onmessage=_=>{var k,I;try{const j=JSON.parse(_.data);if((j.type==="command_result"||j.type==="error")&&j.requestId){const v=ln.get(j.requestId);v&&(ln.delete(j.requestId),j.type==="error"?v.reject(new Error(((k=j.data)==null?void 0:k.message)||"Command failed")):v.resolve(j.data));return}if(j.type==="session_output"){const v=j.sessionId||j.cliId||j.cliType;v&&Gt.emitSessionOutput(v,typeof j.data=="string"?j.data:"",typeof j.seq=="number"?j.seq:void 0);return}if(j.type==="runtime_snapshot"){Gt.emitRuntimeSnapshot(j.sessionId,typeof j.text=="string"?j.text:"",typeof j.seq=="number"?j.seq:0,!!j.truncated);return}if(j.type==="topic_update"){const v=j.update;v&&as.publish(v);return}if(j.type==="status"||j.type==="initial_state"){const v=j.data;if(!v)return;const{injectEntries:x,markLoaded:E,getIdes:T}=s.current,L=v.instanceId||"standalone",M=T().find(C=>C.id===L),W=Xx(L);Gt.register(L,W),Gt.setState(L,"connected"),u("connected",L),Gt.emitStatus(L,v);const U=rn(v,{daemonId:L,existingDaemon:M,existingEntries:T()});Si("ws_status",{type:j.type,daemonId:L,sessions:(v.sessions||[]).map(C=>({id:C.id,parentId:C.parentId,providerType:C.providerType,kind:C.kind,transport:C.transport,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,title:C.title})),recentLaunches:(v.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),Si("entries",{daemonId:L,entries:U.filter(C=>C.type!=="adhdev-daemon").map(C=>({id:C.id,type:C.type,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,sessionId:C.sessionId}))}),U.length>0&&x(U,{authoritativeDaemonIds:[L]}),E(),c.current!==L&&((I=i.current)==null||I.call(i),c.current=L,i.current=as.subscribe({sendData:ga},L,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${L}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const R=s.current.getIdes(),B=R.find(D=>D.id===L),S=rn(C.status,{daemonId:L,existingDaemon:B,existingEntries:R,timestamp:C.timestamp});S.length>0&&s.current.injectEntries(S),C.userName&&a.current&&a.current(C.userName)}))}}catch(j){console.error("[Standalone WS] Parse error:",j)}},y.onclose=_=>{g.current&&(Kt==null||Kt.stopScreenshots(),Kt&&Gt.setState(Kt.daemonId,"disconnected"),u("disconnected"),p.current=null,A.current=`close:${_.code}${_.wasClean?":clean":":unclean"}`,er("close",{code:_.code,reason:_.reason||"",wasClean:_.wasClean}),b())},y.onerror=_=>{w.current||!g.current||(A.current="error",er("error",{message:_ instanceof Event?"event":String(_),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",_))}}function b(){if(!g.current)return;clearTimeout(m.current);const y=f.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),er("schedule_reconnect",{reason:A.current,delayMs:y}),m.current=setTimeout(()=>{f.current=Math.min(f.current*1.5,Vx),d()},y)}return d(),()=>{var y;g.current=!1,w.current=!0,(y=i.current)==null||y.call(i),i.current=null,c.current=null,clearTimeout(m.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,Ft=null),Kt&&(Kt.stopScreenshots(),Gt.unregister(Kt.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function Jx({children:e}){const[s,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(cr=(c,l)=>{r(c),l&&a(l)},()=>{cr=null}),[]);const i=o.useMemo(()=>{const c=s==="connected",l=qx(s),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:s,isConnected:c,connectionStates:u}},[s,n]);return t.jsx(pd,{connectionOverrides:i,children:t.jsx(Qx,{children:e})})}const Zx=[{id:"dashboard",path:"/dashboard",icon:t.jsx(Ri,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(Xt,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx(dn,{}),label:"Settings"}];function eb({children:e}){const s=Us(),r=wa(),[n,a]=o.useState(!1),[i,c]=o.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),l=m=>{s(m),a(!1)},u=()=>{c(m=>{const f=!m;try{localStorage.setItem("sidebar-collapsed",f?"1":"0")}catch{}return f})},p=m=>`nav-item${r.pathname.startsWith(m)?" active":""} cursor-pointer ${i?"justify-center py-2.5 px-0":""}`;return t.jsxs("div",{className:`app-layout${n?" mobile-menu-open":""}${i?" sidebar-collapsed":""}`,children:[t.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:()=>a(!0),children:[t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"})]}),n&&t.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:()=>a(!1),onKeyDown:m=>m.key==="Escape"&&a(!1)}),t.jsxs("aside",{className:`sidebar ${n?"sidebar-open":""}`,children:[t.jsxs("div",{className:"sidebar-header",children:[t.jsxs("div",{className:`sidebar-logo ${i?"justify-center gap-0":""}`,children:[t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&t.jsx("span",{children:"ADHDev"})]}),t.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:()=>a(!1),children:t.jsx(At,{size:16})})]}),t.jsx("nav",{className:"sidebar-nav",children:Zx.map(m=>t.jsxs("div",{className:p(m.path),id:`nav-${m.id}`,onClick:()=>l(m.path),title:i?m.label:void 0,children:[t.jsx("span",{className:"nav-icon",children:m.icon}),!i&&m.label]},m.id))}),t.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":""}`,id:"nav-docs",onClick:()=>window.open("https://docs.adhf.dev","_blank"),title:i?"Docs":void 0,children:[t.jsx("span",{className:"nav-icon",children:t.jsx(Pi,{})}),!i&&t.jsxs(t.Fragment,{children:["Docs",t.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]})]}),t.jsxs("div",{className:`nav-item cursor-pointer${r.pathname==="/about"?" active":""} ${i?"justify-center py-2.5 px-0":""}`,id:"nav-about",onClick:()=>s("/about"),title:i?"About":void 0,children:[t.jsx("span",{className:"nav-icon",children:t.jsx(Di,{})}),!i&&"About"]}),!i&&t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.84"]}),t.jsx(Np,{collapsed:i}),t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:u,title:i?"Expand sidebar":"Collapse sidebar",children:[t.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&t.jsx("span",{className:"text-xs",children:"Collapse"})]})]})]}),t.jsx("main",{className:"main-content relative",children:t.jsx("div",{className:"main-content-inner",children:e})})]})}const tb=[{icon:t.jsx(Xt,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(Qt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(Ei,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(Rt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(dr,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(Pi,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],sb=[{icon:t.jsx(Md,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(Ri,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(mn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(jd,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(ka,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(Sd,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],rb=[{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 nb(){return t.jsxs(Rc,{icon:t.jsx(Di,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:t.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.8.84"]}),children:[t.jsx(Lt,{children:t.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[t.jsxs("div",{className:"max-w-2xl",children:[t.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),t.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."}),t.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."})]}),t.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[t.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 ↗"}),t.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 ↗"}),t.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 ↗"})]})]})}),t.jsx(Lt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:t.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:tb.map(e=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[t.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[t.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]}),t.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),t.jsx(Lt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:t.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:Tc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:_c.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Lc.map(e=>`${e.icon} ${e.name}`)}].map(e=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[t.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),t.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(s=>t.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:s},s))})]},e.label))})}),t.jsx(Lt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:t.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:sb.map(e=>t.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[t.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[t.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]}),t.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),t.jsx(Lt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:t.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:t.jsxs("table",{className:"w-full text-[13px]",children:[t.jsx("thead",{children:t.jsxs("tr",{className:"bg-bg-secondary",children:[t.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),t.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),t.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),t.jsx("tbody",{children:rb.map((e,s)=>t.jsxs("tr",{className:s%2===0?"bg-bg-glass":"bg-transparent",children:[t.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e.feature}),t.jsx("td",{className:"px-4 py-2.5 text-center",children:e.selfhost?t.jsx("span",{className:"text-emerald-500",children:"✓"}):t.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),t.jsx("td",{className:"px-4 py-2.5 text-center",children:t.jsx("span",{className:"text-emerald-500",children:"✓"})})]},e.feature))})]})})}),t.jsx(Pc,{icon:t.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:t.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[t.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),t.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[t.jsx(Bd,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function ab(){const{ides:e}=ys(),s=e.find(B=>B.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=Pt(),{userName:a}=ys(),[i,c]=o.useState(a||""),[l,u]=o.useState(null),[p,m]=o.useState(null),[f,g]=o.useState("127.0.0.1"),[w,A]=o.useState(""),[d,b]=o.useState(""),[y,h]=o.useState(""),[N,_]=o.useState(""),[k,I]=o.useState(""),[j,v]=o.useState(!1),x=async()=>{const S=await(await es("/auth/session")).json();u(S)},E=async()=>{const S=await(await es("/api/v1/standalone/preferences")).json();m(S),g(S.standaloneBindHost)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([x(),E()]).catch(B=>{_(B instanceof Error?B.message:String(B))})},[]);const T=B=>{const S=B.target.value.trim();s!=null&&s.id&&S!==a&&n(s.id,"set_user_name",{userName:S}).catch(console.error)},[L,M]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),W=B=>{M(B);try{localStorage.setItem("adhdev_sound",B?"1":"0")}catch{}},U=async()=>{_(""),I(""),v(!0);try{const B=await es("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:f})}),S=await B.json();if(!B.ok)throw new Error((S==null?void 0:S.error)||"Failed to save standalone network preference");m(S),g(S.standaloneBindHost),I(S.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(B){_(B instanceof Error?B.message:String(B))}finally{v(!1)}},C=async()=>{if(_(""),I(""),d.trim().length<4){_("Password must be at least 4 characters.");return}if(d!==y){_("New password and confirmation do not match.");return}v(!0);try{const B=await es("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,newPassword:d})}),S=await B.json();if(!B.ok)throw new Error((S==null?void 0:S.error)||"Failed to save password");u(S),await E(),A(""),b(""),h(""),I(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),jl()}catch(B){_(B instanceof Error?B.message:String(B))}finally{v(!1)}},R=async()=>{_(""),I(""),v(!0);try{const B=await es("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,clear:!0})}),S=await B.json();if(!B.ok)throw new Error((S==null?void 0:S.error)||"Failed to clear password");u(S),await E(),A(""),b(""),h(""),I("Standalone password disabled.")}catch(B){_(B instanceof Error?B.message:String(B))}finally{v(!1)}};return t.jsxs(Rc,{icon:t.jsx(dn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(Pr,{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)&&t.jsx(Pr,{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."}),t.jsx(Lt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:t.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[t.jsx("span",{className:"text-text-muted",children:"Version"}),t.jsxs("span",{className:"font-mono text-xs",children:["v","0.8.84"]}),t.jsx("span",{className:"text-text-muted",children:"Status"}),t.jsx("span",{className:s?"text-green-400":"text-yellow-400",children:s?"● Running":"○ Not connected"}),t.jsx("span",{className:"text-text-muted",children:"Current bind"}),t.jsx("span",{className:"font-mono text-xs",children:(p==null?void 0:p.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Default bind"}),t.jsx("span",{className:"font-mono text-xs",children:(p==null?void 0:p.standaloneBindHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Auth"}),t.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),t.jsx(Lt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.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."}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[t.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:[t.jsx("input",{type:"radio",name:"standalone-bind-host",checked:f==="127.0.0.1",onChange:()=>g("127.0.0.1")}),t.jsxs("span",{children:[t.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),t.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."})]})]}),t.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:[t.jsx("input",{type:"radio",name:"standalone-bind-host",checked:f==="0.0.0.0",onChange:()=>g("0.0.0.0")}),t.jsxs("span",{children:[t.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),t.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."})]})]})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",onClick:()=>{U()},disabled:j,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:j?"Saving…":"Save default network mode"}),t.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(p==null?void 0:p.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),t.jsx(Lt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.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."}),N&&t.jsx(Pr,{variant:"error",children:N}),k&&t.jsx(Pr,{variant:"success",children:k}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[t.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:w,onChange:B=>A(B.target.value)}),t.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:d,onChange:B=>b(B.target.value)}),t.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:y,onChange:B=>h(B.target.value)})]}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",onClick:()=>{C()},disabled:j,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:j?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&t.jsx("button",{type:"button",onClick:()=>{R()},disabled:j,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"})]})]})}),t.jsx(Lt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?t.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):t.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(B=>t.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:`w-2 h-2 rounded-full ${B.running?"bg-green-400":"bg-text-muted/30"}`}),t.jsx("span",{className:"text-sm font-medium",children:B.name})]}),t.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:B.type})]},B.type))})}),t.jsx(Lt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(Mp,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),t.jsx(Lt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode and theme.",children:t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),t.jsx(Rp,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),t.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."}),t.jsx(Op,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),t.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."}),t.jsx(Fp,{})]})]})}),t.jsx(Lt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(Cp,{}),t.jsx(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Kd,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:L,onChange:W})]})}),t.jsx(Lt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:t.jsx("div",{className:"flex flex-col gap-3",children:t.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:[t.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[t.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[t.jsx(wd,{size:16,className:"text-text-secondary"})," Display Name"]}),t.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),t.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:B=>c(B.target.value),onBlur:T,onKeyDown:B=>{B.key==="Enter"&&B.currentTarget.blur()}})]})})})]})}Sp();Bp();const ob=Ti({baseUrl:"",getToken:oo});function ib({children:e}){const[s,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,u]=o.useState(""),[p,m]=o.useState(!1),f=async()=>{a(!0),u("");try{const A=await(await es("/auth/session")).json();r(A)}catch(w){u(w instanceof Error?w.message:String(w))}finally{a(!1)}};o.useEffect(()=>{f()},[]);const g=async w=>{w.preventDefault(),m(!0),u("");try{const A=await es("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),d=await A.json();if(!A.ok)throw new Error((d==null?void 0:d.error)||"Login failed");r(d),c(""),jl()}catch(A){u(A instanceof Error?A.message:String(A))}finally{m(!1)}};return n?t.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):s?!s.required||s.authenticated?t.jsx(t.Fragment,{children:e}):t.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:t.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:[t.jsxs("div",{children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),t.jsx("p",{className:"text-sm text-text-muted mt-1",children:s.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."})]}),s.hasPasswordAuth?t.jsxs("form",{className:"flex flex-col gap-3",onSubmit:g,children:[t.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}),t.jsx("button",{type:"submit",disabled:p||!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:p?"Signing in…":"Unlock dashboard"})]}):t.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&&t.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})]})}):t.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 Ni(){const{ides:e,initialLoaded:s}=ys();if(!s)return t.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?t.jsx(ra,{to:`/machines/${r.id}`,replace:!0}):t.jsx(ra,{to:"/dashboard",replace:!0})}function cb(){const e=o.useMemo(()=>({sendCommand:Jr,sendData:ga}),[]);return t.jsx(nd,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(xd,{client:ob,children:t.jsx(ib,{children:t.jsx(Jx,{children:t.jsx(gd,{value:e,children:t.jsx(eb,{children:t.jsxs(ad,{children:[t.jsx(is,{path:"/dashboard",element:t.jsx(px,{})}),t.jsx(is,{path:"/machine",element:t.jsx(Ni,{})}),t.jsx(is,{path:"/machines/:id",element:t.jsx(Hx,{})}),t.jsx(is,{path:"/machines",element:t.jsx(Ni,{})}),t.jsx(is,{path:"/about",element:t.jsx(nb,{})}),t.jsx(is,{path:"/settings",element:t.jsx(ab,{})}),t.jsx(is,{path:"*",element:t.jsx(ra,{to:"/dashboard",replace:!0})})]})})})})})})})}Bm({connectionManager:Gt});od(document.getElementById("root")).render(t.jsx(cb,{}));