@adhdev/daemon-standalone 0.8.68 → 0.8.69
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 gd(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0
|
|
|
29
29
|
|
|
30
30
|
`)))return}const C=(c==null?void 0:c[R.id])??S[R.id];try{const U=await j(R.invokeScript),G=lr(U);if(G&&!G.ok||dr(U))throw new Error((G==null?void 0:G.error)||Es(U)||`Could not run ${R.label}`);G&&k(R,C??!0,G)}catch(U){g(R,C);const G=U instanceof Error?U.message:`Could not run ${R.label}`;ct.showToast(G,"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:"│"}),x.map(R=>{const C=String(T[R.id]||""),U=Sd(R,d,C),G=N===R.id,A=w===R.id,D=Sr(R,d);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:G?`${p}55`:"transparent",border:"1px solid",color:C?"var(--text-primary)":"var(--text-muted)"},onClick:()=>$(R),children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),A?"...":U||R.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),G&&D.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>h(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()}),D.map(B=>t.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:B.value===C?`${p}18`:"transparent",color:B.value===C?p:"var(--text-secondary)",fontWeight:B.value===C?600:400,borderLeft:B.value===C?`2px solid ${p}`:"2px solid transparent"},title:B.description||B.label,onMouseEnter:W=>{W.currentTarget.style.background=`${p}12`},onMouseLeave:W=>{W.currentTarget.style.background=B.value===C?`${p}18`:"transparent"},onClick:()=>I(R,B.value),children:B.label},B.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:C?"var(--text-primary)":"var(--text-muted)"},onClick:()=>M(R),title:`Click to cycle: ${D.map(B=>B.label).join(" → ")}`,children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),U||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:C?`${p}44`:"transparent",background:C?`${p}14`:"var(--surface-tertiary)",color:C?p:"var(--text-muted)"},onClick:()=>L(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:()=>O(R),children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),R.resultDisplay==="inline"&&C?`${R.label}: ${C}`: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:C?"var(--text-primary)":"var(--text-muted)"},children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),C?`${R.label}: ${C}`:R.label]},R.id);default:return null}})]})}const Id=o.memo(function({contextKey:s,panelLabel:r,isSending:n,onSend:a,isActive:i=!0}){const c=o.useRef(null),[l,m]=o.useState("");o.useEffect(()=>{m("")},[s]),o.useEffect(()=>{var u;i&&((u=c.current)==null||u.focus())},[s,i]);const p=()=>{const u=l.trim();!u||n||(m(""),a(u))};return t.jsx("div",{className:"dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden transition-all duration-200 ease-out",style:{borderTop:i?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:i?72:0,opacity:i?1:0,transform:i?"translateY(0)":"translateY(10px)",padding:i?"10px 12px":"0 12px",pointerEvents:i?"auto":"none"},"aria-hidden":!i,children:t.jsxs("div",{className:"flex gap-2.5 items-center",title:i?`Send message to ${r}`:void 0,children:[t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:c,type:"text",placeholder:`Send message to ${r}...`,value:l,onChange:u=>m(u.target.value),onPaste:u=>{const f=u.clipboardData.getData("text");f&&m(v=>v+f),u.preventDefault()},onKeyDown:u=>{if(u.key==="Enter"){if(u.nativeEvent.isComposing){u.preventDefault();return}u.preventDefault(),p()}},onBlur:u=>{if(window.innerWidth<768){const f=u.relatedTarget;if((f==null?void 0:f.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:p,disabled:!l.trim()||n,className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${l.trim()&&!n?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:l.trim()&&!n?{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:l.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})}),et=e=>e.transport==="pty",Is=(e,s)=>et(e)?e.mode||"terminal":"chat",ai=(e,s)=>et(e)&&Is(e)==="terminal",Ye=e=>e.transport==="acp";function Vt(e){return e.streamSource!=="agent-stream"}function qt(e){var s;return e.daemonId||((s=e.routeId)==null?void 0:s.split(":")[0])||e.routeId||""}function oi(e){return e.machineName||""}function er(e){return qt(e)}function Dt(e){return e.agentType||""}function Rr(e){return e.hostIdeType||""}function ta(e){return e.displayPrimary||e.agentName||"Agent"}function ii(e){return[e.displaySecondary,oi(e)].filter(Boolean)}function us(e){return e.agentName||at(Dt(e))}function Ad(e){var s,r;if(!Vt(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return at(Rr(e)||Dt(e))}function sa(e){return Vt(e)?e.sessionId:e.nativeSessionId}function Ha(e){return Vt(e)?"native":e.tabKey}function Td(e){return e.sessionId}function Md(e,s){if(s)return Vt(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function Ld(e,s){const r=Dt(e),n=Vt(e),a=et(e)||Ye(e),i=n?a?us(e)||(s==null?void 0:s.cliName)||at(Rr(e)||r):s!=null&&s.type?at(s.type):at(Rr(e)||r):us(e);return{isNativeConversation:n,isCli:et(e),isAcp:Ye(e),isCliTerminal:ai(e),providerType:r,displayLabel:i,targetEntry:Md(e,s)}}function ci({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=Ls(),c=qt(e),l=oi(e),m=e.transport==="cdp-page"||e.transport==="cdp-webview",p=e.streamSource==="agent-stream"&&!!e.agentName,u=!p&&(e.transport==="pty"||e.transport==="acp"),f=us(e),v=Ad(e),S=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),T=o.useCallback(()=>{if(r){r();return}const d=sa(e);d&&i(`/dashboard?activeTab=${encodeURIComponent(d)}`)},[e,i,r]);return t.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[m&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:T,title:v,children:[t.jsx(It,{size:12}),t.jsx("span",{children:v})]}):t.jsxs("span",{className:"conversation-meta-chip",title:v,children:[t.jsx(It,{size:12}),t.jsx("span",{children:v})]})),p&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[t.jsx(Ys,{size:12}),t.jsx("span",{children:f})]}),u&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[t.jsx(Ys,{size:12}),t.jsx("span",{children:f})]}),l&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:S,title:l,children:[t.jsx(Ot,{size:12}),t.jsx("span",{children:l})]}):t.jsxs("span",{className:"conversation-meta-chip",title:l,children:[t.jsx(Ot,{size:12}),t.jsx("span",{children:l})]}))]})}function Ua(e,s){return`${e}:${s}`}function _d(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function ur(e,s){_d()&&console.debug(`[subscription-manager] ${e}`,s)}class Rd{constructor(){qe(this,"active",new Map)}subscribe(s,r,n,a){var p;const i=Ua(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 u={daemonId:r,request:n,handlers:new Set([a])};this.active.set(i,u),ur("subscribe",{daemonId:r,topic:n.topic,key:n.key}),l=((p=s.sendData)==null?void 0:p.call(s,r,n))??!1}const m=()=>{var v;const u=this.active.get(i);if(!u||(u.handlers.delete(a),u.handlers.size>0))return;this.active.delete(i);const f={type:"unsubscribe",topic:n.topic,key:n.key};ur("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(v=s.sendData)==null||v.call(s,r,f)};return m.initialSendAccepted=l,m}publish(s){const r=Ua(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,ks.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),ks.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.handler_invoked",topic:s.topic,payload:{key:s.key}})}))}resubscribeAll(s){var r;ur("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);ur("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 Gt=new Rd;function Pd(e,s){if(!e)return s??null;if(!s)return e??null;const r=Array.isArray(e.messages)&&e.messages.length>0?e.messages:s.messages,n=e.activeModal||(e.status==="waiting_approval"?s.activeModal:null);return{...s,...e,messages:r,activeModal:n,inputContent:e.inputContent??s.inputContent}}function Dd(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});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 mr(e,s){return{...e,parentId:e.parentId??(s==null?void 0:s.parentSessionId)??null,providerName:e.providerName??(s==null?void 0:s.providerName)??(s==null?void 0:s.cliName)??(s==null?void 0:s.type)??e.providerType,workspace:e.workspace??(s==null?void 0:s.workspace)??null,mode:e.mode??(s==null?void 0:s.mode),capabilities:e.capabilities??(s==null?void 0:s.sessionCapabilities)??[],cdpConnected:e.cdpConnected??(s==null?void 0:s.cdpConnected),activeChat:Pd(e.activeChat,s==null?void 0:s.activeChat),controlValues:e.controlValues??(s==null?void 0:s.controlValues),providerControls:e.providerControls??(s==null?void 0:s.providerControls),summaryMetadata:e.summaryMetadata??(s==null?void 0:s.summaryMetadata),runtimeWriteOwner:e.runtimeWriteOwner??(s==null?void 0:s.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(s==null?void 0:s.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(s==null?void 0:s.lastMessagePreview),lastMessageRole:e.lastMessageRole??(s==null?void 0:s.lastMessageRole),lastMessageAt:e.lastMessageAt??(s==null?void 0:s.lastMessageAt),lastMessageHash:e.lastMessageHash??(s==null?void 0:s.lastMessageHash)}}function Ed(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 Pr(e,s){const r=[],{daemonId:n,existingDaemon:a,existingEntries:i,timestamp:c}=s,l=c||e.timestamp||Date.now(),m=e.sessions||[],{topLevel:p,childrenByParent:u}=Ed(m),f=Dd(i,n),v=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,S=p.filter(b=>b.kind==="workspace"&&b.transport==="cdp-page"),T=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},...v&&{machine:v,platform:v.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:S.some(b=>!!b.cdpConnected)});for(const b of S){const N=f.get(b.id),h=mr(b,N),w=(u.get(b.id)||[]).map(_=>mr(_,f.get(_.id)));r.push({id:`${n}:ide:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(N==null?void 0:N.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:w,agents:w.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,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 T){const N=f.get(b.id),h=mr(b,N);r.push({id:`${n}:cli:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(N==null?void 0:N.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||(N==null?void 0:N.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,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 N=f.get(b.id),h=mr(b,N);r.push({id:`${n}:acp:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(N==null?void 0:N.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,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 on=new Map,cn=new Map,ln=new Set,Fs=new Map,$d=1200;function Bd(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 Fa(e,s){const r=Fs.get(e);!r||r.size===0||(Fs.delete(e),r.forEach(n=>n(s)))}function Kd(e,s){return new Promise(r=>{const n=Fs.get(e)||new Set;Fs.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&Fs.delete(e),r(c)},i=setTimeout(()=>a(!1),s);n.add(a)})}function tr(){const{sendCommand:e,sendData:s}=At(),{injectEntries:r,getIdes:n}=Lr();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??6e4,l=cn.get(a)||0;if(!(i!=null&&i.force)&&ln.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const m=on.get(a);if(m)return m;const p=(async()=>{if(s&&!ln.has(a)&&(ln.add(a),Gt.subscribe({sendData:s},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},d=>{const b=n(),N=b.find(w=>w.id===a),h=Pr(d.status,{daemonId:a,existingDaemon:N,existingEntries:b,timestamp:d.timestamp});h.length>0&&r(h),cn.set(a,Date.now()),Fa(a,!0)}),!(i!=null&&i.force)&&await Kd(a,$d)))return;const u=await e(a,"get_status_metadata"),f=Bd(u);if(!f)return;const v=n(),S=v.find(d=>d.id===a),T=Pr(f,{daemonId:a,existingDaemon:S,existingEntries:v,timestamp:f.timestamp||Date.now()});T.length>0&&r(T,{authoritativeDaemonIds:[a]}),cn.set(a,Date.now()),Fa(a,!0)})().finally(()=>{on.delete(a)});return on.set(a,p),p},[n,r,e,s])}function Ut(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}function ra(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=Ns(e.content),i=Ns(s.content);if(!a||a!==i)return!1;const c=Ut(e),l=Ut(s);return c&&l?Math.abs(c-l)<=15e3:!!e._localId!=!!s._localId}function za(e){let s=0;return e!=null&&e._localId||(s+=4),e!=null&&e.id&&(s+=3),e!=null&&e._turnKey&&(s+=2),Ut(e)&&(s+=1),s}function As(e){return Ns(e==null?void 0:e.content)}function Rn(e,s){return!e||!s||e.length<=s.length||s.length<80?!1:e.startsWith(s)||e.includes(s)}function Wd(e,s){const r=As(e),n=As(s);return!r||!n||r===n?null:Rn(r,n)?e:Rn(n,r)?s:null}function Od(e,s){const r=Wd(e,s);if(r)return r;const n=za(e),a=za(s);return a!==n?a>n?s:e:As(s).length>=As(e).length?s:e}function Qs(e){const s=[];for(const r of e){const n=s.findIndex(a=>ra(a,r));if(n>=0){s.splice(n,1,Od(s[n],r));continue}s.push(r)}return s}function Hd(e,s){const r=Array.isArray(e)?e:[],n=Array.isArray(s)?s:[];return r.length===0?n:n.length===0?r:Qs([...r,...n])}function Va(e){return[...e].sort((s,r)=>{const n=Ut(s),a=Ut(r);return n&&a&&n!==a?n-a:0})}function Ga(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=>ra(i,n));return a>=0?(r.splice(a,1),!1):!0})}function Ud(e,s){return e.filter(r=>{const n=As(r),a=String((r==null?void 0:r.role)||"").toLowerCase(),i=Ut(r);return!s.some(c=>{if(ra(r,c))return!0;const l=String((c==null?void 0:c.role)||"").toLowerCase();if(!n||!a||a!==l)return!1;const m=As(c);if(!Rn(m,n)&&m!==n)return!1;const p=Ut(c);return i&&p?Math.abs(i-p)<=15e3:!0})})}const Fd=60,zd=200;function Vd(e={}){return e.isCliLike?zd:Fd}const sr=60,qa=new Map;function Gd(e){let s=2166136261;for(const r of e){const n=String(r||"");for(let a=0;a<n.length;a+=1)s^=n.charCodeAt(a),s=Math.imul(s,16777619)>>>0;s^=255,s=Math.imul(s,16777619)>>>0}return s.toString(16).padStart(8,"0")}function li(e,s){return`${e}::${s}`}function Pn(e=sr){return{liveMessages:[],cursor:qd([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function di(e){if(!e)return"";let s="";try{s=JSON.stringify(e.content??"")}catch{s=String(e.content??"")}return Gd([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),s])}function qd(e,s=sr){return{knownMessageCount:e.length,lastMessageSignature:di(e[e.length-1]),tailLimit:s}}function Ya(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 Yd(e,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return e;case"append":return Qs([...e,...r]);case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??e.length),e.length));return Qs([...e.slice(0,n),...r])}case"full":default:return r}}class Xd{constructor(s){qe(this,"manager");qe(this,"sendData");qe(this,"daemonId");qe(this,"sessionId");qe(this,"historySessionId");qe(this,"subscriptionKey");qe(this,"snapshot");qe(this,"transportSubscription",null);qe(this,"listeners",new Set);qe(this,"retainCount",0);qe(this,"loadHistoryPromise",null);this.manager=s.manager||Gt,this.sendData=s.sendData,this.daemonId=s.daemonId,this.sessionId=s.sessionId,this.historySessionId=s.historySessionId,this.subscriptionKey=s.subscriptionKey,this.snapshot=Pn(Math.max(0,s.tailLimit??sr))}updateOptions(s){s.manager&&(this.manager=s.manager),s.sendData&&(this.sendData=s.sendData),s.historySessionId&&(this.historySessionId=s.historySessionId)}getSnapshot(){return this.snapshot}subscribe(s){return this.listeners.add(s),s(this.snapshot),()=>{this.listeners.delete(s)}}retain(){this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),this.retainCount===0&&this.disconnect()}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.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null}emit(){this.listeners.forEach(s=>s(this.snapshot))}handleUpdate(s){const r=Yd(this.snapshot.liveMessages,s),n={knownMessageCount:Math.max(r.length,Number(s.totalMessages||0)),lastMessageSignature:typeof s.lastMessageSignature=="string"?s.lastMessageSignature:di(r[r.length-1]),tailLimit:this.snapshot.cursor.tailLimit};Ya(this.snapshot.liveMessages)===Ya(r)&&this.snapshot.cursor.knownMessageCount===n.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===n.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:r,cursor:n},this.emit())}}function ui(e){const s=li(e.daemonId,e.sessionId),r=qa.get(s);if(r)return r.updateOptions(e),r;const n=new Xd(e);return qa.set(s,n),n}function Qd(e,s){return{...e,loadHistoryPage:s}}function Jd(e,s){return e.subscriptionKey.localeCompare(s.subscriptionKey)||e.daemonId.localeCompare(s.daemonId)||e.sessionId.localeCompare(s.sessionId)||e.historySessionId.localeCompare(s.historySessionId)}function Zd(e){const s=new Set,r=[];for(const n of e){const a=er(n),i=n.sessionId||"";if(!a||!i)continue;const c=li(a,i);s.has(c)||(s.add(c),r.push({daemonId:a,sessionId:i,historySessionId:n.providerSessionId||i,subscriptionKey:`daemon:${a}:session:${i}`}))}return r.sort(Jd),{descriptors:r,signature:r.map(n=>`${n.subscriptionKey}|${n.historySessionId}`).join("||")}}function eu(e,s){const{sendData:r,sendCommand:n}=At(),a=(s==null?void 0:s.enabled)!==!1,i=er(e),c=e.sessionId||"",l=e.providerSessionId||c,m=`daemon:${i}:session:${c}`,p=Math.max(0,(s==null?void 0:s.tailLimit)??sr),u=o.useMemo(()=>!a||!i||!c?null:ui({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:m,sendData:r,tailLimit:p}),[i,a,l,r,c,m,p]),[f,v]=o.useState(()=>(u==null?void 0:u.getSnapshot())||Pn(p));o.useEffect(()=>{if(!u){v(Pn(p));return}u.retain(),v(u.getSnapshot());const T=u.subscribe(d=>{v(d)});return()=>{T(),u.release()}},[u,p]);const S=o.useCallback(async()=>{!u||!i||!c||await u.loadHistoryPage(async()=>{const T=e.agentType,d=await n(i,"chat_history",{agentType:T,offset:u.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,u,i,l,n,c]);return o.useMemo(()=>Qd(f,S),[S,f])}function tu(e,s){const{sendData:r}=At(),n=(s==null?void 0:s.enabled)!==!1,a=Math.max(0,sr),i=o.useMemo(()=>Zd(e),[e]);o.useEffect(()=>{if(!r||i.descriptors.length===0)return;const c=i.descriptors.map(l=>ui({...l,sendData:r,tailLimit:a}));return c.forEach(l=>l.retain()),()=>{c.forEach(l=>l.release())}},[i.signature,n,r,a])}const su=60;function Dn({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,handleFocusAgent:a,isFocusingAgent:i,actionLogs:c,userName:l,showMetaChips:m=!1,scrollToBottomRequestNonce:p,isInputActive:u=!0}){var G,A;const f=o.useRef(new Map),v=tr();Zs("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:c.length,isSendingChat:n});const S=nt.useMemo(()=>Rs(e),[e.status,e.connectionState]),T=o.useMemo(()=>Ld(e,s),[e,s]),d=Vd({isCliLike:T.isCli||T.isAcp}),b=eu(e,{enabled:!!e.sessionId}),[N,h]=o.useState(d),w=e.tabKey,_=b.historyMessages,y=b.hasMoreHistory,j=b.historyError,k=Hd(b.liveMessages,e.messages);o.useEffect(()=>{h(d)},[d,w]);const g=Math.max(0,k.length-N),x=ta(e),$=er(e),[I,M]=o.useState(!1);o.useEffect(()=>{const D=T.targetEntry;$&&(!D||D.providerControls===void 0||D.controlValues===void 0)&&v($,{minFreshMs:3e4}).catch(()=>{})},[$,T.isAcp,(G=T.targetEntry)==null?void 0:G.providerControls,(A=T.targetEntry)==null?void 0:A.controlValues,v]);const L=o.useCallback(async()=>{if(!I){if(k.length>N){h(D=>Math.min(k.length,D+su));return}M(!0);try{await b.loadHistoryPage()}finally{M(!1)}}},[b,I,k.length,N]),{allMessages:O,receivedAtMap:R}=o.useMemo(()=>{const D=g>0?k.slice(-N):k;if(_.length===0){const xe=Va(Qs(D)),Re={};return xe.forEach((ie,Ie)=>{const te=`${e.tabKey}:${ys(ie,Ie)}`;let ce=Ut(ie)||f.current.get(te)||0;ce||(ce=Date.now(),f.current.set(te,ce)),Re[ys(ie,Ie)]=ce}),{allMessages:xe,receivedAtMap:Re}}const B=Ud(_,D),W=Va(Qs([...B,...D])),X={};return W.forEach((xe,Re)=>{const ie=`${e.tabKey}:${ys(xe,Re)}`;let Ie=Ut(xe)||f.current.get(ie)||0;Ie||(Ie=Date.now(),f.current.set(ie,Ie)),X[ys(xe,Re)]=Ie}),{allMessages:W,receivedAtMap:X}},[e.tabKey,g,_,k,N]),C=o.useMemo(()=>c.filter(D=>D.routeId===e.tabKey).sort((D,B)=>D.timestamp-B.timestamp),[c,e.tabKey]),U=o.useMemo(()=>{if(k.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((S.isGenerating||e.status==="streaming")&&M(!1),e.status==="not_monitored")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(Ys,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),t.jsx("button",{onClick:a,disabled:i,className:"btn btn-primary",children:i?"⌛ Switching...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ss,{size:14})," Open ",x," 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")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(Uo,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),t.jsx("button",{onClick:a,disabled:i,className:"btn btn-primary",children:i?"⌛ Opening...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ss,{size:14})," Open ",x," 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"&&!I)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,a,i,I,k.length,x,S.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[m&&t.jsx(ci,{conversation:e,className:"chat-pane-meta-row"}),t.jsx(Ll,{messages:O,actionLogs:C,agentName:us(e)||x||"Agent",userName:l,isCliMode:T.isCli||T.isAcp,isWorking:S.isGenerating,contextKey:e.tabKey,receivedAtMap:R,onLoadMore:L,isLoadingMore:I,hasMoreHistory:y,hiddenLiveCount:g,loadError:j??void 0,emptyState:U,scrollToBottomRequestNonce:p}),u&&!T.isCliTerminal&&(()=>{var D,B;return t.jsx(Cd,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:T.providerType,displayLabel:T.displayLabel,controls:(D=T.targetEntry)==null?void 0:D.providerControls,controlValues:(B=T.targetEntry)==null?void 0:B.controlValues})})(),!T.isCliTerminal&&t.jsx(Id,{contextKey:e.tabKey,panelLabel:x,isSending:n,onSend:r,isActive:u})]})}let mi=cs;function pi(){return mi()}class ru{constructor(){qe(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 fi=new ru;class nu{sendPtyInput(s,r,n){return!1}sendPtyResize(s,r,n,a){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 pt=new nu;function au(e){e.dashboardWS&&(fi=e.dashboardWS),e.connectionManager&&(pt=e.connectionManager),e.useDaemonsHook&&(mi=e.useDaemonsHook)}function lt(e){return ta(e)}function ms(e){return ii(e).join(" · ")}function hi(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=Ns(s==null?void 0:s.content);return r||(e.title?e.title:ms(e)||"No messages yet")}function xi(e,s){const{isReconnecting:r,isConnecting:n}=Rs(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function ou(e,s){const r=["Chat",...ii(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function ts(e){return xi(e)||ms(e)}function iu(e){return`${lt(e)} · ${hi(e)}`}function cu(e){const s=Rr(e),r=s?at(s):us(e);return`${lt(e)} — ${r||"Agent"}`}function lu(e){return us(e)||"CLI"}function bi(e){return e.title||us(e)||e.routeId}function gi(e){return e?`Remote · ${lt(e)||e.workspaceName||"Session"}`:"Remote"}function du({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,isVisible:i=!0}){var D;const{ides:c}=cs(),l=o.useRef(null),{sendCommand:m,sendData:p}=At(),[u,f]=o.useState(""),[v,S]=o.useState(!1),[T,d]=o.useState(1),b=o.useRef(!1),N=o.useRef(0),h=o.useRef(!1),w=o.useRef(""),_=o.useRef(null),y=o.useRef(!1),j=o.useRef(null),k=e.tabKey,g=e.sessionId||"",x=e.daemonId||((D=e.routeId)==null?void 0:D.split(":")[0])||e.routeId||"",$=c.find(B=>B.id===x&&B.type==="adhdev-daemon"),I=($==null?void 0:$.terminalSizingMode)==="fit"?"fit":"measured",M=.6,L=1.15,O=()=>{if(typeof window>"u")return 1;const B=window.innerWidth||0;return B<=360?.68:B<=390?.74:B<=430?.82:B<=480?.9:1},R=()=>{var B,W;N.current=0,h.current=!1,w.current="",_.current=null,y.current=!1,j.current!==null&&(cancelAnimationFrame(j.current),j.current=null),S(!1),(W=(B=r.current)==null?void 0:B.reset)==null||W.call(B)},C=()=>{var B,W;N.current=0,h.current=!1,w.current="",_.current=null,y.current=!1,j.current!==null&&(cancelAnimationFrame(j.current),j.current=null),S(!0),(W=(B=r.current)==null?void 0:B.reset)==null||W.call(B)},U=()=>{var W;if(j.current=null,!i)return;const B=w.current;B&&(w.current="",(W=r.current)==null||W.write(B))},G=B=>{B&&(w.current+=B,i&&j.current===null&&(j.current=requestAnimationFrame(U)))},A=(B,W=0,X,xe)=>{var Re,ie,Ie,te,ce;W>0&&N.current>=W||W===0&&h.current||(N.current=W,S(!0),typeof X=="number"&&typeof xe=="number"&&X>0&&xe>0&&((ie=(Re=r.current)==null?void 0:Re.resize)==null||ie.call(Re,X,xe)),(te=(Ie=r.current)==null?void 0:Ie.reset)==null||te.call(Ie),B&&((ce=r.current)==null||ce.write(B)))};return o.useEffect(()=>{R()},[g]),o.useEffect(()=>{var W;if(!g)return;const B=((W=pt.onRuntimeEvent)==null?void 0:W.call(pt,g,X=>{if(!(!X||X.sessionId!==g)){if(X.type==="runtime_snapshot"){if(!i){_.current={text:X.text||"",seq:X.seq||0,cols:X.cols,rows:X.rows};return}A(X.text||"",X.seq||0,X.cols,X.rows);return}if(X.type==="session_output"){h.current=!0,typeof X.seq=="number"&&(N.current=Math.max(N.current,X.seq)),v||S(!0),typeof X.data=="string"&&G(X.data);return}if(X.type==="session_cleared"){if(!i){y.current=!0,w.current="",_.current=null;return}C()}}}))||(()=>{});return()=>{B()}},[x,g,r,i,v]),o.useEffect(()=>{var W,X,xe;if(!g)return;x&&((W=pt.getState)==null?void 0:W.call(pt,x))==="connected"&&(S(!0),(X=pt.requestRuntimeSnapshot)==null||X.call(pt,x,g).catch(()=>{}));const B=(xe=pt.onStateChange)==null?void 0:xe.call(pt,(Re,ie)=>{var Ie;Re!==x||ie!=="connected"||(S(!0),(Ie=pt.requestRuntimeSnapshot)==null||Ie.call(pt,x,g).catch(()=>{}))});return()=>{B==null||B()}},[x,g,r]),o.useEffect(()=>{s&&R()},[s,k,r]),o.useEffect(()=>{f("")},[e.tabKey]),o.useEffect(()=>{const B=()=>{b.current||d(O())};return B(),window.addEventListener("resize",B),()=>window.removeEventListener("resize",B)},[]),o.useEffect(()=>{var W;if(!i){(W=l.current)==null||W.blur();return}y.current&&(y.current=!1,C());const B=_.current;B&&(_.current=null,A(B.text,B.seq,B.cols,B.rows)),w.current&&j.current===null&&(j.current=requestAnimationFrame(U)),requestAnimationFrame(()=>{var X;(X=r.current)==null||X.bumpResize()})},[i]),o.useEffect(()=>()=>{j.current!==null&&(cancelAnimationFrame(j.current),j.current=null)},[]),o.useEffect(()=>{const B=W=>{var xe;const X=W.detail;X!=null&&X.sessionId&&X.sessionId!==g||v&&((xe=r.current)==null||xe.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",B),()=>{window.removeEventListener("adhdev:fit-cli-terminal",B)}},[v,g,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(B=>Math.max(M,Number((B-.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(B=>Math.min(L,Number((B+.1).toFixed(2))))},title:"Increase terminal viewport",children:"+"})]}),t.jsx("div",{className:"w-full h-full overflow-auto rounded-lg",children:t.jsx("div",{style:{width:`${100/T}%`,height:`${100/T}%`,transform:`scale(${T})`,transformOrigin:"top left"},children:t.jsx(qo,{ref:r,readOnly:!v||!i,sizingMode:I,onInput:B=>{v&&(p!=null&&p(x,{type:"pty_input",sessionId:g,targetSessionId:g,data:B})||m(x,"pty_input",{targetSessionId:g,data:B}).catch(console.error))}})})}),!v&&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.jsx("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:l,type:"text",placeholder:`Send message to ${lt(e)}...`,value:u,disabled:!v||!i||a,onChange:B=>f(B.target.value),onPaste:B=>{const W=B.clipboardData.getData("text");W&&f(X=>X+W),B.preventDefault()},onKeyDown:B=>{if(B.key!=="Enter")return;if(B.nativeEvent.isComposing){B.preventDefault();return}B.preventDefault();const W=u.trim();!v||!W||a||(f(""),n(W))},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 B=u.trim();!v||!B||a||(f(""),n(B))},disabled:!v||!i||!u.trim()||a,className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${u.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:u.trim()&&!a?{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:u.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})]})}function uu({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 mu({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",m=()=>{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:m,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 na({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(Hr,{size:n}):t.jsx(Ht,{size:n})})}function Xa({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Qa({notification:e,shortcutIndex:s,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=Fr(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:m=>{m.stopPropagation(),n()},children:"Mark read"}):t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:m=>{m.stopPropagation(),a()},children:"Mark unread"}),t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:m=>{m.stopPropagation(),i()},children:"Delete"})]})]})}function pu({activeConv:e,agentCount:s,wsStatus:r,isConnected:n,conversations:a,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:m,onSetCliViewMode:p,onHideConversation:u,hiddenConversations:f=[],onShowConversation:v,onShowAllHidden:S,onResetPanelsToMain:T,inboxOpen:d,onInboxOpenChange:b,hiddenOpen:N,onHiddenOpenChange:h,onOpenNewSession:w,actionShortcuts:_,notifications:y,notificationUnreadCount:j,onOpenNotification:k,onMarkNotificationRead:g,onMarkNotificationUnread:x,onDeleteNotification:$}){const{ides:I,p2pStates:M={}}=cs(),L=!!e&&et(e)&&!Ye(e),O=!!e&&Ye(e),R=m||(e?ai(e)?"terminal":"chat":null),[C,U]=o.useState(!1),G=o.useRef(null),A=o.useRef(null),D=n?"#22c55e":r==="connected"?"#eab308":"#ef4444",B=n?"0 0 4px #22c55e80":r==="connected"?"0 0 4px #eab30880":"0 0 4px #ef444480",W=I.filter(F=>F.type==="adhdev-daemon"),X=Object.values(M),xe=X.filter(F=>F==="connected").length,Re=X.filter(F=>F==="connecting"||F==="new"||F==="checking").length,Ie=r!=="connected"||W.length===0?null:Re>0&&xe===0?"P2P connecting...":xe>0&&s===0?"Waiting for IDE...":null,te=o.useMemo(()=>y.filter(F=>!F.readAt),[y]),ce=o.useMemo(()=>y.filter(F=>!!F.readAt),[y]),oe=o.useMemo(()=>te.slice(0,9),[te]),ye=j;o.useEffect(()=>{if(!d)return;const F=be=>{var se;(se=G.current)!=null&&se.contains(be.target)||b(!1)};return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[d,b]),o.useEffect(()=>{if(!N)return;const F=be=>{var se;(se=A.current)!=null&&se.contains(be.target)||h(!1)};return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[N,h]),o.useEffect(()=>{if(!N&&!d)return;const F=be=>{if(!be.altKey)return;const se=be.code.match(/^Digit([1-9])$/);if(!se)return;const pe=Number(se[1])-1,J=N?f[pe]:void 0,le=d?oe[pe]:void 0;if(!(!J&&!le)){if(be.preventDefault(),be.stopPropagation(),J){v==null||v(J),h(!1);return}le&&(k(le),b(!1))}};return window.addEventListener("keydown",F,!0),()=>window.removeEventListener("keydown",F,!0)},[f,N,d,oe,h,b,k,v]);const ae=F=>{if(!F)return;const be=a.find(se=>se.tabKey===F);be&&(u==null||u(be))};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(Ht,{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:B}})})]}),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:B}}),Ie&&t.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",Ie]}),w&&t.jsx("button",{type:"button",onClick:w,className:"btn btn-secondary btn-sm ml-2",title:"Start or recover a session","aria-label":"Start or recover a session",children:t.jsx(ll,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(L||O||!Ye(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:ms(e)||lt(e),children:lt(e)}),(L||O)&&l&&t.jsxs(t.Fragment,{children:[L&&p&&R&&t.jsx(na,{mode:R,onChange:p,compact:!0}),t.jsx("button",{onClick:()=>l(e),className:"btn btn-secondary btn-sm",title:O?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:t.jsx(kt,{size:14})})]}),!Ye(e)&&t.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:t.jsx(Yn,{size:14})}),!L&&!Ye(e)&&t.jsx("button",{onClick:c,className:"btn btn-secondary btn-sm",title:"Remote Control",children:t.jsx(It,{size:14})})]}),t.jsxs("div",{className:"dashboard-header-inbox",ref:G,children:[t.jsxs("div",{className:`dashboard-header-hidden${C?" is-drop-target":""}`,ref:A,onDragEnter:F=>{F.dataTransfer.types.includes("text/tab-key")&&(F.preventDefault(),U(!0))},onDragOver:F=>{F.dataTransfer.types.includes("text/tab-key")&&(F.preventDefault(),F.dataTransfer.dropEffect="move",U(!0))},onDragLeave:F=>{F.currentTarget.contains(F.relatedTarget)||U(!1)},onDrop:F=>{const be=F.dataTransfer.getData("text/tab-key");F.preventDefault(),U(!1),ae(be)},children:[t.jsxs("button",{type:"button",onClick:()=>h(!N),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(Fo,{size:16}),f.length>0&&t.jsx("span",{className:"dashboard-header-hidden-badge",children:f.length})]}),N&&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(Xa,{value:_==null?void 0:_.toggleHiddenTabs})]}),t.jsxs("div",{className:"dashboard-header-hidden-actions",children:[T&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:T,children:"Reset panels"}),f.length>0&&S&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{S(),h(!1)},children:"Restore all"})]})]}),e&&u&&t.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>u(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(Xa,{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(F=>t.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{v==null||v(F),h(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:lt(F)}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[f.indexOf(F)<9?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",f.indexOf(F)+1]}):null,ms(F)]})]},F.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(Ur,{size:16}),ye>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:ye})]}),d&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[te.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),te.map(F=>t.jsx(Qa,{notification:F,shortcutIndex:oe.indexOf(F)>=0?oe.indexOf(F)+1:void 0,onOpen:()=>k(F),onMarkRead:()=>g(F.id),onMarkUnread:()=>x(F.id),onDelete:()=>$(F.id)},F.id))]}),ce.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),ce.map(F=>t.jsx(Qa,{notification:F,onOpen:()=>k(F),onMarkRead:()=>g(F.id),onMarkUnread:()=>x(F.id),onDelete:()=>$(F.id)},F.id))]}),y.length===0&&t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function gt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function fu(e,s){return String(e||"")!==String(s||"")}function hu(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(m=>String(m||"").toLowerCase()).join(`
|
|
31
31
|
`).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!ei(c.summaryMetadata).map(m=>m.toLowerCase()).join(`
|
|
32
|
-
`).includes(a)))}function xu(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 yi(e,s={}){return xu(hu(e,s),s.sortMode||"recent")}function Dr(e){return e?"Resume saved history":"Start fresh"}function aa(e){return e?"Resuming saved history…":"Starting fresh…"}function bu(){return"Start fresh"}function vi(e,s=!1){return e==="cli"?Dr(s):e==="ide"?"Start IDE":"Start ACP session"}function wi(e,s=!1){return e==="cli"?aa(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function gu(){return"Recover hosted runtime"}function yu(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function vu(){return"Open saved history"}function wu(){return"Saved History"}function oa(){return"Use saved history when you want continuity in the same provider conversation."}function ju(){return"No saved history found yet."}function ku(){return"Refresh saved history"}function Su(){return"Refreshing saved history…"}function ss(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function rs(e){return e==="start-fresh"?"Review the provider and target folder before starting fresh.":e==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Ts(e){return e==="start-fresh"?"Start fresh":"Restart"}function Ms(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function ia(e){return`Resume saved history with ${e}?`}function ca(){return"Review or change the target workspace before resuming saved history."}function Nu(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 la({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:m,onClose:p,onNewChat:u,onSwitchSession:f,onRefreshHistory:v,onResumeSavedSession:S}){var g;const T=s.find(x=>x.id===e.routeId),d=(T==null?void 0:T.chats)||[],b=(g=T==null?void 0:T.activeChat)==null?void 0:g.id,N=et(e)&&!Ye(e),[h,w]=o.useState(()=>gt()),_=l||h,y=x=>{if(m){m(x);return}w(x)},j=o.useMemo(()=>yi(a,{textQuery:_.textQuery,workspaceQuery:_.workspaceQuery,modelQuery:_.modelQuery,resumableOnly:_.resumableOnly,sortMode:_.sortMode}),[_.modelQuery,_.resumableOnly,_.sortMode,_.textQuery,_.workspaceQuery,a]),k=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:N?wu():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:cu(e)}),N&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:oa()})]}),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(kt,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!N&&t.jsx("button",{onClick:u,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),N?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=>y({..._,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=>y({..._,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=>y({..._,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=>y({..._,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=>y({..._,resumableOnly:x.target.checked})}),"Resume-ready only"]})]}),j.map(x=>{const $=e.providerSessionId===x.providerSessionId,I=$||!x.canResume||!!c;return t.jsxs("button",{type:"button",onClick:()=>{I||!S||S(x)},disabled:I,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${$?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${I?"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 ${$?"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:Nu(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",ds(x.summaryMetadata)?` · ${ds(x.summaryMetadata)}`:"",x.messageCount>0?` · ${x.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:$?"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)),(N&&!i&&j.length===0||!N&&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(pl,{size:32})}),t.jsx("div",{className:"text-[13px]",children:N?a.length>0?"No saved history matches these filters.":ju():"No recent chat sessions found."})]}),N&&i&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:Su()})})]}),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:v,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(_s,{size:13})," ",N?ku():"Refresh History"]})})})]})]});return typeof document>"u"?k:qs.createPortal(k,document.body)}const Ja={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 ji({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=Ja[n.type]||Ja.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(kt,{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 Cu=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Iu(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function Au(e){return e.sessionId||e.instanceId||e.agentType}function dn(e,s){return e||s}function Za(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 ki(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=Ct(r,{fallbackId:r.id}));return s}function Si(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 da(e,s,r={}){return Tu(e,s,Si(e,r))}function Tu(e,s,r={}){var S,T,d,b,N,h;const n=[],a=r.machineName,i=r.connectionState,c=Iu(e),l=Yl(e.type,{agentName:e.cliName}),m=et(e)||Ye(e)?l:at(e.type),p=Array.isArray(e.childSessions)?e.childSessions.map(w=>{var _,y;return{sessionId:w.id,instanceId:w.id,providerSessionId:w.providerSessionId,transport:w.transport,agentType:w.providerType,agentName:w.providerName||at(w.providerType),status:w.status,title:w.title,lastMessagePreview:w.lastMessagePreview,lastMessageRole:w.lastMessageRole,lastMessageAt:w.lastMessageAt,lastMessageHash:w.lastMessageHash,messages:((_=w.activeChat)==null?void 0:_.messages)||[],activeModal:((y=w.activeChat)==null?void 0:y.activeModal)||void 0,unread:w.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,inboxBucket:w.inboxBucket,surfaceHidden:w.surfaceHidden}}):[],u=Cu(e),f=e.activeChat||{title:""},v=f.title&&String(f.title).trim()?String(f.title).trim():"";if(u){const w=e.sessionId||e.instanceId,_=l,y=(S=e.activeChat)==null?void 0:S.activeModal,j=y&&Array.isArray(y.buttons)&&y.buttons.length>0,k=jt((T=e.activeChat)==null?void 0:T.status,{activeModal:(d=e.activeChat)==null?void 0:d.activeModal})||jt((N=(b=e.agents)==null?void 0:b[0])==null?void 0:N.status)||"idle",g=e.activeChat||{title:"",messages:[]};let x=g.title&&String(g.title).trim()?String(g.title).trim():"";const $=(h=e.activeChat)==null?void 0:h.id,I=e.chats;if($&&Array.isArray(I)&&I.length>0){const U=I.find(G=>G.id===$||G.id&&String(G.id)===String($));U!=null&&U.title&&String(U.title).trim()&&(x=String(U.title).trim())}const M=(et(e)||Ye(e),e.type),L=(et(e)||Ye(e))&&Ka(x,_,M)?"":x,O=g.messages||[],R=Za(s,[e.id,w]),C=Ga(O,R);n.push({routeId:e.id,sessionId:w,providerSessionId:e.providerSessionId,nativeSessionId:w,transport:e.transport,daemonId:e.daemonId||void 0,mode:et(e)?e.mode||"terminal":"chat",agentName:_,agentType:M,status:k,title:L,messages:[...O,...C],resume:e.resume,hostIdeType:!et(e)&&!Ye(e)?e.type:void 0,workspaceName:c,displayPrimary:c||L||(et(e)?e.mode==="chat"?_:"Terminal":_),displaySecondary:m,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:j?y.buttons:void 0,modalMessage:j?y.message:void 0,streamSource:"native",tabKey:dn(w,e.id),machineName:a,connectionState:i})}if(u&&(et(e)||Ye(e)))return n;for(const w of p){const _=w.activeModal&&Array.isArray(w.activeModal.buttons)&&w.activeModal.buttons.length>0,y=Xl(w),j=Au(w),k=`${e.id}:${j}`,g=w.title&&String(w.title).trim()||"",x=Ka(g,w.agentName,w.agentType)?"":g,$=w.messages||[],I=Za(s,[k,w.sessionId,w.instanceId]),M=Ga($,I);(w.transport==="cdp-webview"||w.sessionId||w.providerSessionId||$.length>0||M.length>0||_||x||!["idle","panel_hidden","disconnected","not_monitored"].includes(y))&&n.push({routeId:e.id,sessionId:w.sessionId||w.instanceId,providerSessionId:w.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:w.transport||"cdp-webview",daemonId:e.daemonId||void 0,mode:"chat",agentName:w.agentName,agentType:w.agentType,status:y,title:x,messages:[...$,...M],hostIdeType:e.type,workspaceName:c,displayPrimary:c||v||x||m,displaySecondary:`${m} · ${w.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:w.lastMessagePreview,lastMessageRole:w.lastMessageRole,lastMessageAt:w.lastMessageAt,lastMessageHash:w.lastMessageHash,lastUpdated:w.lastUpdated||e.lastUpdated,modalButtons:_?w.activeModal.buttons:void 0,modalMessage:_?w.activeModal.message:void 0,streamSource:"agent-stream",tabKey:dn(w.sessionId||w.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,mode:"chat",agentName:l,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:c,displayPrimary:c||m,displaySecondary:m,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:dn(e.sessionId||e.instanceId,e.id),connectionState:i}),n}function Mu(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 Lu(e,s){const r=Mu(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Ni=[{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:"🏄"}],Ci=[{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:"🧩"}],Ii=[{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:"🟠"}],_u=Ni,Ru=Ci,Pu=Ii;function ps(...e){return Bc(Kc(e))}function Du({icon:e,title:s,subtitle:r,badge:n,actions:a,className:i}){return t.jsxs("div",{className:ps("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 Ai({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(Du,{icon:e,title:s,subtitle:r,badge:n,actions:a}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:ps("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}function Pt({title:e,icon:s,description:r,accentColor:n,className:a,children:i}){return t.jsxs("div",{className:ps("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 Ti({icon:e,title:s,description:r,action:n,className:a}){return t.jsxs("div",{className:ps("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 Eu={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"},$u={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Bu({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:ps("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Eu[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:$u[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 Ku={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"},Wu={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Ou({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:ps("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Ku[e],r),children:[t.jsx("span",{className:ps("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Wu[e])}),n]})}const En="adhdev:themechange";function Hu(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function bs(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function gs(e){return e==="system"?Hu():e}function Mi(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Nr(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(En,{detail:{preference:e,theme:s}}))}function Uu(){const e=bs(),s=gs(e);Mi(s),Nr(e,s)}function ua(){const[e,s]=o.useState(bs),[r,n]=o.useState(()=>gs(bs()));o.useEffect(()=>{Mi(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=m=>{if(e==="system"){const p=m.matches?"light":"dark";n(p),Nr("system",p)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=m=>{const p=m.detail||{},u=p.preference,f=p.theme;s(u==="dark"||u==="light"||u==="system"?u:bs()),n(f==="dark"||f==="light"?f:gs(bs()))},l=m=>{if(m.key!=="theme")return;const p=bs(),u=gs(p);s(p),n(u)};return window.addEventListener(En,c),window.addEventListener("storage",l),()=>{window.removeEventListener(En,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=gs(c);s(c),n(l);try{localStorage.setItem("theme",c)}catch{}Nr(c,l)},[]),i=o.useCallback(()=>{s(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",m=gs(l);n(m);try{localStorage.setItem("theme",l)}catch{}return Nr(l,m),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const eo={dark:"Dark",light:"Light",system:"System"};function Fu({collapsed:e}){const{preference:s,cycleTheme:r}=ua(),n=s==="dark"?t.jsx(hl,{size:16}):s==="light"?t.jsx(fl,{size:16}):t.jsx(xl,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${eo[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:eo[s]})]})}function es({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 zu({onPrefChange:e}){const[s,r]=od(),n=(a,i)=>{r({[a]:i}),e==null||e(a,i)};return t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ur,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:a=>n("globalEnabled",a)}),s.globalEnabled&&t.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&t.jsx(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(It,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:a=>n("browserNotifications",a)}),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(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(bl,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:a=>n("completionAlert",a)}),t.jsx(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(gl,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:a=>n("approvalAlert",a)}),t.jsx(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ys,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:a=>n("disconnectAlert",a)})]}),!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 Er(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function Vu(e,s){const r=Er(e),n=Er(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 Li(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function zs(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||Vu(r,s)>=0)return!1;const n=Er(r),a=Er(s);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Gu(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function un(e,s){return e instanceof Error?e.message:s}function qu({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(Ti,{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(Xu,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function to({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 qs.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 Yu(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[..._u,...Ru,...Pu].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 Xu({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var O,R;const[i,c]=o.useState("idle"),[l,m]=o.useState(""),[p,u]=o.useState(null),[f,v]=o.useState("idle"),[S,T]=o.useState(""),d=e.version||null,b=((O=e.machine)==null?void 0:O.platform)||((R=e.system)==null?void 0:R.platform)||"",N=Ct(e,{fallbackId:e.id}),h=b==="win32"?"🪟":b==="darwin"?"🍎":"🐧",w=s.filter(C=>C.daemonId===e.id&&C.transport==="cdp-page"),_=s.filter(C=>C.daemonId===e.id&&C.transport==="pty"),y=s.filter(C=>C.daemonId===e.id&&C.transport==="acp"),j=e.p2p,k=async()=>{if(r){c("upgrading"),m("Starting upgrade...");try{const C=Gu(await r(e.id,"daemon_upgrade",{}));C.alreadyLatest?(c("done"),m(`Already on v${C.version||"latest"}.`)):C.upgraded||C.success?(c("done"),m(`Upgrade to v${C.version||"latest"} started. Daemon is restarting...`)):(c("error"),m(C.error||"Upgrade failed"))}catch(C){c("error"),m(un(C,"Connection lost during upgrade"))}}},g=async()=>{if(u(null),!!n){v("loading");try{await n(e.id),v("done"),T("Machine disconnected.")}catch(C){v("error"),T(un(C,"Failed to disconnect"))}}},x=async()=>{if(u(null),!!a){v("loading");try{await a(e.id),v("done"),T("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(C){v("error"),T(un(C,"Failed to revoke token"))}}},$="0.8.68",I=Li(e,$),M=zs(e,$),L=w.length+_.length+y.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:N}),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] ${I?"":"bg-bg-secondary"}`,style:I?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",d,!I&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&I&&t.jsx("button",{onClick:k,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${$}`,children:i==="upgrading"?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${M?"↑ Update now":`↑ Update${` to v${$}`}`}`}),n&&t.jsx("button",{onClick:()=>u("disconnect"),disabled:f==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&t.jsx("button",{onClick:()=>u("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),t.jsx(Ou,{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:[j&&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 ${j.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${j.state==="connecting"||j.state==="new"?"animate-pulse":""}`,style:j.state==="connecting"||j.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",j.state==="connected"?"connected":j.state==="connecting"||j.state==="new"?"connecting...":j.state||"off"]}),j.peers!==void 0&&j.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",j.peers," peer",j.peers!==1?"s":"",")"]})]}),j&&L>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),L>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[w.map(C=>{const U=Yu(C.type),G=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:U.icon}),t.jsx("span",{children:U.name}),G!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${G?"bg-green-400":"animate-pulse"}`,style:G?void 0:{background:"var(--status-warning)"},title:G?"CDP connected":"CDP connecting..."})]},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)),y.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||S)&&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:S||l})]}),p==="disconnect"&&t.jsx(to,{title:"🔌 Disconnect Machine",message:`Disconnect "${N}" from ADHDev?
|
|
32
|
+
`).includes(a)))}function xu(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 yi(e,s={}){return xu(hu(e,s),s.sortMode||"recent")}function Dr(e){return e?"Resume saved history":"Start fresh"}function aa(e){return e?"Resuming saved history…":"Starting fresh…"}function bu(){return"Start fresh"}function vi(e,s=!1){return e==="cli"?Dr(s):e==="ide"?"Start IDE":"Start ACP session"}function wi(e,s=!1){return e==="cli"?aa(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function gu(){return"Recover hosted runtime"}function yu(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function vu(){return"Open saved history"}function wu(){return"Saved History"}function oa(){return"Use saved history when you want continuity in the same provider conversation."}function ju(){return"No saved history found yet."}function ku(){return"Refresh saved history"}function Su(){return"Refreshing saved history…"}function ss(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function rs(e){return e==="start-fresh"?"Review the provider and target folder before starting fresh.":e==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Ts(e){return e==="start-fresh"?"Start fresh":"Restart"}function Ms(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function ia(e){return`Resume saved history with ${e}?`}function ca(){return"Review or change the target workspace before resuming saved history."}function Nu(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 la({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:m,onClose:p,onNewChat:u,onSwitchSession:f,onRefreshHistory:v,onResumeSavedSession:S}){var g;const T=s.find(x=>x.id===e.routeId),d=(T==null?void 0:T.chats)||[],b=(g=T==null?void 0:T.activeChat)==null?void 0:g.id,N=et(e)&&!Ye(e),[h,w]=o.useState(()=>gt()),_=l||h,y=x=>{if(m){m(x);return}w(x)},j=o.useMemo(()=>yi(a,{textQuery:_.textQuery,workspaceQuery:_.workspaceQuery,modelQuery:_.modelQuery,resumableOnly:_.resumableOnly,sortMode:_.sortMode}),[_.modelQuery,_.resumableOnly,_.sortMode,_.textQuery,_.workspaceQuery,a]),k=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:N?wu():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:cu(e)}),N&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:oa()})]}),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(kt,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!N&&t.jsx("button",{onClick:u,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),N?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=>y({..._,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=>y({..._,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=>y({..._,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=>y({..._,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=>y({..._,resumableOnly:x.target.checked})}),"Resume-ready only"]})]}),j.map(x=>{const $=e.providerSessionId===x.providerSessionId,I=$||!x.canResume||!!c;return t.jsxs("button",{type:"button",onClick:()=>{I||!S||S(x)},disabled:I,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${$?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${I?"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 ${$?"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:Nu(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",ds(x.summaryMetadata)?` · ${ds(x.summaryMetadata)}`:"",x.messageCount>0?` · ${x.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:$?"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)),(N&&!i&&j.length===0||!N&&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(pl,{size:32})}),t.jsx("div",{className:"text-[13px]",children:N?a.length>0?"No saved history matches these filters.":ju():"No recent chat sessions found."})]}),N&&i&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:Su()})})]}),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:v,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(_s,{size:13})," ",N?ku():"Refresh History"]})})})]})]});return typeof document>"u"?k:qs.createPortal(k,document.body)}const Ja={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 ji({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=Ja[n.type]||Ja.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(kt,{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 Cu=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Iu(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function Au(e){return e.sessionId||e.instanceId||e.agentType}function dn(e,s){return e||s}function Za(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 ki(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=Ct(r,{fallbackId:r.id}));return s}function Si(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 da(e,s,r={}){return Tu(e,s,Si(e,r))}function Tu(e,s,r={}){var S,T,d,b,N,h;const n=[],a=r.machineName,i=r.connectionState,c=Iu(e),l=Yl(e.type,{agentName:e.cliName}),m=et(e)||Ye(e)?l:at(e.type),p=Array.isArray(e.childSessions)?e.childSessions.map(w=>{var _,y;return{sessionId:w.id,instanceId:w.id,providerSessionId:w.providerSessionId,transport:w.transport,agentType:w.providerType,agentName:w.providerName||at(w.providerType),status:w.status,title:w.title,lastMessagePreview:w.lastMessagePreview,lastMessageRole:w.lastMessageRole,lastMessageAt:w.lastMessageAt,lastMessageHash:w.lastMessageHash,messages:((_=w.activeChat)==null?void 0:_.messages)||[],activeModal:((y=w.activeChat)==null?void 0:y.activeModal)||void 0,unread:w.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,inboxBucket:w.inboxBucket,surfaceHidden:w.surfaceHidden}}):[],u=Cu(e),f=e.activeChat||{title:""},v=f.title&&String(f.title).trim()?String(f.title).trim():"";if(u){const w=e.sessionId||e.instanceId,_=l,y=(S=e.activeChat)==null?void 0:S.activeModal,j=y&&Array.isArray(y.buttons)&&y.buttons.length>0,k=jt((T=e.activeChat)==null?void 0:T.status,{activeModal:(d=e.activeChat)==null?void 0:d.activeModal})||jt((N=(b=e.agents)==null?void 0:b[0])==null?void 0:N.status)||"idle",g=e.activeChat||{title:"",messages:[]};let x=g.title&&String(g.title).trim()?String(g.title).trim():"";const $=(h=e.activeChat)==null?void 0:h.id,I=e.chats;if($&&Array.isArray(I)&&I.length>0){const U=I.find(G=>G.id===$||G.id&&String(G.id)===String($));U!=null&&U.title&&String(U.title).trim()&&(x=String(U.title).trim())}const M=(et(e)||Ye(e),e.type),L=(et(e)||Ye(e))&&Ka(x,_,M)?"":x,O=g.messages||[],R=Za(s,[e.id,w]),C=Ga(O,R);n.push({routeId:e.id,sessionId:w,providerSessionId:e.providerSessionId,nativeSessionId:w,transport:e.transport,daemonId:e.daemonId||void 0,mode:et(e)?e.mode||"terminal":"chat",agentName:_,agentType:M,status:k,title:L,messages:[...O,...C],resume:e.resume,hostIdeType:!et(e)&&!Ye(e)?e.type:void 0,workspaceName:c,displayPrimary:c||L||(et(e)?e.mode==="chat"?_:"Terminal":_),displaySecondary:m,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:j?y.buttons:void 0,modalMessage:j?y.message:void 0,streamSource:"native",tabKey:dn(w,e.id),machineName:a,connectionState:i})}if(u&&(et(e)||Ye(e)))return n;for(const w of p){const _=w.activeModal&&Array.isArray(w.activeModal.buttons)&&w.activeModal.buttons.length>0,y=Xl(w),j=Au(w),k=`${e.id}:${j}`,g=w.title&&String(w.title).trim()||"",x=Ka(g,w.agentName,w.agentType)?"":g,$=w.messages||[],I=Za(s,[k,w.sessionId,w.instanceId]),M=Ga($,I);(w.transport==="cdp-webview"||w.sessionId||w.providerSessionId||$.length>0||M.length>0||_||x||!["idle","panel_hidden","disconnected","not_monitored"].includes(y))&&n.push({routeId:e.id,sessionId:w.sessionId||w.instanceId,providerSessionId:w.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:w.transport||"cdp-webview",daemonId:e.daemonId||void 0,mode:"chat",agentName:w.agentName,agentType:w.agentType,status:y,title:x,messages:[...$,...M],hostIdeType:e.type,workspaceName:c,displayPrimary:c||v||x||m,displaySecondary:`${m} · ${w.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:w.lastMessagePreview,lastMessageRole:w.lastMessageRole,lastMessageAt:w.lastMessageAt,lastMessageHash:w.lastMessageHash,lastUpdated:w.lastUpdated||e.lastUpdated,modalButtons:_?w.activeModal.buttons:void 0,modalMessage:_?w.activeModal.message:void 0,streamSource:"agent-stream",tabKey:dn(w.sessionId||w.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,mode:"chat",agentName:l,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:c,displayPrimary:c||m,displaySecondary:m,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:dn(e.sessionId||e.instanceId,e.id),connectionState:i}),n}function Mu(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 Lu(e,s){const r=Mu(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Ni=[{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:"🏄"}],Ci=[{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:"🧩"}],Ii=[{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:"🟠"}],_u=Ni,Ru=Ci,Pu=Ii;function ps(...e){return Bc(Kc(e))}function Du({icon:e,title:s,subtitle:r,badge:n,actions:a,className:i}){return t.jsxs("div",{className:ps("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 Ai({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(Du,{icon:e,title:s,subtitle:r,badge:n,actions:a}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:ps("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}function Pt({title:e,icon:s,description:r,accentColor:n,className:a,children:i}){return t.jsxs("div",{className:ps("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 Ti({icon:e,title:s,description:r,action:n,className:a}){return t.jsxs("div",{className:ps("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 Eu={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"},$u={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Bu({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:ps("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Eu[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:$u[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 Ku={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"},Wu={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Ou({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:ps("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Ku[e],r),children:[t.jsx("span",{className:ps("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Wu[e])}),n]})}const En="adhdev:themechange";function Hu(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function bs(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function gs(e){return e==="system"?Hu():e}function Mi(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Nr(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(En,{detail:{preference:e,theme:s}}))}function Uu(){const e=bs(),s=gs(e);Mi(s),Nr(e,s)}function ua(){const[e,s]=o.useState(bs),[r,n]=o.useState(()=>gs(bs()));o.useEffect(()=>{Mi(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=m=>{if(e==="system"){const p=m.matches?"light":"dark";n(p),Nr("system",p)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=m=>{const p=m.detail||{},u=p.preference,f=p.theme;s(u==="dark"||u==="light"||u==="system"?u:bs()),n(f==="dark"||f==="light"?f:gs(bs()))},l=m=>{if(m.key!=="theme")return;const p=bs(),u=gs(p);s(p),n(u)};return window.addEventListener(En,c),window.addEventListener("storage",l),()=>{window.removeEventListener(En,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=gs(c);s(c),n(l);try{localStorage.setItem("theme",c)}catch{}Nr(c,l)},[]),i=o.useCallback(()=>{s(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",m=gs(l);n(m);try{localStorage.setItem("theme",l)}catch{}return Nr(l,m),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const eo={dark:"Dark",light:"Light",system:"System"};function Fu({collapsed:e}){const{preference:s,cycleTheme:r}=ua(),n=s==="dark"?t.jsx(hl,{size:16}):s==="light"?t.jsx(fl,{size:16}):t.jsx(xl,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${eo[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:eo[s]})]})}function es({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 zu({onPrefChange:e}){const[s,r]=od(),n=(a,i)=>{r({[a]:i}),e==null||e(a,i)};return t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ur,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:a=>n("globalEnabled",a)}),s.globalEnabled&&t.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&t.jsx(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(It,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:a=>n("browserNotifications",a)}),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(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(bl,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:a=>n("completionAlert",a)}),t.jsx(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(gl,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:a=>n("approvalAlert",a)}),t.jsx(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ys,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:a=>n("disconnectAlert",a)})]}),!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 Er(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function Vu(e,s){const r=Er(e),n=Er(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 Li(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function zs(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||Vu(r,s)>=0)return!1;const n=Er(r),a=Er(s);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Gu(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function un(e,s){return e instanceof Error?e.message:s}function qu({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(Ti,{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(Xu,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function to({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 qs.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 Yu(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[..._u,...Ru,...Pu].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 Xu({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var O,R;const[i,c]=o.useState("idle"),[l,m]=o.useState(""),[p,u]=o.useState(null),[f,v]=o.useState("idle"),[S,T]=o.useState(""),d=e.version||null,b=((O=e.machine)==null?void 0:O.platform)||((R=e.system)==null?void 0:R.platform)||"",N=Ct(e,{fallbackId:e.id}),h=b==="win32"?"🪟":b==="darwin"?"🍎":"🐧",w=s.filter(C=>C.daemonId===e.id&&C.transport==="cdp-page"),_=s.filter(C=>C.daemonId===e.id&&C.transport==="pty"),y=s.filter(C=>C.daemonId===e.id&&C.transport==="acp"),j=e.p2p,k=async()=>{if(r){c("upgrading"),m("Starting upgrade...");try{const C=Gu(await r(e.id,"daemon_upgrade",{}));C.alreadyLatest?(c("done"),m(`Already on v${C.version||"latest"}.`)):C.upgraded||C.success?(c("done"),m(`Upgrade to v${C.version||"latest"} started. Daemon is restarting...`)):(c("error"),m(C.error||"Upgrade failed"))}catch(C){c("error"),m(un(C,"Connection lost during upgrade"))}}},g=async()=>{if(u(null),!!n){v("loading");try{await n(e.id),v("done"),T("Machine disconnected.")}catch(C){v("error"),T(un(C,"Failed to disconnect"))}}},x=async()=>{if(u(null),!!a){v("loading");try{await a(e.id),v("done"),T("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(C){v("error"),T(un(C,"Failed to revoke token"))}}},$="0.8.69",I=Li(e,$),M=zs(e,$),L=w.length+_.length+y.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:N}),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] ${I?"":"bg-bg-secondary"}`,style:I?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",d,!I&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&I&&t.jsx("button",{onClick:k,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${$}`,children:i==="upgrading"?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${M?"↑ Update now":`↑ Update${` to v${$}`}`}`}),n&&t.jsx("button",{onClick:()=>u("disconnect"),disabled:f==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&t.jsx("button",{onClick:()=>u("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),t.jsx(Ou,{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:[j&&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 ${j.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${j.state==="connecting"||j.state==="new"?"animate-pulse":""}`,style:j.state==="connecting"||j.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",j.state==="connected"?"connected":j.state==="connecting"||j.state==="new"?"connecting...":j.state||"off"]}),j.peers!==void 0&&j.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",j.peers," peer",j.peers!==1?"s":"",")"]})]}),j&&L>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),L>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[w.map(C=>{const U=Yu(C.type),G=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:U.icon}),t.jsx("span",{children:U.name}),G!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${G?"bg-green-400":"animate-pulse"}`,style:G?void 0:{background:"var(--status-warning)"},title:G?"CDP connected":"CDP connecting..."})]},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)),y.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||S)&&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:S||l})]}),p==="disconnect"&&t.jsx(to,{title:"🔌 Disconnect Machine",message:`Disconnect "${N}" 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:()=>u(null)})]})}const Qu=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Ju(){const{preference:e,setPreference:s}=ua();return t.jsx("div",{className:"flex gap-2",children:Qu.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 Zu(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 em(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function mn(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function so(e){const{r:s,g:r,b:n}=em(e);return .2126*mn(s)+.7152*mn(r)+.0722*mn(n)}function ro(e,s){const r=so(e),n=so(s),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function _i(e){const s=Zu(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return ro(s,r)>=ro(s,n)?r:n}const $n={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},Bn={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},tm=[{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"}}}],Ri="adhdev-chat-theme",Pi="adhdev-chat-theme-custom";function Cr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Ri)||"ember"}catch{return"ember"}}function Et(e){try{const s=localStorage.getItem(Pi);if(s){const r=JSON.parse(s);return{...e==="dark"?$n:Bn,...r[e]}}}catch{}return e==="dark"?$n:Bn}function pr(e,s){try{localStorage.setItem(Pi,JSON.stringify({dark:e,light:s}))}catch{}}function Mt(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 $r(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 sm={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Vs(e,s){var a;const r=(a=sm[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",$r(r,24)),n.style.setProperty("--accent-on-primary",_i(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${$r(r,18)})`),n.style.setProperty("--border-accent",Mt(r,.35)),n.style.setProperty("--nav-active-bg",Mt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Mt(r,.06)}`)}function ns(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",Mt(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",Mt(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",Mt(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",Mt(e.borderSubtle,.5)),s.style.setProperty("--border-default",Mt(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",$r(e.accentColor,30)),s.style.setProperty("--accent-on-primary",_i(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${$r(e.accentColor,40)})`),s.style.setProperty("--border-accent",Mt(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",Mt(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Mt(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 ${Mt(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 ma(){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 rm(e){try{localStorage.setItem(Ri,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=as()?"dark":"light";ns(Et(s))}else ma(),Vs(e,as()?"dark":"light")}function nm(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Cr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=as()?"dark":"light";ns(Et(s))}else ma(),Vs(e,as()?"dark":"light")}function as(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function wt({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 $s({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 am({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,a]=o.useState(()=>Et(r));o.useEffect(()=>{a(Et(r))},[r]);const i=o.useCallback((c,l)=>{a(m=>{const p={...m,[c]:l},f=Et(r==="dark"?"light":"dark");return r==="dark"?pr(p,f):pr(f,p),ns(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($s,{title:"App Background",children:[t.jsx(wt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),t.jsx(wt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),t.jsx(wt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),t.jsxs($s,{title:"App Text",children:[t.jsx(wt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),t.jsx(wt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),t.jsx(wt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),t.jsxs($s,{title:"Borders & Accent",children:[t.jsx(wt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),t.jsx(wt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),t.jsx(wt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),t.jsxs("div",{children:[t.jsxs($s,{title:"Chat Bubbles",children:[t.jsx(wt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),t.jsx(wt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),t.jsx(wt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),t.jsx(wt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),t.jsxs($s,{title:"Chat Layout",children:[t.jsx(wt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),t.jsx(wt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),t.jsx(wt,{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?$n:Bn,m=Et(e?"light":"dark");e?pr(c,m):pr(m,c),a(c),ns(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 om(){const[e,s]=o.useState(Cr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Et("dark"));o.useEffect(()=>{n(as());const m=new MutationObserver(()=>{const f=as();n(f);const v=Cr();v==="custom"?ns(Et(f?"dark":"light")):Vs(v,f?"dark":"light")});m.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const p=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const f=as();n(f);const v=Cr();v==="custom"?ns(Et(f?"dark":"light")):Vs(v,f?"dark":"light")};return p.addEventListener("change",u),()=>{m.disconnect(),p.removeEventListener("change",u)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?ns(Et(r?"dark":"light")):(ma(),Vs(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Et(r?"dark":"light"))},[r]);const c=m=>{s(m),rm(m)},l=[...tm,{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(m=>{const p=e===m.id,u=r?m.preview.dark:m.preview.light,f=m.id==="honey"||m.id==="ember"?"#1a1a1a":m.id==="custom"?a.userText:"#fff";return t.jsxs("button",{onClick:()=>c(m.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:u.containerBg},children:[t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"Hello! How can I help?"}),t.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.userBubble,color:f},children:"Fix the bug please"}),t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"On it! ✨"})]}),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:m.id==="custom"?"🎨 Custom":m.name}),t.jsx("div",{className:"text-[10px] text-text-muted",children:m.description})]})]})]},m.id)})}),e==="custom"&&t.jsx(am,{dark:r,onColorsChange:m=>i(m)})]})}const Di="adhdev_mobileDashboardMode_v1";function Ei(){try{return localStorage.getItem(Di)==="workspace"?"workspace":"chat"}catch{return"chat"}}function im(e){try{localStorage.setItem(Di,e)}catch{}}function cm(){const[e,s]=o.useState(!0);return o.useEffect(()=>{s(Ei()==="chat")},[]),t.jsx(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ht,{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),im(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}function lm(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 dm(e,s){const{sendData:r}=At(),{injectEntries:n,getIdes:a}=Lr(),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(m=>Gt.subscribe({sendData:r},m,{type:"subscribe",topic:"machine.runtime",key:`machine:${m}`,params:{intervalMs:s==null?void 0:s.intervalMs}},p=>{const u=a().find(v=>v.id===m),f=lm(u,m,p);n([f])}));return()=>{l.forEach(m=>m())}},[i,a,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}const um=4e3;function $i(e,s){const{sendData:r}=At(),[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 m=Gt.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 m.initialSendAccepted?l=setTimeout(()=>{c(!1)},um):c(!1),()=>{l&&clearTimeout(l),m()}},[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 mm(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Bi(e){const{sendData:s}=At(),[r,n]=o.useState({});return o.useEffect(()=>{const a=mm(e);if(!a||!e.sessionId||!s){n({});return}const i=Gt.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}),ks.record({interactionId:c.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:c.status,modalButtonCount:Array.isArray(c.modalButtons)?c.modalButtons.length:0}})});return()=>{i()}},[e.daemonId,e.routeId,e.sessionId,s]),r}const Ki="adhdev_hiddenTabs";function pm(){try{const e=localStorage.getItem(Ki);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function hs(e){try{localStorage.setItem(Ki,JSON.stringify([...e]))}catch{}}function fm(){const[e,s]=o.useState(pm),r=o.useCallback(p=>{s(u=>{const f=new Set(u);return f.has(p)?f.delete(p):f.add(p),hs(f),f})},[]),n=o.useCallback(p=>{s(u=>{if(u.has(p))return u;const f=new Set(u);return f.add(p),hs(f),f})},[]),a=o.useCallback(p=>{s(u=>{if(!u.has(p))return u;const f=new Set(u);return f.delete(p),hs(f),f})},[]),i=o.useCallback(()=>{s(p=>{if(p.size===0)return p;const u=new Set;return hs(u),u})},[]),c=o.useCallback((p,u)=>{s(f=>{const v=new Set(f);for(const S of u)v.add(S);return hs(v),v})},[]),l=o.useCallback((p,u)=>{s(f=>{const v=new Set(f);for(const S of u)v.delete(S);return hs(v),v})},[]),m=o.useCallback(p=>e.has(p),[e]);return{hiddenTabs:e,toggleTab:r,hideTab:n,showTab:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:m}}function no(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 hm(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=no(a,s),c=Array.isArray(a.childSessions)?a.childSessions.map(m=>no(m,s)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function Wi(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 xm(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))Wi(s,a)===i&&(delete n[a],r=!0);return r?n:e}function bm({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{cd()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:bi(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return dd(a),o.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(l=>{const m=Date.now(),p={};for(const[u,f]of Object.entries(l))m-f<5e3&&(p[u]=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 m=l.filter(p=>p.timestamp>c).slice(-100);return m.length===l.length?l:m})},6e4);return()=>clearInterval(i)},[n]),null}function gm(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 os(e){const s=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1];return e.lastMessageAt||gm(s==null?void 0:s.receivedAt)||0}function Kn(e,s=0){return os(e)||e.lastUpdated||s||0}function Oi(e){return os(e)||e.lastUpdated||0}function Hi(e,s,r=Oi){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 Wn(e){var r;const s=jt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function ym(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!Wn(e)&&!e.title.trim()}function vm(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(Wn(r))-Number(Wn(s));if(n!==0)return n;const a=r.messages.length-s.messages.length;return a!==0?a:Hi(s,r)})[0]||null}function Bt(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=vm(a);return n?i&&ym(n)?i:n:i||r[0]||null}function wm(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 pn(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 jm(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 ao(e){if(!e)return"";const s=Array.isArray(e.messages)?e.messages:[],r=s[s.length-1],n=r?jm(Ns(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 km(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||""),ao(e.activeChat),...s.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastUpdated||""),ao(r.activeChat)].join(":"))].join("|")}function Sm(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 Nm(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 Cm(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 Im(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function Am(e){const s=Im(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=Ns(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Tm({ides:e,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:a}){const i=o.useMemo(()=>wm(e),[e]),c=o.useMemo(()=>ki(e),[e]),l=o.useRef([]),m=o.useRef([]),p=o.useRef([]),u=o.useRef(new Map),f=o.useRef(new Map),v=o.useMemo(()=>{const y=new Map,j=[];for(const $ of i){const{connectionState:I="new",machineName:M}=Si($,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),L=Nm($,r),O=km($),R=u.current.get($.id);if(R&&R.ide===$&&R.sourceSignature===O&&R.connectionState===I&&R.machineName===M&&Cm(R.localRefs,L)){y.set($.id,R),j.push(...R.conversations);continue}const C=da($,r,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),U={ide:$,sourceSignature:O,connectionState:I,machineName:M,localRefs:L,conversations:C};y.set($.id,U),j.push(...C)}u.current=y;const k=new Map,g=$=>{const I=Am($),M=f.current.get($.tabKey);if(M&&M.signature===I)return k.set($.tabKey,M),M.timestamp;const L={signature:I,timestamp:Oi($)||(M==null?void 0:M.timestamp)||0};return k.set($.tabKey,L),L.timestamp},x=[...j].sort(($,I)=>Hi($,I,g));return f.current=k,x},[i,r,s,c]),S=o.useMemo(()=>{const y=Sm(v,n);return pn(l.current,y)?l.current:(l.current=y,y)},[v,n]),T=o.useMemo(()=>{const y=new Map,j=Array.from(new Set(S.map(k=>k.routeId)));for(const k of j){const g=Bt(S,k);g&&y.set(k,g)}return y},[S]),d=o.useMemo(()=>{const y=new Map;for(const j of S)if(j.sessionId&&y.set(j.sessionId,j),j.streamSource==="native"&&j.sessionId){const k=T.get(j.routeId);k&&y.set(j.sessionId,k)}return y},[S,T]),b=o.useMemo(()=>{const y=new Map;for(const j of S)j.sessionId&&y.set(j.sessionId,j),y.set(j.routeId,T.get(j.routeId)||j),y.set(j.tabKey,j);return y},[S,T]),N=o.useCallback(y=>{if(y)return d.get(y)},[d]),h=o.useCallback(y=>{if(y)return b.get(y)},[b]),w=o.useMemo(()=>{const y=S.filter(j=>!a.has(j.tabKey));return pn(m.current,y)?m.current:(m.current=y,y)},[S,a]),_=o.useMemo(()=>{const y=w.map(j=>j.tabKey);return pn(p.current,y)?p.current:(p.current=y,y)},[w]);return{chatIdes:i,conversations:S,visibleConversations:w,visibleTabKeys:_,resolveConversationBySessionId:N,resolveConversationByTarget:h}}function Mm({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 m=new URLSearchParams(l);return m.delete("activeTab"),m},{replace:!0})},[n,s]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function Lm({ides:e,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:a}){o.useEffect(()=>{ct.setIdes(e)},[e]),o.useEffect(()=>{ct.setResolveAction((i,c,l)=>{s(i,c,l).catch(()=>{})})},[s]),o.useEffect(()=>{const i=ct.onToast(m=>{r(u=>u.some(v=>v.message===m.message&&m.timestamp-v.timestamp<3e3)?u:[...u.slice(-4),{id:m.id,message:m.message,type:m.type,timestamp:m.timestamp,targetKey:m.targetKey,actions:m.actions}]);const p=m.duration||5e3;setTimeout(()=>r(u=>u.filter(f=>f.id!==m.id)),p)}),c=ct.onSystemMessage((m,p)=>{var S,T;const u=a(m),f=(S=p._localId)==null?void 0:S.startsWith("sys_approval_"),v=!!(u&&(u.status==="waiting_approval"||(T=u.modalButtons)!=null&&T.length||u.modalMessage));f&&v||n(d=>({...d,[m]:[...d[m]||[],p]}))}),l=ct.onClearSystemMessage((m,p)=>{n(u=>{var f;return(f=u[m])!=null&&f.length?{...u,[m]:u[m].filter(v=>{var S;return!(v.role==="system"&&((S=v._localId)!=null&&S.startsWith(p)))})}:u})});return()=>{i(),c(),l()}},[r,n]),o.useEffect(()=>{const i=fi.on("status_event",c=>{ct.handleRawEvent(c,"ws")});return()=>{i()}},[]),o.useEffect(()=>{var c;const i=l=>{var b;const m=l.data;if((m==null?void 0:m.type)!=="notification_action"||typeof m.action!="string"||!m.action.startsWith("approval_")||!(m.daemonId||m.targetSessionId||m.targetKey))return;const p=m.targetSessionId||m.targetKey||m.daemonId,u=a(p),f=(u==null?void 0:u.routeId)||m.daemonId;if(!f)return;const v=Number(m.buttonIndex),S=m.button||((b=u==null?void 0:u.modalButtons)==null?void 0:b[v])||"Approve",T=String(S).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),d=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(T);s(f,"resolve_action",{action:d?"approve":"reject",button:S,...Number.isFinite(v)&&{buttonIndex:v},...(u==null?void 0:u.sessionId)&&{targetSessionId:u.sessionId},...m.targetSessionId&&{targetSessionId:m.targetSessionId}}).catch(N=>console.error("[SW Action] approval failed:",N))};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 _m="adhdev_dashboardLayout_v1",Rm="adhdev_dashboardDockview_v1",Pm="adhdev_dashboardDockviewHiddenRestore_v1",Bs={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function pa(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function Ui(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Fi(e){return`${_m}:${e}`}function Dm(e){const s=Fi(e);return pa(s,null)}function Em(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=Fi(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function zi(e){return`${Rm}:${e}`}function $m(e){const s=zi(e);return pa(s,null)}function Bm(e,s){try{const r=zi(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Vi(e){return`${Pm}:${e}`}function Km(e){const s=Vi(e);return pa(s,{})}function Wm(e,s){try{const r=Vi(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Om(){return{groupAssignments:[...Bs.groupAssignments],focusedGroup:Bs.focusedGroup,groupActiveTabIds:{...Bs.groupActiveTabIds},groupTabOrders:{...Bs.groupTabOrders},groupSizes:[...Bs.groupSizes]}}function Hm(){const[e]=o.useState(()=>Ui(typeof window<"u"?window.innerWidth:1280)),[s,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,m]=o.useState({}),[p,u]=o.useState([]),[f,v]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[S,T]=o.useState(!1),d=o.useCallback(()=>{if(S)return;const b=Dm(e)??Om();r(new Map(b.groupAssignments)),a(b.focusedGroup),c(b.groupActiveTabIds),m(b.groupTabOrders),u(b.groupSizes),T(!0)},[S,e]);return o.useEffect(()=>{S&&Em(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:p})},[S,e,s,n,i,l,p]),o.useEffect(()=>{const b=window.matchMedia("(max-width: 767px)"),N=h=>v(h.matches);return b.addEventListener("change",N),()=>b.removeEventListener("change",N)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:a,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:l,setGroupTabOrders:m,groupSizes:p,setGroupSizes:u,isMobile:f,hasHydratedStoredLayout:S,hydrateStoredLayout:d}}function Um(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=[s.providerSessionId,s.sessionId].filter(a=>typeof a=="string"&&a.length>0);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Fm({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:l,setSearchParams:m,historyModalOpen:p,activeConv:u,isRefreshingHistory:f,ides:v,handleRefreshHistory:S}){const T=o.useRef(!1),d=o.useRef(!1),b=o.useRef(null),N=o.useRef(!1);o.useEffect(()=>{if(!e||T.current||s.length===0)return;if(!a){i();return}const h=r(e);if(!h)return;const w=n.get(h.tabKey)??0;c(_=>({..._,[w]:h.tabKey})),l(w),T.current=!0,d.current=!0,b.current!=null&&(window.clearTimeout(b.current),b.current=null),m(_=>{const y=new URLSearchParams(_);return y.delete("activeTab"),y},{replace:!0})},[e,s,r,n,a,i,c,l,m]),o.useEffect(()=>{if(!(d.current||a)&&s.length!==0){if(!e){i(),d.current=!0;return}if(T.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){N.current=!1;return}if(!u||N.current||f)return;const h=v.find(w=>w.id===u.routeId);h&&(!h.chats||h.chats.length===0||Um(h.chats,u))&&(N.current=!0,S())},[p,u,f,v,S]),o.useEffect(()=>{if(!u)return;let h=null,w=0,_=-1,y=0;const j=()=>{h=null;const k=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(x=>x.offsetParent!==null);if(k.length===0){w<18&&(w+=1,h=requestAnimationFrame(j));return}let g=0;for(const x of k)x.scrollTop=x.scrollHeight,g+=x.scrollHeight;g===_?y+=1:(y=0,_=g),w+=1,!(y>=2||w>=18)&&(h=requestAnimationFrame(j))};return h=requestAnimationFrame(j),()=>{h!=null&&cancelAnimationFrame(h)}},[u==null?void 0:u.tabKey])}function zm({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[m,p]=o.useState(null),[u,f]=o.useState(null),v=o.useMemo(()=>{if(e||!n)return null;const N=l(n);return N&&!et(N)&&!Ye(N)?N:null},[e,n,l]),S=o.useMemo(()=>{const N=m==null?void 0:m.routeId;if(!N)return null;const h=m!=null&&m.tabKey?i.find(w=>w.tabKey===m.tabKey):a?i.find(w=>w.tabKey===a):null;return(h==null?void 0:h.routeId)===N?h:Bt(i,N)},[i,m,a]),T=o.useMemo(()=>{if(S)return c.find(N=>N.id===S.routeId)},[c,S]);o.useEffect(()=>{v&&(p({routeId:v.routeId,tabKey:Ha(v)}),f(v),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,v]);const d=o.useCallback(N=>{N&&(p({routeId:N.routeId,tabKey:Ha(N)}),f(N))},[]),b=o.useCallback(()=>{p(null),f(null)},[]);return{remoteDialogConv:S,remoteDialogIdeEntry:T,remoteDialogActiveConv:u,setRemoteDialogActiveConv:f,openRemoteDialog:d,closeRemoteDialog:b}}function ws(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:et(e)||Ye(e)?{agentType:Dt(e)}:e.streamSource==="agent-stream"?{agentType:Dt(e)}:s}function Js(e){return e?er(e):""}function Ks(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function fn(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=[s.providerSessionId,s.sessionId].filter(a=>typeof a=="string"&&a.length>0);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function oo({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:a,setLocalUserMessages:i,setClearedTabs:c}){const[l,m]=o.useState(!1),[p,u]=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]),v=o.useCallback(async(d,b)=>{try{const N=d||(s==null?void 0:s.daemonId)||"",h=await e(N,"switch_chat",{id:b,sessionId:b,...ws(s)}),w=h==null?void 0:h.result;if((h==null?void 0:h.success)===!0||w==="switched"||w==="switched-by-title")return;w===!1||w==="not_found"?Ks(a,"⚠️ Session tab not found — try refreshing history"):typeof w=="string"&&w.startsWith("error:")?Ks(a,`⚠️ Switch error: ${w}`):Ks(a,"⚠️ Session switch failed")}catch(N){console.error("Switch failed",N),Ks(a,`❌ Switch failed: ${N.message||"connection error"}`)}},[s,e,a]),S=o.useCallback(async()=>{if(!(!s||l)){m(!0);try{const d=Js(s);await e(d,"new_chat",{...ws(s)}),c(b=>({...b,[s.tabKey]:Date.now()})),i(b=>({...b,[s.tabKey]:[]}))}catch(d){console.error("New chat failed",d)}finally{m(!1)}}},[s,l,e,c,i]),T=o.useCallback(async()=>{var d,b;if(!(!s||p)){u(!0);try{const N=Js(s),h=async()=>e(N,"list_chats",{forceExpand:!0,...ws(s)});let w=await h(),_=(w==null?void 0:w.chats)||((d=w==null?void 0:w.result)==null?void 0:d.chats);fn(_,s)&&(await new Promise(y=>setTimeout(y,450)),w=await h(),_=(w==null?void 0:w.chats)||((b=w==null?void 0:w.result)==null?void 0:b.chats)),w!=null&&w.success&&Array.isArray(_)&&(n(s.routeId,_),fn(_,s)&&!fn(r,s)&&Ks(a,"⚠️ History dialog did not fully open — try once more"))}catch(N){console.error("Refresh history failed",N)}finally{u(!1)}}},[s,r,p,e,n,a]);return{isCreatingChat:l,isRefreshingHistory:p,handleLaunchIde:f,handleSwitchSession:v,handleNewChat:S,handleRefreshHistory:T}}function Vm(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 Gm(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function io(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 fr(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 m=a[l];typeof m=="number"&&m>0&&i.set(c,m)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function co(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 qm(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 Ym(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 lo(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 uo(e){return Array(e).fill(100/e)}function Xm({groupAssignments:e,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:a,groupSizes:i,setGroupSizes:c,isMobile:l,visibleConversations:m,visibleTabKeys:p}){const u=o.useRef(null),f=o.useMemo(()=>fr(e,p),[e,p]),v=f.assignments,S=o.useMemo(()=>l?1:f.groupCount,[f.groupCount,l]),T=S>1,d=o.useCallback((y,j)=>{s(k=>{const g=new Map(fr(k,p).assignments);return j===0?g.delete(y):g.set(y,j),g}),n(k=>({...k,[j]:y})),r(j)},[s,p,n,r]),b=o.useCallback(y=>{s(j=>{const k=fr(j,p).assignments,g=new Map;for(const[x,$]of k)$!==y&&($>y?g.set(x,$-1):g.set(x,$));return g}),c(j=>{if(j.length<=1)return[];const k=[...j];k.splice(y,1);const g=k.reduce((x,$)=>x+$,0);return g>0?k.map(x=>x/g*100):[]}),r(0)},[s,p,c,r]),N=o.useCallback((y,j)=>{j.preventDefault();const k=u.current;if(!k)return;const g=j.clientX,x=k.offsetWidth,$=i.length===S?[...i]:uo(S),I=L=>{const R=(L.clientX-g)/x*100,C=[...$];C[y]=Math.max(15,$[y]+R),C[y+1]=Math.max(15,$[y+1]-R),c(C)},M=()=>{document.removeEventListener("mousemove",I),document.removeEventListener("mouseup",M),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",I),document.addEventListener("mouseup",M)},[i,S,c]),h=o.useCallback((y,j,k)=>{if(S>=4)return;const g=k==="left"?j:j+1;s(x=>{const $=fr(x,p).assignments,I=new Map;for(const M of m){const L=$.get(M.tabKey)??0,O=L>=g?L+1:L;O>0&&I.set(M.tabKey,O)}return g>0&&I.set(y,g),I}),c(x=>{const $=x.length===S?[...x]:uo(S),I=$[j]??100/S,M=Math.max(15,I/2),L=Math.max(15,I/2),O=[...$];O[j]=M,O.splice(g,0,L);const R=O.reduce((C,U)=>C+U,0);return O.map(C=>C/R*100)}),n(x=>{const $=lo(x,g);return $[g]=y,$}),a(x=>{const $=lo(x,g);return $[g]=[y],$}),r(g)},[S,s,p,m,c,n,a,r]);o.useEffect(()=>{Vm(e,v)||s(v)},[e,v,s]),o.useEffect(()=>{const{mapping:y,usedGroups:j}=f;n(k=>{const g=co(k,y);return io(k,g)?k:g}),a(k=>{const g=co(k,y);return io(k,g)?k:g}),r(k=>{const g=l?0:qm(k,j,y);return k===g?k:g}),c(k=>{const g=l?[]:Ym(k,j,f.groupCount);return Gm(k,g)?k:g})},[f,l,n,a,r,c]);const w=o.useMemo(()=>{const y=Array.from({length:S},()=>[]);for(const j of m){const k=v.get(j.tabKey)??0,g=Math.min(k,S-1);y[g].push(j)}return y},[m,v,S]),_=o.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:u,normalizedGroupAssignments:v,numGroups:S,isSplitMode:T,groupedConvs:w,moveTabToGroup:d,closeGroup:b,handleResizeStart:N,splitTabRelative:h,clearAllSplits:_}}function Qm({ides:e,sendDaemonCommand:s}){const r="0.8.68",n=o.useMemo(()=>e.filter(u=>u.type!=="adhdev-daemon"?!1:Li(u,r)).sort((u,f)=>Number(zs(f,r))-Number(zs(u,r))),[r,e]),a=o.useMemo(()=>n.some(u=>zs(u,r)),[r,n]),[i,c]=o.useState(!1),[l,m]=o.useState({}),p=o.useCallback(async u=>{var f,v;m(S=>({...S,[u]:"upgrading"}));try{const S=await s(u,"daemon_upgrade",{});(f=S==null?void 0:S.result)!=null&&f.upgraded||(v=S==null?void 0:S.result)!=null&&v.success?m(T=>({...T,[u]:"done"})):m(T=>({...T,[u]:"error"}))}catch{m(S=>({...S,[u]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:p}}const On="adhdev_dashboard_notifications_v1",fa=80;function Ir(e,s=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:s}function Br(e){return{...e,createdAt:Ir(e.createdAt),updatedAt:Ir(e.updatedAt,e.createdAt),lastEventAt:Ir(e.lastEventAt,e.updatedAt||e.createdAt)}}function Jm(e){return e.providerSessionId||e.sessionId||e.tabKey||e.id}function Zm(e){return[e.type,e.providerSessionId||e.sessionId||e.tabKey||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function ep(e,s){const r=Date.now(),n=[];for(const a of e){const i=a.sessionId?s.get(a.sessionId):void 0;if(i!=null&&i.surfaceHidden)continue;const c=(i==null?void 0:i.inboxBucket)||"idle",l=c==="needs_attention"?"needs_attention":c==="task_complete"&&(i!=null&&i.unread)?"task_complete":null;if(!l)continue;const m=Ir(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),p=Zm({type:l,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(i==null?void 0:i.lastUpdated)||a.lastUpdated});n.push(Br({id:p,dedupKey:p,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:a.title||a.displayPrimary||a.agentName||a.tabKey,preview:a.lastMessagePreview||a.displaySecondary||"",createdAt:m,updatedAt:m,lastEventAt:m}))}return n.sort((a,i)=>i.updatedAt-a.updatedAt)}function tp(e,s,r=fa){const n=new Map;for(const i of e)i.deletedAt||n.set(i.id,Br(i));for(const i of s){const c=Br(i),l=n.get(c.id);if(!l){n.set(c.id,c);continue}n.set(c.id,{...l,...c,createdAt:l.createdAt,readAt:l.readAt,deletedAt:l.deletedAt})}const a=new Map;for(const i of Array.from(n.values())){if(i.deletedAt)continue;const c=Jm(i),l=a.get(c);if(!l){a.set(c,i);continue}(i.updatedAt>l.updatedAt||i.updatedAt===l.updatedAt&&i.createdAt>l.createdAt)&&a.set(c,i)}return Array.from(a.values()).sort((i,c)=>{const l=c.updatedAt-i.updatedAt;return l!==0?l:c.createdAt-i.createdAt}).slice(0,Math.max(0,r))}function sp(e,s,r=Date.now()){return e.map(n=>n.id===s?{...n,readAt:r,updatedAt:Math.max(n.updatedAt,r)}:n)}function rp(e,s){return e.map(r=>{if(r.id!==s)return r;const n={...r};return delete n.readAt,n})}function np(e,s,r=Date.now()){return e.map(n=>{const a=!!s.sessionId&&n.sessionId===s.sessionId,i=!!s.providerSessionId&&n.providerSessionId===s.providerSessionId,c=!!s.tabKey&&n.tabKey===s.tabKey;return!a&&!i&&!c?n:{...n,readAt:r,updatedAt:Math.max(n.updatedAt,r)}})}function ap(e,s){return e.filter(r=>r.id!==s)}function op(e){return e.filter(s=>!s.readAt&&!s.deletedAt).length}function ip(e){const s=new Map;for(const r of e){if(r.deletedAt)continue;const n=[r.providerSessionId,r.sessionId,r.tabKey].filter(Boolean);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 cp(){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(On),s=e?JSON.parse(e):[];return Array.isArray(s)?s.map(r=>Br(r)).filter(r=>!r.deletedAt):[]}catch{return[]}}function lp(e){if(!(typeof window>"u"))try{const s=e.filter(r=>!r.deletedAt).slice(0,fa);if(s.length===0){window.localStorage.removeItem(On);return}window.localStorage.setItem(On,JSON.stringify(s))}catch{}}function dp(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.updatedAt===a.updatedAt&&r.createdAt===a.createdAt&&r.readAt===a.readAt&&r.preview===a.preview&&r.title===a.title&&r.deletedAt===a.deletedAt:!1})}function up(e){const{conversations:s,liveSessionInboxState:r,maxItems:n=fa}=e,a=o.useMemo(()=>ep(s,r),[s,r]),[i,c]=o.useState(()=>cp());o.useEffect(()=>{c(S=>{const T=tp(S,a,n);return dp(S,T)?S:T})},[a,n]),o.useEffect(()=>{lp(i)},[i]);const l=o.useMemo(()=>op(i),[i]),m=o.useMemo(()=>ip(i),[i]),p=o.useCallback((S,T)=>{c(d=>sp(d,S,T))},[]),u=o.useCallback(S=>{c(T=>rp(T,S))},[]),f=o.useCallback((S,T)=>{c(d=>np(d,S,T))},[]),v=o.useCallback(S=>{c(T=>ap(T,S))},[]);return{notifications:i,unreadCount:l,notificationStateBySessionId:m,markRead:p,markUnread:u,markTargetRead:f,deleteNotification:v}}function mp(e,s,r=2e3){return e?e.tabKey===s.tabKey&&e.message===s.message&&s.timestamp-e.timestamp<r:!1}function pp(e,s){return e?e.tabKey===s.tabKey&&e.message===s.message&&e.timestamp===s.timestamp?null:e:null}function mo(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function ha(e){return e instanceof Error?e.message:String(e||"")}function po(e){const s=ha(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function fo(e,s){const r=ha(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function Gr({sendDaemonCommand:e,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:a}){const[i,c]=o.useState(!1),[l,m]=o.useState(!1),p=o.useRef(!1),u=o.useRef(null),f=o.useCallback(async d=>{if(!s)return;const b=d.trim();if(!b||p.current)return;const N=Date.now(),h={tabKey:s.tabKey,message:b,timestamp:N};if(mp(u.current,h))return;p.current=!0,m(!0),u.current=h;const w=`${N}-${Math.random().toString(36).slice(2,8)}`,_={role:"user",content:b,timestamp:N,_localId:w},y=!(et(s)||Ye(s));y&&r(j=>({...j,[h.tabKey]:[...j[h.tabKey]||[],_]}));try{const j=Js(s);if(!j)return;const k=await e(j,"send_chat",{message:b,...ws(s)}),g=mo(k);if(y&&(g!=null&&g.deduplicated||(g==null?void 0:g.sent)===!1)){r(x=>({...x,[h.tabKey]:(x[h.tabKey]||[]).filter($=>$._localId!==w)}));return}if((g==null?void 0:g.success)===!1)throw new Error((g==null?void 0:g.error)||"Send failed");setTimeout(()=>{const x=Date.now()-6e4;r($=>{const I=$[h.tabKey];if(!I)return $;const M=I.filter(L=>L.timestamp>x);return M.length===I.length?$:{...$,[h.tabKey]:M}})},6e4)}catch(j){const k=ha(j);k.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",k):console.error("Send failed",j),u.current=pp(u.current,h),y&&r(g=>({...g,[h.tabKey]:(g[h.tabKey]||[]).filter(x=>x._localId!==w)})),n(g=>[...g,{routeId:h.tabKey,text:`❌ **Send failed** — ${k||"Unknown error"}`,timestamp:Date.now()}])}finally{p.current=!1,m(!1)}},[s,e,n,r]),v=o.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await e(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(d){console.error("Relaunch failed",d)}},[s,e]),S=o.useCallback(async d=>{if(s)try{const N=(s.modalButtons||[]).indexOf(d),h=d.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),w=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(h),_=Js(s);if(!_)return;const y=await e(_,"resolve_action",{button:d,action:w?"approve":"reject",...N>=0&&{buttonIndex:N},...ws(s)}),j=mo(y);j.success||n(k=>[...k,{routeId:s.tabKey,text:fo(d,j==null?void 0:j.error),timestamp:Date.now()}])}catch(b){po(b)||console.error("[ModalButton] Error:",b),n(N=>[...N,{routeId:s.tabKey,text:po(b)?fo(d,b):`❌ **${d}** error`,timestamp:Date.now()}])}},[s,e,n]),T=o.useCallback(async()=>{if(!(!s||i)){c(!0);try{await e(s.routeId,"focus_session",{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(d){console.error("Focus agent failed",d)}finally{c(!1)}}},[s,i,e]);return{isSendingChat:l,isFocusingAgent:i,handleSendChat:f,handleRelaunch:v,handleModalButton:S,handleFocusAgent:T}}const xa=o.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:m,isSendingChat:p,handleFocusAgent:u,isFocusingAgent:f,actionLogs:v,userName:S,scrollToBottomRequestNonce:T,isInputActive:d=!0}){const b=Bi(s),N=b.status||b.modalMessage||b.modalButtons?{...s,...b.status?{status:b.status}:{},...b.modalMessage!==void 0?{modalMessage:b.modalMessage}:{},...b.modalButtons!==void 0?{modalButtons:b.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(Qo,{activeConv:N,onModalButton:c}),N.transport!=="pty"&&N.transport!=="acp"&&N.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(ls,{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,N.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(du,{activeConv:N,clearToken:r,terminalRef:i,handleSendChat:m,isSendingChat:p,isVisible:n})}),!n&&t.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(Dn,{activeConv:N,ideEntry:a,handleSendChat:m,isSendingChat:p,handleFocusAgent:u,isFocusingAgent:f,actionLogs:v,userName:S,scrollToBottomRequestNonce:T,isInputActive:d})})]}):t.jsx(Dn,{activeConv:N,ideEntry:a,handleSendChat:m,isSendingChat:p,handleFocusAgent:u,isFocusingAgent:f,actionLogs:v,userName:S,scrollToBottomRequestNonce:T,isInputActive:d})]})},(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.handleFocusAgent===s.handleFocusAgent&&e.isFocusingAgent===s.isFocusingAgent&&e.actionLogs===s.actionLogs&&e.userName===s.userName&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&e.isInputActive===s.isInputActive);function fp({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,isFocusingAgent:l,onBack:m,onOpenNativeConversation:p,onOpenMachine:u,onOpenHistory:f,onOpenRemote:v,onHideConversation:S,onStopCli:T,cliViewMode:d,onSetCliViewMode:b,handleSendChat:N,handleFocusAgent:h,handleModalButton:w,handleRelaunch:_}){const y=o.useRef(null),j=et(e)&&!s,k=j&&d==="terminal",g=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:`flex items-center justify-between gap-3 ${g} 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:m,type:"button","aria-label":"Back",children:t.jsx(Gn,{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(ci,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>p(e),onOpenMachine:()=>u(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[j&&d&&t.jsx(na,{mode:d,onChange:b,compact:!0}),j&&T&&t.jsx("button",{onClick:()=>{T(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(kt,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:t.jsx(Yn,{size:14})}),!s&&!j&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>v(e),type:"button",children:t.jsx(It,{size:14})}),S&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(e),type:"button",title:"Close chat",children:t.jsx(kt,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(xa,{activeConv:e,clearToken:0,isCliTerminal:k,ideEntry:n,terminalRef:y,handleModalButton:w,handleRelaunch:_,handleSendChat:N,isSendingChat:c,handleFocusAgent:h,isFocusingAgent:l,actionLogs:a,userName:i})})]})}const hn={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 hp(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Gi(){const[e,s]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{s(hp())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(hn[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:hn[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:hn[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 qi({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:It},{key:"chats",label:"Chats",icon:Ht}];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 hr({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 xs({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 Ws({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 xr({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:m,isConnecting:p}=Rs(e.conversation),u=lt(e.conversation),f=ms(e.conversation),v=xi(e.conversation,{requiresAction:s==="needs_attention"}),S=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",T=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",N=c?"text-text-secondary opacity-80":"text-text-muted",h=c?"text-text-muted opacity-80":"text-text-muted",w="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] ${S}`,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 ${T}`,style:a?{color:"var(--accent-on-primary)"}:void 0,children:r(u)}),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:u}),!i&&t.jsx("span",{className:`text-[11px] font-medium shrink-0 ${h}`,children:Xo(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${b}`,children:[f,m?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${w} 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…"})]}):v==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:w,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${N}`,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 ho({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 xp({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:m,onShowConversation:p,onShowAllHidden:u,onOpenNewSession:f,onOpenMachine:v,onOpenSettings:S,onSectionChange:T,wsStatus:d="connected",isStandalone:b=!1}){const N=d==="disconnected"||d==="reconnecting"||d==="offline"||d==="auth_failed",h=c.length>0,w=s.length>0||r.length>0||n.length>0||a.length>0,_=e==="machines"?"Machines":"Chats",y=b?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",j=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 ${y}`,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(Ur,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:S,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(Or,{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] ${j}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:N?t.jsx(Ws,{icon:t.jsx(ho,{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(Ws,{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(Gi,{})})}):t.jsx(xs,{children:c.map((k,g)=>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] ${g>0?"border-t border-border-subtle/70":""}`,onClick:()=>v(k.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(k.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:k.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:k.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[k.unread," new"]}):k.total>0?`${k.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:k.subtitle}),k.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[k.total," chat",k.total!==1?"s":"",k.unread>0?` · ${k.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},k.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(hr,{title:"Needs attention",className:"mb-0"}),t.jsx(xs,{children:s.map((k,g)=>t.jsx("div",{className:g>0?"border-t border-border-subtle/70":"",children:t.jsx(xr,{item:k,type:"needs_attention",getAvatarText:l,onOpenConversation:m})},k.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(hr,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(xs,{children:r.map((k,g)=>t.jsx("div",{className:g>0?"border-t border-border-subtle/70":"",children:t.jsx(xr,{item:k,type:"task_complete",getAvatarText:l,onOpenConversation:m})},k.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(hr,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(xs,{children:n.map((k,g)=>t.jsx("div",{className:g>0?"border-t border-border-subtle/70":"",children:t.jsx(xr,{item:k,type:"working",getAvatarText:l,onOpenConversation:m})},k.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(hr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?t.jsx(xs,{children:a.map((k,g)=>t.jsx("div",{className:g>0?"border-t border-border-subtle/70":"",children:t.jsx(xr,{item:k,type:"earlier",getAvatarText:l,onOpenConversation:m})},k.conversation.tabKey))}):w?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):N?t.jsx(Ws,{icon:t.jsx(ho,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):h?t.jsx(Ws,{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(Ht,{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(Ws,{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:u,children:"Restore all"})]}),t.jsx(xs,{className:"bg-bg-secondary/25",children:i.map((k,g)=>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 ${g>0?"border-t border-border-subtle/70":""}`,onClick:()=>p(k),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(k))}),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(k)}),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:ms(k)}),t.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},k.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(qi,{section:e,onSectionChange:T})]})}function bp(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 Yi(e){const s=[e.workspace||"Workspace unknown"],r=ds(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=bp(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function qr(...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 gp(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 Yr(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=gp(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 yp(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 vp(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Xr(e,s,r){const n=await e(s,"file_list_browse",{path:r}),a=vp(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,u)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${u}`:p==="/"||p==="\\"?`${c}${u}`:`${p.replace(/[\\/]+$/,"")}${c}${u}`,m=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,u)=>p.name.localeCompare(u.name)):[];return{path:i,directories:m}}function Qr({title:e,description:s,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:m,onConfirm:p}){const[u,f]=o.useState(r);o.useEffect(()=>{f(r)},[r]);const v=yp(r),S=u.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(kt,{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:()=>{!v||a||m(v)},disabled:!v||a,children:[t.jsx(Gn,{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:u,onChange:T=>f(T.target.value),onKeyDown:T=>{T.key!=="Enter"||!S||a||(T.preventDefault(),m(S))},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:()=>{!S||a||m(S)},disabled:!S||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(T=>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:()=>m(T.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(Ss,{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:T.name}),t.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:T.path})]})]},T.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(S||r),disabled:!S&&!r||a,children:c})]})]})})}function ba({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:m=!1,showArgsInput:p,argsValue:u,onArgsChange:f,showModelInput:v,modelValue:S,onModelChange:T,historyProviderNode:d,onConfirm:b,onCancel:N}){const h=n==null?void 0:n.find(w=>w.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:N,"aria-label":"Close launch confirmation",children:t.jsx(kt,{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:w=>i(w.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:m,children:n.map(w=>t.jsx("option",{value:w.key,children:w.label},w.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(w=>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:w.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:w.value})]},`${w.label}:${w.value}`)),v&&T&&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:S||"",onChange:w=>T(w.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:m})]}),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:u||"",onChange:w=>f(w.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:m})]})]}),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:N,disabled:m,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:m,children:[t.jsx(Xn,{size:14}),m?l:c]})]})]})})}function xo(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function is(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 m of s.workspaces||[])i.push({key:`saved:${m.id}`,label:`${m.id===s.defaultWorkspaceId?"⭐ ":""}${xo(m.path,m.label)}`,description:m.path,workspaceId:m.id,workspacePath:m.path});const c=(r==null?void 0:r.trim())||"",l=c?(s.workspaces||[]).find(m=>m.path===c):null;if(c&&!l&&i.push({key:`custom:${c}`,label:xo(c),description:c,workspaceId:null,workspacePath:c}),n){const m=`saved:${n}`;if(i.some(p=>p.key===m))return{options:i,selectedKey:m}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function wp(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function jp(e){return[wp(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function kp(e){return e.lastLaunchedAt?Fr(e.lastLaunchedAt):""}function Xi(e){return{metaText:jp(e),updatedLabel:kp(e)}}function xn(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function Sp({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var dt,ut,ht,ot;const c=tr(),[l,m]=o.useState(!1),p=(((dt=e.detectedIdes)==null?void 0:dt.length)||0)>0,u=o.useMemo(()=>(e.workspaces||[]).map(de=>({id:de.id,path:de.path,label:de.label})),[e]),f=e.defaultWorkspaceId||null,[v,S]=o.useState(f||((ut=u[0])==null?void 0:ut.id)||""),[T,d]=o.useState(""),[b,N]=o.useState(""),[h,w]=o.useState([]),[_,y]=o.useState(!1),[j,k]=o.useState(""),[g,x]=o.useState(!1),[$,I]=o.useState(xn(p,s.length,r.length)),M=o.useRef(null),[L,O]=o.useState(null),R=o.useRef("__home__"),[C,U]=o.useState("__home__"),[G,A]=o.useState(""),[D,B]=o.useState(""),[W,X]=o.useState(""),[xe,Re]=o.useState([]),[ie,Ie]=o.useState(()=>gt().textQuery),[te,ce]=o.useState(()=>gt().workspaceQuery),[oe,ye]=o.useState(()=>gt().modelQuery),[ae,F]=o.useState(()=>gt().resumableOnly),[be,se]=o.useState(()=>gt().sortMode),[pe,J]=o.useState(!1),[le,ne]=o.useState(!1),ge=o.useRef(null),ue=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const E=v==="__custom__"?T.trim():((ht=u.find(de=>de.id===v))==null?void 0:ht.path)||"",ve=v==="__custom__"&&!!E&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),he=v!=="__custom__"&&((ot=u.find(de=>de.id===v))==null?void 0:ot.path)||"",Se=o.useMemo(()=>(e.recentLaunches||[]).map(de=>de.workspace),[e]),Q=o.useCallback(async de=>{y(!0),k("");try{const ze=await a(de);N(ze.path),d(ze.path),w(ze.directories)}catch(ze){k(ze instanceof Error?ze.message:"Could not load folder")}finally{y(!1)}},[a]),Ne=o.useCallback(()=>{var ze;S("__custom__"),x(!0);const de=Yr(e.platform,qr(T.trim(),he,Se,e.defaultWorkspacePath,(ze=u.find(Je=>Je.id===f))==null?void 0:ze.path,u.map(Je=>Je.path)));Q(de)},[T,f,Q,Se,he,e.platform,u]),Ue=o.useCallback(de=>{if(de!=null&&de.workspaceId){S(de.workspaceId),d("");return}if(de!=null&&de.workspacePath){S("__custom__"),d(de.workspacePath);return}S(""),d("")},[]),Ee=o.useCallback(de=>{if(S(de),de==="__custom__"){Ne();return}d("")},[Ne]),Ve=o.useCallback(de=>{S("__custom__"),d(de)},[]),Xe=o.useCallback((de,ze)=>{M.current=ze,R.current=de.selectedWorkspaceKey||"__home__",U(de.selectedWorkspaceKey||"__home__"),A(de.initialArgs||""),B(de.initialModel||""),X(""),Re([]);const Je=de.providerType?`${e.id}:${de.providerType}`:null;if(fu(ue.current,Je)){const tt=gt();Ie(tt.textQuery),ce(tt.workspaceQuery),ye(tt.modelQuery),F(tt.resumableOnly),se(tt.sortMode)}ue.current=Je,O(de),de.providerType&&i&&(J(!0),i(de.providerType).then(tt=>Re(tt||[])).catch(tt=>console.warn("Failed to load saved sessions",tt)).finally(()=>J(!1)))},[i,e.id]),Qe=o.useMemo(()=>yi(xe,{textQuery:ie,workspaceQuery:te,modelQuery:oe,resumableOnly:ae,sortMode:be}),[oe,ae,xe,be,ie,te]);o.useEffect(()=>{W&&(Qe.some(de=>de.providerSessionId===W)||X(""))},[Qe,W]);const ft=o.useCallback(()=>{M.current&&(ne(!0),M.current().finally(()=>{M.current=null,ne(!1),O(null)}))},[]),Ge=o.useCallback(()=>{M.current=null,O(null)},[]),bt=o.useCallback(de=>{R.current=de,U(de)},[]);return o.useEffect(()=>{var de;ge.current!==e.id&&(ge.current=e.id,S(f||((de=u[0])==null?void 0:de.id)||"__custom__"),d(""),N(""),w([]),k(""),x(!1),Ie(gt().textQuery),ce(gt().workspaceQuery),ye(gt().modelQuery),F(gt().resumableOnly),se(gt().sortMode),ue.current=null,I(xn(p,s.length,r.length)))},[r.length,s.length,f,p,e.id,u]),o.useEffect(()=>{var de;v!=="__custom__"&&(v&&u.some(ze=>ze.id===v)||S(f||((de=u[0])==null?void 0:de.id)||"__custom__"))},[f,v,u]),o.useEffect(()=>{$==="ide"&&p||$==="cli"&&s.length>0||$==="acp"&&r.length>0||I(xn(p,s.length,r.length))},[$,r.length,s.length,p]),{showAllRecent:l,setShowAllRecent:m,hasIdeOptions:p,workspaceRows:u,defaultWorkspaceId:f,workspaceChoice:v,customWorkspacePath:T,browseCurrentPath:b,browseDirectories:h,browseBusy:_,browseError:j,browseDialogOpen:g,activeLauncherKind:$,launchConfirm:L,launchConfirmWorkspaceKeyRef:R,launchConfirmWorkspaceKey:C,launchConfirmArgs:G,launchConfirmModel:D,launchConfirmResumeId:W,launchConfirmSavedSessions:xe,launchConfirmTextFilter:ie,launchConfirmWorkspaceFilter:te,launchConfirmModelFilter:oe,launchConfirmResumableOnly:ae,launchConfirmSortMode:be,filteredLaunchConfirmSavedSessions:Qe,launchConfirmSessionsLoading:pe,launchConfirmBusy:le,resolvedWorkspacePath:E,canCreateMissingWorkspace:ve,openBrowseDialog:Ne,loadBrowsePath:Q,handleWorkspaceChoiceChange:Ee,chooseCustomWorkspacePath:Ve,setCustomWorkspacePath:d,setBrowseDialogOpen:x,setActiveLauncherKind:I,openLaunchConfirm:Xe,handleConfirmLaunch:ft,closeLaunchConfirm:Ge,setWorkspaceSelectionFromOption:Ue,setLaunchConfirmWorkspaceKeyAndSync:bt,setLaunchConfirmArgs:A,setLaunchConfirmModel:B,setLaunchConfirmResumeId:X,setLaunchConfirmTextFilter:Ie,setLaunchConfirmWorkspaceFilter:ce,setLaunchConfirmModelFilter:ye,setLaunchConfirmResumableOnly:F,setLaunchConfirmSortMode:se}}function Np({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:m,section:p,showBottomNav:u,onBack:f,onSectionChange:v,onOpenConversation:S,onOpenRecent:T,onOpenMachineDetails:d,onMachineUpgrade:b,onLaunchDetectedIde:N,onAddWorkspace:h,onBrowseDirectory:w,onLaunchWorkspaceProvider:_,onListSavedSessions:y}){const j=C=>C==="ide"?"IDE":C==="cli"?"CLI":"ACP",k=r.slice(0,4),g=s.slice(0,3),x=Sp({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:w,onListSavedSessions:y}),$=o.useMemo(()=>k.map(C=>{const{metaText:U,updatedLabel:G}=Xi(C);return{key:`recent-launch:${C.id}`,primary:C.label,secondary:U,updatedLabel:G,onClick:()=>{const{options:A,selectedKey:D}=is({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspacePath:C.workspace});x.openLaunchConfirm({title:C.kind==="ide"?ss("restart-ide",C.label):C.providerSessionId?ia(C.label):ss("start-fresh",C.label),description:C.kind==="ide"?rs("restart-ide"):C.providerSessionId?ca():rs("start-fresh"),confirmLabel:C.kind==="ide"?Ts("restart-ide"):C.providerSessionId?Dr(!0):Ts("start-fresh"),busyLabel:C.kind==="ide"?Ms("restart-ide"):C.providerSessionId?aa(!0):Ms("start-fresh"),workspaceOptions:A,selectedWorkspaceKey:D,details:[{label:"Mode",value:j(C.kind)},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]},async()=>{const B=A.find(W=>W.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(B),await T({...C,workspace:(B==null?void 0:B.workspacePath)??null})})}}}),[x,T,k]),I=o.useMemo(()=>g.map(C=>({key:`recent-chat:${C.conversation.tabKey}`,primary:lt(C.conversation),secondary:ou(C.conversation,{timestampLabel:C.timestamp?Xo(C.timestamp):null}),unread:C.unread,onClick:()=>S(C.conversation)})),[S,g]),M=x.showAllRecent?$:$.slice(0,4),L=$.length>0,O=I.length>0,R=m?"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 ${R} 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(Gn,{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:Ct(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:[O&&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:I.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))})]}),L&&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:M.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))}),$.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 ${$.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?"⭐ ":"",Vr(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(Ss,{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:U,selectedKey:G}=is({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:U,selectedWorkspaceKey:G,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:C.name}]},async()=>{const A=U.find(D=>D.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(A),N(C.type,{workspacePath:(A==null?void 0:A.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 U=x.activeLauncherKind==="cli"?"cli":"acp",{options:G,selectedKey:A}=is({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 ${U.toUpperCase()}`,workspaceOptions:G,selectedWorkspaceKey:A,details:[{label:"Mode",value:U.toUpperCase()},{label:"Provider",value:C.displayName}],showArgsInput:!0,showModelInput:U==="acp",initialArgs:"",initialModel:"",providerType:C.type},async()=>{const D=G.find(B=>B.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(D),_(U,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(Qr,{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(ba,{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?Dr(!!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:oa()}),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:bu()}),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(G=>G.providerSessionId===x.launchConfirmResumeId);if(!C)return null;const U=Yi(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:U.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:U.providerSessionId}),t.jsx("div",{className:"mt-1",children:U.metaLine}),U.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:U.updatedLabel}),U.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:U.preview})]})})()]}),onConfirm:x.handleConfirmLaunch,onCancel:x.closeLaunchConfirm}),u&&t.jsx(qi,{section:p,onSectionChange:v})]})}function Qi(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 Cp(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:ds(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,m,p,u;const a=Xs(n)?"cli":vs(n)?"acp":"ide",i=ds(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(Xs(n)?n.cliName||n.type:vs(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:vs(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((u=(p=(m=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:m.at)==null?void 0:p.call(m,-1))==null?void 0:u.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function Ip(e,s){const r=new Map;for(const n of s){const a=qt(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,v)=>v.timestamp-f.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=Ln(n),m=a.filter(f=>f.unread||f.requiresAction).length,p=Qi(n),u=[n.platform||"machine",p].filter(Boolean);return{id:n.id,label:Ct(n,{fallbackId:n.id}),subtitle:u.join(" · "),unread:m,total:a.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?iu(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 br(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 Ap({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:m,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:v,onRequestedMobileSectionConsumed:S,setSelectedTabKey:T,setScreen:d,setSelectedMachineId:b,setSection:N,setMachineBackTarget:h,resetMachineAction:w,markNotificationTargetRead:_}){const y=o.useRef(null),j=o.useCallback(k=>{if(!(k!=null&&k.sessionId))return;const g=_r(k,c),x=Math.max(Date.now(),os(k),g.lastUpdated||0);br("mark_read:start",{tabKey:k.tabKey,sessionId:k.sessionId,displayPrimary:lt(k),inboxBucket:g.inboxBucket,unread:g.unread,lastSeenAt:g.lastSeenAt,lastUpdated:g.lastUpdated,activityAt:os(k),readAt:x}),_({sessionId:k.sessionId,tabKey:k.tabKey}),l(qt(k)||k.routeId,"mark_session_seen",{sessionId:k.sessionId,seenAt:x}).then($=>{br("mark_read:result",{tabKey:k.tabKey,sessionId:k.sessionId,result:$})}).catch($=>{br("mark_read:error",{tabKey:k.tabKey,sessionId:k.sessionId,error:$ instanceof Error?$.message:String($)})})},[c,l]);return o.useEffect(()=>{var g;if(!n){d("inbox"),T(((g=e[0])==null?void 0:g.tabKey)||null),y.current=null;return}if(i!=="chat"){y.current=null;return}const k=`${n.tabKey}:${n.sessionId||""}`;y.current!==k&&(y.current=k,j(n))},[e,j,i,n,d,T]),o.useEffect(()=>{if(!m)return;const k=e.find(g=>g.tabKey===m);k&&(T(k.tabKey),d("chat"),p==null||p())},[e,p,m,d,T]),o.useEffect(()=>{if(!u)return;const k=s.find(g=>g.id===u);k&&(b(k.id),w(),N("machines"),h("inbox"),d("machine"),f==null||f())},[s,f,u,w,h,d,N,b]),o.useEffect(()=>{v&&(N(v),d("inbox"),S==null||S())},[S,v,d,N]),o.useEffect(()=>{const k=r.filter(g=>g.inboxBucket==="task_complete"||g.unread);k.length!==0&&br("inbox_state",{screen:i,selectedTabKey:a,items:k.map(g=>{const x=_r(g.conversation,c);return{liveState:x,tabKey:g.conversation.tabKey,sessionId:g.conversation.sessionId,displayPrimary:lt(g.conversation),serverBucket:x.inboxBucket,computedBucket:g.inboxBucket,serverUnread:x.unread,computedUnread:g.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,activityAt:os(g.conversation)}})})},[r,c,i,a]),{markConversationRead:j}}function Tp(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function bo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Mp(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Lp({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[m,p]=o.useState(null),u=o.useCallback(()=>{i("idle"),l(""),p(null)},[]),f=o.useCallback(async(h,w,_)=>{var y;try{i("loading"),l(`Launching ${w}…`);const j={ideType:w,enableCdp:!0};(y=_==null?void 0:_.workspacePath)!=null&&y.trim()&&(j.workspace=_.workspacePath.trim()),await e(h,"launch_ide",j),i("done"),l(`${w} launch requested`)}catch(j){i("error"),l(j instanceof Error?j.message:"Launch IDE failed"),console.error("Launch IDE failed",j)}},[e]),v=o.useCallback(async(h,w,_)=>{if(w.trim())try{i("loading"),l(_!=null&&_.createIfMissing?"Creating folder…":"Saving workspace…");const y=await e(h,"workspace_add",{path:w.trim(),createIfMissing:(_==null?void 0:_.createIfMissing)===!0});if(y!=null&&y.success){i("done"),l(_!=null&&_.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((y==null?void 0:y.error)||"Could not save workspace")}catch(y){i("error"),l(y instanceof Error?y.message:"Could not save workspace")}},[e]),S=o.useCallback(async h=>{var w,_,y,j,k,g;try{i("loading"),l("Starting daemon upgrade…");const x=await e(h,"daemon_upgrade",{});if((w=x==null?void 0:x.result)!=null&&w.alreadyLatest){i("done"),l(`Already on v${((_=x==null?void 0:x.result)==null?void 0:_.version)||"latest"}.`);return}if((y=x==null?void 0:x.result)!=null&&y.upgraded||(j=x==null?void 0:x.result)!=null&&j.success){i("done"),l(`Upgrade to v${((k=x==null?void 0:x.result)==null?void 0:k.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((g=x==null?void 0:x.result)==null?void 0:g.error)||"Upgrade failed")}catch(x){i("error"),l(x instanceof Error?x.message:"Upgrade failed")}},[e]),T=o.useCallback(async(h,w,_,y)=>{var g,x,$;const j=Date.now(),k={machineId:h,kind:w,providerType:_,workspaceId:(y==null?void 0:y.workspaceId)||null,workspacePath:(y==null?void 0:y.workspacePath)||null,resumeSessionId:(y==null?void 0:y.resumeSessionId)||null,startedAt:j};try{i("loading"),l(`Launching ${_}…`),p(k);const I={cliType:_};(g=y==null?void 0:y.workspacePath)!=null&&g.trim()?I.dir=y.workspacePath.trim():y!=null&&y.workspaceId&&(I.workspaceId=y.workspaceId),y!=null&&y.resumeSessionId&&(I.resumeSessionId=y.resumeSessionId),(x=y==null?void 0:y.args)!=null&&x.trim()&&(I.cliArgs=y.args.trim().split(/\s+/).filter(Boolean)),($=y==null?void 0:y.model)!=null&&$.trim()&&(I.initialModel=y.model.trim());const M=await e(h,"launch_cli",I),L=(M==null?void 0:M.result)||M,O=(L==null?void 0:L.sessionId)||(L==null?void 0:L.id);if(M!=null&&M.success&&O){p(null),i("done"),l(`${_} launched`),s(`/dashboard?activeTab=${encodeURIComponent(O)}`);return}if(M!=null&&M.success){i("loading"),l(`${_} launch requested — waiting for session…`);return}p(null),i("error"),l((M==null?void 0:M.error)||(L==null?void 0:L.error)||`Could not launch ${w.toUpperCase()} workspace`)}catch(I){if(Mp(I)){i("loading"),l(`${_} launch requested — waiting for session…`);return}p(null),i("error"),l(I instanceof Error?I.message:`Could not launch ${w.toUpperCase()} workspace`)}},[s,e]),d=o.useCallback(async(h,w)=>{try{const _=await e(h,"list_saved_sessions",{providerType:w,kind:"cli",limit:30}),y=(_==null?void 0:_.result)??_;return Array.isArray(y==null?void 0:y.sessions)?y.sessions:[]}catch(_){return console.error("Failed to list saved sessions on mobile:",_),[]}},[e]),b=o.useCallback(async(h,w)=>Xr(e,h,w),[e]);o.useEffect(()=>{var y;if(!m)return;const h=bo(m.workspacePath),w=r.find(j=>{var M,L,O,R;if(!j||j.type==="adhdev-daemon"||Tp(j.daemonId||j.id)!==m.machineId||(j.transport==="acp"?"acp":j.transport==="pty"?"cli":null)!==m.kind||String(j.agentType||j.type||"")!==m.providerType)return!1;const $=String(j.providerSessionId||"");if(m.resumeSessionId&&$)return $===m.resumeSessionId;if(h){const C=bo(j.workspace||j.runtimeWorkspaceLabel);return C?C===h:!1}return Number(j.lastUpdated||j._lastUpdate||j.timestamp||((R=(O=(L=(M=j.activeChat)==null?void 0:M.messages)==null?void 0:L.at)==null?void 0:O.call(L,-1))==null?void 0:R.timestamp)||0)>=m.startedAt-5e3});if(!w)return;const _=typeof w.sessionId=="string"&&w.sessionId?w.sessionId:typeof w.instanceId=="string"&&w.instanceId?w.instanceId:(y=n.find(j=>j.routeId===w.id))==null?void 0:y.sessionId;_&&(p(null),i("done"),l(`${m.providerType} launched`),s(`/dashboard?activeTab=${encodeURIComponent(_)}`))},[n,r,s,m]),o.useEffect(()=>{if(!m)return;const h=window.setTimeout(()=>{p(w=>!w||w.startedAt!==m.startedAt?w:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(h)},[m]);const N=o.useCallback(async(h,w)=>{if(w.kind==="ide"&&w.providerType){await f(h,w.providerType,{workspacePath:w.workspace||null});return}(w.kind==="cli"||w.kind==="acp")&&w.providerType&&await T(h,w.kind,w.providerType,{workspacePath:w.workspace||null,resumeSessionId:w.providerSessionId||null})},[f,T]);return{machineAction:{state:a,message:c},resetMachineAction:u,handleLaunchDetectedIde:f,handleAddWorkspace:v,handleMachineUpgrade:S,handleLaunchWorkspaceProvider:T,handleListSavedSessions:d,handleBrowseDirectory:b,handleOpenRecent:N}}function _p({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:m,setMachineBackTarget:p}){const u=o.useCallback(N=>{i(N.tabKey),c("chat"),n(N)},[n,c,i]),f=o.useCallback(N=>{const h=e.find(w=>w.routeId===N.routeId&&w.streamSource==="native");h&&(i(h.tabKey),c("chat"),n(h))},[e,n,c,i]),v=o.useCallback(()=>{n(s),c("inbox")},[n,s,c]),S=o.useCallback((N,h="inbox")=>{l(N),a(),m("machines"),p(h),c("machine")},[a,p,c,m,l]),T=o.useCallback(N=>{const h=qt(N);h&&S(h,"chat")},[S]),d=o.useCallback(()=>{a(),c(r)},[r,a,c]),b=o.useCallback(N=>{m(N),c("inbox")},[c,m]);return{openConversation:u,openNativeConversation:f,backFromConversation:v,openMachine:S,openConversationMachine:T,backFromMachine:d,changeMachineSection:b}}function Rp(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function Pp(e){const s=e instanceof Error?e.message:String(e||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function gr(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Dp({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,userName:m,requestedActiveTabKey:p,onRequestedActiveTabConsumed:u,requestedMachineId:f,onRequestedMachineConsumed:v,requestedMobileSection:S,onRequestedMobileSectionConsumed:T,onOpenHistory:d,onOpenRemote:b,onStopCli:N,wsStatus:h,isConnected:w,onShowHiddenConversation:_,onShowAllHiddenConversations:y,onHideConversation:j,onOpenNewSession:k,notificationStateBySessionId:g,onMarkNotificationTargetRead:x}){const[$,I]=o.useState(()=>{var Q;return((Q=e[0])==null?void 0:Q.tabKey)||null}),[M,L]=o.useState(()=>e[0]?"chat":"inbox"),[O,R]=o.useState("chats"),[C,U]=o.useState(null),[G,A]=o.useState("inbox"),D=Ls(),B="0.8.68",W=o.useMemo(()=>e.find(Q=>Q.tabKey===$)||e[0]||null,[e,$]),X=o.useMemo(()=>W?r.find(Q=>Q.id===W.routeId):void 0,[r,W]),xe=o.useMemo(()=>!W||Ye(W)||!et(W)?null:Is(W),[W]),Re=o.useMemo(()=>r.filter(Q=>Q.type==="adhdev-daemon").sort(Zn),[r]),ie=o.useMemo(()=>Re.find(Q=>Q.id===C)||null,[Re,C]),Ie=o.useMemo(()=>zr(r),[r]),te=Gr({sendDaemonCommand:a,activeConv:W||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),ce=Lp({sendDaemonCommand:a,navigate:D,ides:r,conversations:e}),oe=o.useMemo(()=>e.map(Q=>{const Ne=M==="chat"&&(W==null?void 0:W.tabKey)===Q.tabKey,Ue=Jn(Q,Ie,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Ne,notificationStateBySessionId:g}),Ee=os(Q),Ve=hi(Q);return{conversation:Q,timestamp:Ee,preview:Ve,unread:Ue.unread,requiresAction:Ue.requiresAction,isWorking:Ue.isWorking,inboxBucket:Ue.inboxBucket}}),[e,Ie,g,M,W]),{markConversationRead:ye}=Ap({conversations:e,machineEntries:Re,items:oe,selectedConversation:W,selectedTabKey:$,screen:M,liveSessionInboxState:Ie,sendDaemonCommand:a,requestedActiveTabKey:p,onRequestedActiveTabConsumed:u,requestedMachineId:f,onRequestedMachineConsumed:v,requestedMobileSection:S,onRequestedMobileSectionConsumed:T,setSelectedTabKey:I,setScreen:L,setSelectedMachineId:U,setSection:R,setMachineBackTarget:A,resetMachineAction:ce.resetMachineAction,markNotificationTargetRead:x}),ae=_p({conversations:e,selectedConversation:W,machineBackTarget:G,markConversationRead:ye,resetMachineAction:ce.resetMachineAction,setSelectedTabKey:I,setScreen:L,setSelectedMachineId:U,setSection:R,setMachineBackTarget:A}),F=o.useMemo(()=>gr(oe.filter(Q=>Q.requiresAction)),[oe]),be=o.useMemo(()=>gr(oe.filter(Q=>Q.unread&&!Q.requiresAction)),[oe]),se=o.useMemo(()=>gr(oe.filter(Q=>!Q.unread&&!Q.requiresAction&&Q.isWorking)),[oe]),pe=o.useMemo(()=>gr(oe.filter(Q=>!Q.unread&&!Q.requiresAction&&!Q.isWorking)),[oe]),J=o.useMemo(()=>ie?oe.filter(Q=>qt(Q.conversation)===ie.id):[],[oe,ie]),le=o.useMemo(()=>Cp(ie,r),[r,ie]),ne=(ie==null?void 0:ie.version)||null,ge=!!ie&&!!ne&&!0&&ne!==B,ue=o.useMemo(()=>(ie==null?void 0:ie.availableProviders)||[],[ie]),E=o.useMemo(()=>ue.filter(Q=>Q.category==="cli"&&Q.installed!==!1).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[ue]),ve=o.useMemo(()=>ue.filter(Q=>Q.category==="acp"&&Q.installed!==!1).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[ue]),he=o.useMemo(()=>Ip(Re,oe),[oe,Re]),Se=o.useCallback(async Q=>{ie&&await ce.handleOpenRecent(ie.id,Q)},[ce,ie]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:M==="chat"&&W?t.jsx(fp,{selectedConversation:W,isAcp:Ye(W),isStandalone:l,selectedIdeEntry:X,actionLogs:n,userName:m,isSendingChat:te.isSendingChat,isFocusingAgent:te.isFocusingAgent,handleModalButton:te.handleModalButton,handleRelaunch:te.handleRelaunch,onBack:ae.backFromConversation,onOpenNativeConversation:ae.openNativeConversation,onOpenMachine:ae.openConversationMachine,onHideConversation:j,onOpenHistory:d,onOpenRemote:b,onStopCli:N,cliViewMode:xe,onSetCliViewMode:async Q=>{if(W&&xe!==Q)try{await a(qt(W)||W.routeId,"set_cli_view_mode",{targetSessionId:W.sessionId,cliType:Dt(W),mode:Q})}catch(Ne){Pp(Ne)?console.warn("Skipped CLI view mode switch:",Ne instanceof Error?Ne.message:String(Ne)):console.error("Failed to switch CLI view mode:",Ne)}},handleSendChat:te.handleSendChat,handleFocusAgent:te.handleFocusAgent}):M==="machine"&&ie?t.jsx(Np,{selectedMachineEntry:ie,selectedMachineConversations:J,selectedMachineRecentLaunches:le,cliProviders:E,acpProviders:ve,selectedMachineNeedsUpgrade:ge,appVersion:B,machineAction:ce.machineAction,isStandalone:l,section:O,showBottomNav:G==="inbox",onBack:ae.backFromMachine,onSectionChange:ae.changeMachineSection,onOpenConversation:ae.openConversation,onOpenRecent:Se,onOpenMachineDetails:()=>D(`/machines/${ie.id}`),onMachineUpgrade:()=>ce.handleMachineUpgrade(ie.id),onLaunchDetectedIde:(Q,Ne)=>ce.handleLaunchDetectedIde(ie.id,Q,Ne),onAddWorkspace:(Q,Ne)=>ce.handleAddWorkspace(ie.id,Q,Ne),onBrowseDirectory:Q=>ce.handleBrowseDirectory(ie.id,Q),onLaunchWorkspaceProvider:(Q,Ne,Ue)=>ce.handleLaunchWorkspaceProvider(ie.id,Q,Ne,Ue),onListSavedSessions:Q=>ce.handleListSavedSessions(ie.id,Q)}):t.jsx(xp,{section:O,attentionItems:F,unreadItems:be,workingItems:se,completedItems:pe,hiddenConversations:s,machineCards:he,getAvatarText:Rp,onOpenConversation:ae.openConversation,onShowConversation:_,onShowAllHidden:y,onOpenNewSession:k,onOpenMachine:ae.openMachine,onOpenSettings:()=>D("/settings"),onSectionChange:R,wsStatus:h,isConnected:w,isStandalone:l})})}function bn(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function Ep({conversations:e,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,m]=o.useState(!1),[p,u]=o.useState(null),f=o.useCallback(()=>{c.current=0,m(!1),u(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",f),window.addEventListener("drop",f),()=>{window.removeEventListener("dragend",f),window.removeEventListener("drop",f)}),[f]);const v=o.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,m(!0))},[]),S=o.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!bn(s,r)){u("merge");return}const N=b.currentTarget.getBoundingClientRect(),h=b.clientX-N.left,w=N.width/3;h<w?u("split-left"):h>w*2?u("split-right"):u("merge")},[s,r]),T=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,m(!1),u(null))},[]),d=o.useCallback(b=>{c.current=0,m(!1);const N=b.dataTransfer.getData("text/tab-key"),h=N?e.some(_=>_.tabKey===N):!1,w=p;if(u(null),i(),!!N){if(b.preventDefault(),w==="split-left"&&bn(s,r)){r==null||r(N,"split-left");return}if(w==="split-right"&&bn(s,r)){r==null||r(N,"split-right");return}if(h){a(N);return}n==null||n(N)}},[e,p,s,r,n,a,i]);return{dragOver:l,dropAction:p,resetDragState:f,handleDragEnter:v,handleDragOver:S,handleDragLeave:T,handleDrop:d}}function $p(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 Bp({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(s??null),[l,m]=o.useState(r??[]),[p,u]=o.useState(null),f=o.useRef(null),v=o.useRef(null),S=o.useRef(n),T=o.useRef(a);o.useEffect(()=>{S.current=n},[n]),o.useEffect(()=>{T.current=a},[a]),o.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),o.useEffect(()=>{m(k=>{const g=$p(k,e);return g.length===k.length&&g.every((x,$)=>x===k[$])?k:g})},[e]);const d=o.useMemo(()=>{const k=p??l;if(k.length===0)return e;const g=new Map(k.map((x,$)=>[x,$]));return[...e].sort((x,$)=>{const I=g.get(x.tabKey)??999,M=g.get($.tabKey)??999;return I-M})},[e,p,l]);o.useEffect(()=>{var g,x;if(d.length===0){i!==null&&(c(null),(g=S.current)==null||g.call(S,null));return}if(i&&d.some($=>$.tabKey===i))return;const k=d[0].tabKey;k!==i&&(c(k),(x=S.current)==null||x.call(S,k))},[d,i]);const b=o.useMemo(()=>d.find(k=>k.tabKey===i),[d,i]),N=o.useCallback(k=>{var g;c(k),(g=S.current)==null||g.call(S,k)},[]),h=o.useCallback((k,g,x)=>{m($=>{var O;const I=$.filter(R=>R!==k),M=I.indexOf(g);if(M<0)return $;const L=x==="left"?M:M+1;return I.splice(L,0,k),(O=T.current)==null||O.call(T,I),I}),u(null)},[]),w=o.useCallback((k,g,x)=>{const I=(l.length>0?l:e.map(O=>O.tabKey)).filter(O=>O!==k),M=I.indexOf(g);if(M<0)return;const L=x==="left"?M:M+1;I.splice(L,0,k),f.current=I,u(I)},[l,e]),_=o.useCallback(()=>{var g;const k=f.current;k&&(m(k),(g=T.current)==null||g.call(T,k))},[]),y=o.useCallback(()=>{f.current=null,u(null)},[]),j=o.useCallback(k=>{m(g=>{var $;const x=g.filter(I=>I!==k);return x.push(k),($=T.current)==null||$.call(T,x),x})},[]);return{activeTabId:i,activeConv:b,sortedConversations:d,previewOrderRef:f,draggingTabRef:v,selectTab:N,handleTabReorder:h,updatePreviewOrder:w,commitPreviewOrder:_,clearPreviewOrder:y,moveTabToEnd:j,setDraggingTabKey:k=>{v.current=k}}}function Kp({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 ga({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(Gi,{}),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 Ji="adhdev-tab-shortcuts";function Zi(){try{return JSON.parse(localStorage.getItem(Ji)||"{}")}catch{return{}}}function ec({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>Zi()),[l,m]=o.useState(null),p=o.useCallback(f=>{const v=[];return f.metaKey&&v.push(a?"⌘":"Meta"),f.ctrlKey&&v.push("Ctrl"),f.altKey&&v.push(a?"⌥":"Alt"),f.shiftKey&&v.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(v.push(f.key.length===1?f.key.toUpperCase():f.key),v.join("+"))},[a]),u=o.useCallback(f=>{c(f);try{localStorage.setItem(Ji,JSON.stringify(f))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const f=v=>{if(v.preventDefault(),v.stopPropagation(),v.key==="Escape"){m(null);return}const S=p(v);if(!S)return;const T={...i};for(const[d,b]of Object.entries(T))b===S&&delete T[d];T[l]=S,u(T),m(null)};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[e,l,i,u,p]),o.useEffect(()=>{if(!e)return;const f=v=>{if(!(!v.ctrlKey&&!v.metaKey&&!v.altKey)){for(const[S,T]of Object.entries(i))if(s.includes(S)&&p(v)===T){v.preventDefault(),r(),n(S);return}}};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,i,s,r,n,p]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:m,saveShortcuts:u}}const Wp=o.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:m,onSelectTab:p,onConversationActivated:u,onPreviewReorder:f,onReorderTab:v,onCommitPreviewOrder:S,onClearPreviewOrder:T,onDragStateReset:d,onDragTabKeyChange:b,onReceiveTab:N,onOpenContextMenu:h,longPressTimer:w,isGroupActive:_}){const y=Rs(s),j=y.isGenerating?"agent-tab-generating":y.isWaiting?"agent-tab-waiting":"",k=y.isReconnecting,g=o.useCallback(U=>{l.current=s.tabKey,b(s.tabKey),U.dataTransfer.setData("text/tab-key",s.tabKey),U.dataTransfer.effectAllowed="move"},[s.tabKey,l,b]),x=o.useCallback(()=>{l.current=null,b(null),S(),T(),d()},[l,b,S,T,d]),$=o.useCallback(U=>{const G=l.current;if(!(!G||G===s.tabKey)&&U.dataTransfer.types.includes("text/tab-key")){U.preventDefault(),U.stopPropagation();const A=U.currentTarget.getBoundingClientRect(),D=U.clientX<A.left+A.width/2?"left":"right";f(G,s.tabKey,D)}},[s.tabKey,l,f]),I=o.useCallback(U=>{U.preventDefault(),U.stopPropagation();const G=U.dataTransfer.getData("text/tab-key");if(G&&G!==s.tabKey){const A=U.currentTarget.getBoundingClientRect(),D=U.clientX<A.left+A.width/2?"left":"right";c.includes(G)?v(G,s.tabKey,D):N&&N(G)}T()},[s.tabKey,c,v,N,T]),M=o.useCallback(U=>{U.stopPropagation(),m(),p(s.tabKey),u(s)},[s,u,m,p]),L=o.useCallback(U=>{U.preventDefault(),h(U.clientX,U.clientY,s.tabKey)},[s.tabKey,h]),O=o.useCallback(U=>{const G=U.touches[0];w.current=setTimeout(()=>{h(G.clientX,G.clientY,s.tabKey)},600)},[s.tabKey,w,h]),R=o.useCallback(()=>{w.current&&clearTimeout(w.current)},[w]),C=["adhdev-dockview-tab",j,r&&"is-active",_&&"is-group-active",k&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:C,draggable:!0,onDragStart:g,onDragEnd:x,onDragOver:$,onDrop:I,onClick:M,onContextMenu:L,onTouchStart:O,onTouchEnd:R,onTouchMove:R,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:y.isGenerating?t.jsx("div",{className:"tab-spinner"}):y.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):k?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):y.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:k?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ts(s)}):y.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[ts(s),t.jsx("span",{className:"connecting-dots"})]}):ts(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 Op({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:m,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:f,onDragStateReset:v,onDragTabKeyChange:S,onReceiveTab:T,onHideTab:d,isGroupActive:b,allowTabShortcuts:N=!0}){const[h,w]=o.useState(null),_=o.useRef(null),y=o.useRef(null),j=o.useMemo(()=>e.map(L=>L.tabKey),[e]);Zs("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(h==null?void 0:h.tabKey)||null});const{isMac:k,tabShortcuts:g,shortcutListening:x,setShortcutListening:$,saveShortcuts:I}=ec({enabled:N,sortedTabKeys:e.map(L=>L.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!h)return;const L=O=>{const R=document.querySelector("[data-pane-context-menu]");R&&R.contains(O.target)||w(null)};return window.addEventListener("mousedown",L,!0),()=>window.removeEventListener("mousedown",L,!0)},[h]),o.useEffect(()=>{const L=y.current;if(!L)return;const O=R=>{Math.abs(R.deltaY)<=Math.abs(R.deltaX)||(R.preventDefault(),L.scrollLeft+=R.deltaY)};return L.addEventListener("wheel",O,{passive:!1}),()=>L.removeEventListener("wheel",O)},[]);const M=o.useCallback((L,O,R)=>{w({x:L,y:O,tabKey:R})},[]);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:y,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(L=>t.jsx(Wp,{conv:L,isActive:s===L.tabKey,isDraggedTab:a.current===L.tabKey,isTaskCompleteUnread:n.has(L.tabKey),shortcut:N?g[L.tabKey]:void 0,conversationKeys:j,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:m,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:f,onDragStateReset:v,onDragTabKeyChange:S,onReceiveTab:T,onOpenContextMenu:M,longPressTimer:_,isGroupActive:b},L.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:[N&&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:L=>{L.stopPropagation(),$(h.tabKey),w(null)},children:["⌨ ",g[h.tabKey]?`Change shortcut (${g[h.tabKey]})`:"Set shortcut"]}),g[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 L={...g};delete L[h.tabKey],I(L),w(null)},children:"✕ Remove shortcut"})]}),d&&t.jsxs(t.Fragment,{children:[N&&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),w(null)},children:"🚫 Hide from Dashboard"})]})]}),N&&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:()=>$(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:L=>L.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. ",k?"⌘+1":"Ctrl+1",", ",k?"⌥+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 Hp({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:m,userName:p,groupIndex:u,onFocus:f,isSplitMode:v,numGroups:S,onMoveTab:T,onReceiveTab:d,style:b,onActiveTabChange:N,initialActiveTabId:h,initialTabOrder:w,onTabOrderChange:_,onHideTab:y,isFocused:j,allowTabShortcuts:k=!0}){const{sendCommand:g}=At(),x=o.useRef(null),{activeTabId:$,activeConv:I,sortedConversations:M,draggingTabRef:L,selectTab:O,handleTabReorder:R,updatePreviewOrder:C,commitPreviewOrder:U,clearPreviewOrder:G,moveTabToEnd:A,setDraggingTabKey:D}=Bp({conversations:e,initialActiveTabId:h,initialTabOrder:w,onActiveTabChange:N,onTabOrderChange:_}),B=Gr({sendDaemonCommand:a,activeConv:I,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),{dragOver:W,dropAction:X,resetDragState:xe,handleDragEnter:Re,handleDragOver:ie,handleDragLeave:Ie,handleDrop:te}=Ep({conversations:e,numGroups:S,onMoveTab:T,onReceiveTab:d,onOwnTabDrop:A,onClearPreviewOrder:G}),ce=I&&!Ye(I)&&Is(I)==="terminal",oe=o.useMemo(()=>I?s.find(se=>se.id===I.routeId):void 0,[s,I]),ye=o.useMemo(()=>I?n.filter(se=>se.routeId===I.tabKey):[],[n,I]),ae=o.useMemo(()=>zr(s),[s]),F=o.useMemo(()=>new Set(M.filter(se=>Ol(se,ae,{isOpenConversation:se.tabKey===$})).map(se=>se.tabKey)),[$,ae,M]);Zs("PaneGroup",{groupIndex:u,conversationCount:e.length,activeTabId:$,dragOver:W});const be=o.useCallback(se=>{se.streamSource==="agent-stream"&&se.agentType&&g(se.routeId,"focus_session",{agentType:se.agentType,...se.sessionId&&{targetSessionId:se.sessionId}}).catch(()=>{})},[g]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:f,style:{...b,outline:W?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(Op,{conversations:M,activeTabId:$,groupIndex:u,numGroups:S,unreadTabKeys:F,draggingTabRef:L,onFocus:f,onSelectTab:O,onConversationActivated:be,onPreviewReorder:C,onReorderTab:R,onCommitPreviewOrder:U,onClearPreviewOrder:G,onDragStateReset:xe,onDragTabKeyChange:D,onMoveTab:T,onReceiveTab:d,onHideTab:y,isGroupActive:j??!1,allowTabShortcuts:k}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:Re,onDragOver:ie,onDragLeave:Ie,onDrop:te,children:[W&&t.jsx(Kp,{dropAction:X,canSplit:!!(S<4&&T)}),I?t.jsx(xa,{activeConv:I,clearToken:r[I.tabKey]||0,isCliTerminal:!!ce,ideEntry:oe,terminalRef:x,handleModalButton:B.handleModalButton,handleRelaunch:B.handleRelaunch,handleSendChat:B.handleSendChat,isSendingChat:B.isSendingChat,handleFocusAgent:B.handleFocusAgent,isFocusingAgent:B.isFocusingAgent,actionLogs:ye,userName:p,isInputActive:!v||!!j}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(ga,{conversationsCount:e.length,isSplitMode:v,isStandalone:l,hasRegisteredMachines:m})})]})]})}function Up({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:m,setLocalUserMessages:p,setActionLogs:u,isStandalone:f,hasRegisteredMachines:v,userName:S,focusedGroup:T,setFocusedGroup:d,moveTabToGroup:b,splitTabRelative:N,closeGroup:h,handleResizeStart:w,groupActiveTabIds:_,setGroupActiveTabIds:y,groupTabOrders:j,setGroupTabOrders:k,toggleHiddenTab:g,allowTabShortcuts:x=!0}){return t.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:a.map(($,I)=>{const M=s&&n.length===r?`${n[I]}%`:void 0;return t.jsxs(nt.Fragment,{children:[s&&I>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:L=>w(I-1,L),onDoubleClick:()=>h(I),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(Hp,{style:s?{flexBasis:M??`${100/r}%`,flexGrow:M?0:1,flexShrink:M?0:1}:void 0,conversations:$,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:m,setLocalUserMessages:p,setActionLogs:u,isStandalone:f,hasRegisteredMachines:v,userName:S,groupIndex:I,isFocused:s&&T===I,onFocus:()=>d(I),isSplitMode:s,numGroups:r,onMoveTab:(L,O)=>{O==="left"&&I>0?b(L,I-1):O==="right"&&I<r-1?b(L,I+1):O==="split-left"&&r<4?N(L,I,"left"):O==="split-right"&&r<4&&N(L,I,"right")},onReceiveTab:L=>b(L,I),onActiveTabChange:L=>y(O=>(O[I]??null)===(L??null)?O:{...O,[I]:L}),initialActiveTabId:_[I],initialTabOrder:j[I],onTabOrderChange:L=>k(O=>{const R=O[I]||[];return R.length===L.length&&R.every((C,U)=>C===L[U])?O:{...O,[I]:L}}),onHideTab:g,allowTabShortcuts:x})]},I)})})}function tc({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?pt.onScreenshot("ide-page",(u,f)=>{if(u!==e)return;const v=new FileReader;v.onload=()=>i(v.result),v.readAsDataURL(f)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var u;return e?((u=pt.onStatus)==null?void 0:u.call(pt,(f,v)=>{f===e&&v!=null&&v.screenshotUsage&&l(v.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,s]),o.useEffect(()=>{const p=e?pt.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 m=o.useCallback(async(p,u)=>{const f=e?pt.get(e):null;return!f||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):f.sendInput(p,u,s)},[e,r,s]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:m}}const sc="adhdev-dashboard-action-shortcuts",Fp=1200,zp={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Vp(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function rt(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 rc(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:rt("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:rt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:rt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:rt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:rt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:rt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:rt("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:rt("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:rt("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:rt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:rt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:rt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:rt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:rt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:rt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:rt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:rt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:rt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:rt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:rt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:rt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:rt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:rt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:rt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:rt("toggleCliView",e)}]}function Hn(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function Kr(e){const s=Object.fromEntries(rc(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(sc)||"{}"),n={...s,...r};for(const[a,i]of Object.entries(zp))n[a]===i&&(n[a]=s[a]);return n}catch{return s}}function nc(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Gp({enabled:e=!0,onTrigger:s}){const r=Vp(),[n,a]=o.useState(()=>Kr(r)),[i,c]=o.useState(null),[l,m]=o.useState([]),p=o.useRef({parts:[],timer:null}),u=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(nc(d.key)),b.join("+"))},[r]),f=o.useCallback(d=>{a(d);try{localStorage.setItem(sc,JSON.stringify(d))}catch{}},[]);o.useEffect(()=>{const d=Kr(r),b=Object.entries(n),N=Object.entries(d);b.length===N.length&&b.every(([h,w])=>d[h]===w)||f(d)},[n,r,f]);const v=o.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),S=o.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},Fp))},[]);o.useEffect(()=>{if(!i)return;const d=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){c(null),m([]);return}const N=u(b);if(!N)return;const w=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(N);if(l.length===0&&w){m([N]);return}const y=[...l,N].slice(0,2).join(" "),j={...n};for(const[k,g]of Object.entries(j))g===y&&delete j[k];j[i]=y,f(j),c(null),m([])};return window.addEventListener("keydown",d,!0),()=>window.removeEventListener("keydown",d,!0)},[n,u,f,i,l]),o.useEffect(()=>{if(!e||i)return;const d=b=>{if(b.defaultPrevented)return;const N=u(b);if(!N)return;const h=b.metaKey||b.ctrlKey||b.altKey;if(Hn(b.target)&&!h)return;const w=p.current.parts,_=h?[N]:[...w.slice(-1),N].slice(-2),y=_.join(" "),j=_[_.length-1],k=Object.entries(n).filter(([,M])=>!!M),g=k.find(([,M])=>M===y);if(g){b.preventDefault(),v(),s(g[0]);return}if(k.some(([,M])=>M.startsWith(`${y} `))){b.preventDefault(),p.current.parts=_,S();return}const $=k.find(([,M])=>M===j);if($){b.preventDefault(),v(),s($[0]);return}if(k.some(([,M])=>M.startsWith(`${j} `))){b.preventDefault(),p.current.parts=[j],S();return}v()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n,S,e,u,s,v,i]),o.useEffect(()=>()=>v(),[v]);const T=o.useMemo(()=>rc(r),[r]);return{isMac:r,actionDefinitions:T,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:m,saveShortcuts:f}}function qp({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"}),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 Yp(e){return e.some(s=>s.type!=="adhdev-daemon")||e.some(s=>s.type==="adhdev-daemon"&&!!s.machine)}function go({hasStoredLayout:e,initialDataLoaded:s,visibleConversationCount:r,ides:n}){return!e||r>0?!1:s?!Yp(n):!0}const ac=o.createContext(null);function Jr(){const e=o.useContext(ac);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Ar(e){return lt(e)||e.tabKey}function Xp(e){return`remote:${e}`}function zt(e){return e.startsWith("remote:")}function yo(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function gn(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,m;try{s.focus(),(m=(l=e==null?void 0:e.body)==null?void 0:l.focus)==null||m.call(l)}catch{}})}catch{}}function yr(e,s){e.classList.remove(An.className,Tn.className),e.classList.add(s==="light"?An.className:Tn.className)}function vo(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 Qp(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 Jp(e,s,r){var l;const n=[s];let a;for(const m of n){let p;for(const u of m){const f=e.addPanel({id:u.tabKey,component:"conversation",title:Ar(u),params:{kind:"conversation",tabKey:u.tabKey},...p?{position:{referencePanel:p,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});p||(p=f.id)}a=p??a}const i=r??((l=s[0])==null?void 0:l.tabKey)??null;if(!i)return;const c=e.getPanel(i);c&&c.group.model.openPanel(c)}function wo(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!==Ar(n)&&a.api.setTitle(Ar(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:Ar(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 jo(e,s,r){var m,p;const n=r?Xp(r):null;for(const u of[...e.panels])zt(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=Bt(s,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=gi(a);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((m=e.activePanel)==null?void 0:m.id)??((p=e.panels.find(u=>!zt(u.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 Zp({params:e,api:s}){var f;const r=Jr(),n=o.useRef(null),[a,i]=o.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=Gr({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(s.isActive);const v=[s.onDidActiveChange(S=>i(S.isActive)),s.onDidActiveGroupChange(S=>{if(!s.isActive&&!S.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const S of v)S.dispose()}},[s]);const m=o.useMemo(()=>c?r.ides.find(v=>v.id===c.routeId):void 0,[r.ides,c]),p=o.useMemo(()=>c?r.actionLogs.filter(v=>v.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(ga,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,suppressGuide:r.hasDetachedConversationPanels})});const u=!Ye(c)&&Is(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(xa,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:u,ideEntry:m,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 ef({params:e}){var m;const s=Jr(),r=o.useMemo(()=>Bt([...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)||((m=r==null?void 0:r.routeId)==null?void 0:m.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:l}=tc({doId:a,targetSessionId:r?sa(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(Yo,{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 tf(){const e=Jr();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(ga,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,suppressGuide:e.hasDetachedConversationPanels})})}function sf(e){var S,T;Qp(e);const s=Jr(),r=o.useCallback(d=>{"button"in d&&d.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const d=Bt([...s.conversationsByTabKey.values()],e.params.routeId),b=((S=e.api.group.activePanel)==null?void 0:S.id)===e.api.id,N=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${b?" is-active":""}${N?" 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=((T=e.api.group.activePanel)==null?void 0:T.id)===e.api.id,i=e.api.isGroupActive,c=Jn(n,s.liveSessionInboxState,{isOpenConversation:a,notificationStateBySessionId:s.notificationStateBySessionId}),l=c.isReconnecting,m=c.isConnecting,p=c.isGenerating,u=c.isWaiting,f=c.unread,v=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"}):u?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:"○"}):m?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:ts(n)}):m?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ts(n)}):t.jsx("span",{children:ts(n)})})]}),v&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:v,children:v})]})}function rf({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:m,initialDataLoaded:p,userName:u,toggleHiddenTab:f,actionShortcuts:v,registerActionHandlers:S,onActiveTabChange:T,requestedActiveTabKey:d,requestedRemoteIdeId:b,onRequestedActiveTabConsumed:N,scrollToBottomRequest:h,notificationStateBySessionId:w}){var q,Be,Pe;const{theme:_}=ua(),{sendCommand:y}=At(),j=o.useRef(null),k=o.useRef(null),g=o.useRef(!1),x=o.useRef(!1),$=o.useRef(!1),I=o.useRef(null),M=o.useRef([]),[L,O]=o.useState(null),[R,C]=o.useState(!1),[U,G]=o.useState(!1),[A,D]=o.useState(0),B=o.useRef(null),W=o.useMemo(()=>Ui(typeof window<"u"?window.innerWidth:1280),[]),X=o.useRef(typeof window>"u"?{}:Km(W)),xe=o.useMemo(()=>new Map(e.map(K=>[K.tabKey,K])),[e]),Re=o.useMemo(()=>zr(r),[r]),ie=o.useMemo(()=>{const K=j.current;return K?K.groups.some(H=>{try{const z=H.model.location.type;return z!=="floating"&&z!=="popout"?!1:H.panels.some(V=>xe.has(V.id))}catch{return!1}}):!1},[xe,A,e]),Ie=o.useCallback(()=>{var K;(K=j.current)==null||K.focus()},[]),te=o.useCallback(K=>{const H=document,z=K.document;for(const Ce of H.querySelectorAll('link[rel="stylesheet"]')){const We=z.createElement("link");We.rel="stylesheet",We.href=Ce.href,Ce.crossOrigin&&(We.crossOrigin=Ce.crossOrigin),z.head.appendChild(We)}for(const Ce of H.querySelectorAll("style")){const We=z.createElement("style");We.textContent=Ce.textContent,z.head.appendChild(We)}const V=[];for(const Ce of H.styleSheets)try{for(const We of Ce.cssRules)We instanceof CSSStyleRule&&(We.selectorText===":root"||We.selectorText==="html")&&V.push(We.cssText)}catch{}if(V.length>0){const Ce=z.createElement("style");Ce.textContent=V.join(`
|
|
43
|
+
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:x,onCancel:()=>u(null)})]})}const Qu=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Ju(){const{preference:e,setPreference:s}=ua();return t.jsx("div",{className:"flex gap-2",children:Qu.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 Zu(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 em(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function mn(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function so(e){const{r:s,g:r,b:n}=em(e);return .2126*mn(s)+.7152*mn(r)+.0722*mn(n)}function ro(e,s){const r=so(e),n=so(s),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function _i(e){const s=Zu(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return ro(s,r)>=ro(s,n)?r:n}const $n={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},Bn={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},tm=[{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"}}}],Ri="adhdev-chat-theme",Pi="adhdev-chat-theme-custom";function Cr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Ri)||"ember"}catch{return"ember"}}function Et(e){try{const s=localStorage.getItem(Pi);if(s){const r=JSON.parse(s);return{...e==="dark"?$n:Bn,...r[e]}}}catch{}return e==="dark"?$n:Bn}function pr(e,s){try{localStorage.setItem(Pi,JSON.stringify({dark:e,light:s}))}catch{}}function Mt(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 $r(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 sm={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Vs(e,s){var a;const r=(a=sm[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",$r(r,24)),n.style.setProperty("--accent-on-primary",_i(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${$r(r,18)})`),n.style.setProperty("--border-accent",Mt(r,.35)),n.style.setProperty("--nav-active-bg",Mt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Mt(r,.06)}`)}function ns(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",Mt(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",Mt(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",Mt(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",Mt(e.borderSubtle,.5)),s.style.setProperty("--border-default",Mt(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",$r(e.accentColor,30)),s.style.setProperty("--accent-on-primary",_i(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${$r(e.accentColor,40)})`),s.style.setProperty("--border-accent",Mt(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",Mt(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Mt(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 ${Mt(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 ma(){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 rm(e){try{localStorage.setItem(Ri,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=as()?"dark":"light";ns(Et(s))}else ma(),Vs(e,as()?"dark":"light")}function nm(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Cr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=as()?"dark":"light";ns(Et(s))}else ma(),Vs(e,as()?"dark":"light")}function as(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function wt({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 $s({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 am({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,a]=o.useState(()=>Et(r));o.useEffect(()=>{a(Et(r))},[r]);const i=o.useCallback((c,l)=>{a(m=>{const p={...m,[c]:l},f=Et(r==="dark"?"light":"dark");return r==="dark"?pr(p,f):pr(f,p),ns(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($s,{title:"App Background",children:[t.jsx(wt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),t.jsx(wt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),t.jsx(wt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),t.jsxs($s,{title:"App Text",children:[t.jsx(wt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),t.jsx(wt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),t.jsx(wt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),t.jsxs($s,{title:"Borders & Accent",children:[t.jsx(wt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),t.jsx(wt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),t.jsx(wt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),t.jsxs("div",{children:[t.jsxs($s,{title:"Chat Bubbles",children:[t.jsx(wt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),t.jsx(wt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),t.jsx(wt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),t.jsx(wt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),t.jsxs($s,{title:"Chat Layout",children:[t.jsx(wt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),t.jsx(wt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),t.jsx(wt,{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?$n:Bn,m=Et(e?"light":"dark");e?pr(c,m):pr(m,c),a(c),ns(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 om(){const[e,s]=o.useState(Cr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Et("dark"));o.useEffect(()=>{n(as());const m=new MutationObserver(()=>{const f=as();n(f);const v=Cr();v==="custom"?ns(Et(f?"dark":"light")):Vs(v,f?"dark":"light")});m.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const p=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const f=as();n(f);const v=Cr();v==="custom"?ns(Et(f?"dark":"light")):Vs(v,f?"dark":"light")};return p.addEventListener("change",u),()=>{m.disconnect(),p.removeEventListener("change",u)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?ns(Et(r?"dark":"light")):(ma(),Vs(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Et(r?"dark":"light"))},[r]);const c=m=>{s(m),rm(m)},l=[...tm,{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(m=>{const p=e===m.id,u=r?m.preview.dark:m.preview.light,f=m.id==="honey"||m.id==="ember"?"#1a1a1a":m.id==="custom"?a.userText:"#fff";return t.jsxs("button",{onClick:()=>c(m.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:u.containerBg},children:[t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"Hello! How can I help?"}),t.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.userBubble,color:f},children:"Fix the bug please"}),t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"On it! ✨"})]}),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:m.id==="custom"?"🎨 Custom":m.name}),t.jsx("div",{className:"text-[10px] text-text-muted",children:m.description})]})]})]},m.id)})}),e==="custom"&&t.jsx(am,{dark:r,onColorsChange:m=>i(m)})]})}const Di="adhdev_mobileDashboardMode_v1";function Ei(){try{return localStorage.getItem(Di)==="workspace"?"workspace":"chat"}catch{return"chat"}}function im(e){try{localStorage.setItem(Di,e)}catch{}}function cm(){const[e,s]=o.useState(!0);return o.useEffect(()=>{s(Ei()==="chat")},[]),t.jsx(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ht,{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),im(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}function lm(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 dm(e,s){const{sendData:r}=At(),{injectEntries:n,getIdes:a}=Lr(),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(m=>Gt.subscribe({sendData:r},m,{type:"subscribe",topic:"machine.runtime",key:`machine:${m}`,params:{intervalMs:s==null?void 0:s.intervalMs}},p=>{const u=a().find(v=>v.id===m),f=lm(u,m,p);n([f])}));return()=>{l.forEach(m=>m())}},[i,a,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}const um=4e3;function $i(e,s){const{sendData:r}=At(),[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 m=Gt.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 m.initialSendAccepted?l=setTimeout(()=>{c(!1)},um):c(!1),()=>{l&&clearTimeout(l),m()}},[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 mm(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Bi(e){const{sendData:s}=At(),[r,n]=o.useState({});return o.useEffect(()=>{const a=mm(e);if(!a||!e.sessionId||!s){n({});return}const i=Gt.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}),ks.record({interactionId:c.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:c.status,modalButtonCount:Array.isArray(c.modalButtons)?c.modalButtons.length:0}})});return()=>{i()}},[e.daemonId,e.routeId,e.sessionId,s]),r}const Ki="adhdev_hiddenTabs";function pm(){try{const e=localStorage.getItem(Ki);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function hs(e){try{localStorage.setItem(Ki,JSON.stringify([...e]))}catch{}}function fm(){const[e,s]=o.useState(pm),r=o.useCallback(p=>{s(u=>{const f=new Set(u);return f.has(p)?f.delete(p):f.add(p),hs(f),f})},[]),n=o.useCallback(p=>{s(u=>{if(u.has(p))return u;const f=new Set(u);return f.add(p),hs(f),f})},[]),a=o.useCallback(p=>{s(u=>{if(!u.has(p))return u;const f=new Set(u);return f.delete(p),hs(f),f})},[]),i=o.useCallback(()=>{s(p=>{if(p.size===0)return p;const u=new Set;return hs(u),u})},[]),c=o.useCallback((p,u)=>{s(f=>{const v=new Set(f);for(const S of u)v.add(S);return hs(v),v})},[]),l=o.useCallback((p,u)=>{s(f=>{const v=new Set(f);for(const S of u)v.delete(S);return hs(v),v})},[]),m=o.useCallback(p=>e.has(p),[e]);return{hiddenTabs:e,toggleTab:r,hideTab:n,showTab:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:m}}function no(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 hm(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=no(a,s),c=Array.isArray(a.childSessions)?a.childSessions.map(m=>no(m,s)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function Wi(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 xm(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))Wi(s,a)===i&&(delete n[a],r=!0);return r?n:e}function bm({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{cd()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:bi(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return dd(a),o.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(l=>{const m=Date.now(),p={};for(const[u,f]of Object.entries(l))m-f<5e3&&(p[u]=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 m=l.filter(p=>p.timestamp>c).slice(-100);return m.length===l.length?l:m})},6e4);return()=>clearInterval(i)},[n]),null}function gm(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 os(e){const s=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1];return e.lastMessageAt||gm(s==null?void 0:s.receivedAt)||0}function Kn(e,s=0){return os(e)||e.lastUpdated||s||0}function Oi(e){return os(e)||e.lastUpdated||0}function Hi(e,s,r=Oi){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 Wn(e){var r;const s=jt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function ym(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!Wn(e)&&!e.title.trim()}function vm(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(Wn(r))-Number(Wn(s));if(n!==0)return n;const a=r.messages.length-s.messages.length;return a!==0?a:Hi(s,r)})[0]||null}function Bt(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=vm(a);return n?i&&ym(n)?i:n:i||r[0]||null}function wm(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 pn(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 jm(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 ao(e){if(!e)return"";const s=Array.isArray(e.messages)?e.messages:[],r=s[s.length-1],n=r?jm(Ns(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 km(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||""),ao(e.activeChat),...s.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastUpdated||""),ao(r.activeChat)].join(":"))].join("|")}function Sm(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 Nm(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 Cm(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 Im(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function Am(e){const s=Im(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=Ns(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Tm({ides:e,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:a}){const i=o.useMemo(()=>wm(e),[e]),c=o.useMemo(()=>ki(e),[e]),l=o.useRef([]),m=o.useRef([]),p=o.useRef([]),u=o.useRef(new Map),f=o.useRef(new Map),v=o.useMemo(()=>{const y=new Map,j=[];for(const $ of i){const{connectionState:I="new",machineName:M}=Si($,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),L=Nm($,r),O=km($),R=u.current.get($.id);if(R&&R.ide===$&&R.sourceSignature===O&&R.connectionState===I&&R.machineName===M&&Cm(R.localRefs,L)){y.set($.id,R),j.push(...R.conversations);continue}const C=da($,r,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),U={ide:$,sourceSignature:O,connectionState:I,machineName:M,localRefs:L,conversations:C};y.set($.id,U),j.push(...C)}u.current=y;const k=new Map,g=$=>{const I=Am($),M=f.current.get($.tabKey);if(M&&M.signature===I)return k.set($.tabKey,M),M.timestamp;const L={signature:I,timestamp:Oi($)||(M==null?void 0:M.timestamp)||0};return k.set($.tabKey,L),L.timestamp},x=[...j].sort(($,I)=>Hi($,I,g));return f.current=k,x},[i,r,s,c]),S=o.useMemo(()=>{const y=Sm(v,n);return pn(l.current,y)?l.current:(l.current=y,y)},[v,n]),T=o.useMemo(()=>{const y=new Map,j=Array.from(new Set(S.map(k=>k.routeId)));for(const k of j){const g=Bt(S,k);g&&y.set(k,g)}return y},[S]),d=o.useMemo(()=>{const y=new Map;for(const j of S)if(j.sessionId&&y.set(j.sessionId,j),j.streamSource==="native"&&j.sessionId){const k=T.get(j.routeId);k&&y.set(j.sessionId,k)}return y},[S,T]),b=o.useMemo(()=>{const y=new Map;for(const j of S)j.sessionId&&y.set(j.sessionId,j),y.set(j.routeId,T.get(j.routeId)||j),y.set(j.tabKey,j);return y},[S,T]),N=o.useCallback(y=>{if(y)return d.get(y)},[d]),h=o.useCallback(y=>{if(y)return b.get(y)},[b]),w=o.useMemo(()=>{const y=S.filter(j=>!a.has(j.tabKey));return pn(m.current,y)?m.current:(m.current=y,y)},[S,a]),_=o.useMemo(()=>{const y=w.map(j=>j.tabKey);return pn(p.current,y)?p.current:(p.current=y,y)},[w]);return{chatIdes:i,conversations:S,visibleConversations:w,visibleTabKeys:_,resolveConversationBySessionId:N,resolveConversationByTarget:h}}function Mm({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 m=new URLSearchParams(l);return m.delete("activeTab"),m},{replace:!0})},[n,s]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function Lm({ides:e,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:a}){o.useEffect(()=>{ct.setIdes(e)},[e]),o.useEffect(()=>{ct.setResolveAction((i,c,l)=>{s(i,c,l).catch(()=>{})})},[s]),o.useEffect(()=>{const i=ct.onToast(m=>{r(u=>u.some(v=>v.message===m.message&&m.timestamp-v.timestamp<3e3)?u:[...u.slice(-4),{id:m.id,message:m.message,type:m.type,timestamp:m.timestamp,targetKey:m.targetKey,actions:m.actions}]);const p=m.duration||5e3;setTimeout(()=>r(u=>u.filter(f=>f.id!==m.id)),p)}),c=ct.onSystemMessage((m,p)=>{var S,T;const u=a(m),f=(S=p._localId)==null?void 0:S.startsWith("sys_approval_"),v=!!(u&&(u.status==="waiting_approval"||(T=u.modalButtons)!=null&&T.length||u.modalMessage));f&&v||n(d=>({...d,[m]:[...d[m]||[],p]}))}),l=ct.onClearSystemMessage((m,p)=>{n(u=>{var f;return(f=u[m])!=null&&f.length?{...u,[m]:u[m].filter(v=>{var S;return!(v.role==="system"&&((S=v._localId)!=null&&S.startsWith(p)))})}:u})});return()=>{i(),c(),l()}},[r,n]),o.useEffect(()=>{const i=fi.on("status_event",c=>{ct.handleRawEvent(c,"ws")});return()=>{i()}},[]),o.useEffect(()=>{var c;const i=l=>{var b;const m=l.data;if((m==null?void 0:m.type)!=="notification_action"||typeof m.action!="string"||!m.action.startsWith("approval_")||!(m.daemonId||m.targetSessionId||m.targetKey))return;const p=m.targetSessionId||m.targetKey||m.daemonId,u=a(p),f=(u==null?void 0:u.routeId)||m.daemonId;if(!f)return;const v=Number(m.buttonIndex),S=m.button||((b=u==null?void 0:u.modalButtons)==null?void 0:b[v])||"Approve",T=String(S).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),d=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(T);s(f,"resolve_action",{action:d?"approve":"reject",button:S,...Number.isFinite(v)&&{buttonIndex:v},...(u==null?void 0:u.sessionId)&&{targetSessionId:u.sessionId},...m.targetSessionId&&{targetSessionId:m.targetSessionId}}).catch(N=>console.error("[SW Action] approval failed:",N))};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 _m="adhdev_dashboardLayout_v1",Rm="adhdev_dashboardDockview_v1",Pm="adhdev_dashboardDockviewHiddenRestore_v1",Bs={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function pa(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function Ui(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Fi(e){return`${_m}:${e}`}function Dm(e){const s=Fi(e);return pa(s,null)}function Em(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=Fi(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function zi(e){return`${Rm}:${e}`}function $m(e){const s=zi(e);return pa(s,null)}function Bm(e,s){try{const r=zi(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Vi(e){return`${Pm}:${e}`}function Km(e){const s=Vi(e);return pa(s,{})}function Wm(e,s){try{const r=Vi(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Om(){return{groupAssignments:[...Bs.groupAssignments],focusedGroup:Bs.focusedGroup,groupActiveTabIds:{...Bs.groupActiveTabIds},groupTabOrders:{...Bs.groupTabOrders},groupSizes:[...Bs.groupSizes]}}function Hm(){const[e]=o.useState(()=>Ui(typeof window<"u"?window.innerWidth:1280)),[s,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,m]=o.useState({}),[p,u]=o.useState([]),[f,v]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[S,T]=o.useState(!1),d=o.useCallback(()=>{if(S)return;const b=Dm(e)??Om();r(new Map(b.groupAssignments)),a(b.focusedGroup),c(b.groupActiveTabIds),m(b.groupTabOrders),u(b.groupSizes),T(!0)},[S,e]);return o.useEffect(()=>{S&&Em(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:p})},[S,e,s,n,i,l,p]),o.useEffect(()=>{const b=window.matchMedia("(max-width: 767px)"),N=h=>v(h.matches);return b.addEventListener("change",N),()=>b.removeEventListener("change",N)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:a,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:l,setGroupTabOrders:m,groupSizes:p,setGroupSizes:u,isMobile:f,hasHydratedStoredLayout:S,hydrateStoredLayout:d}}function Um(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=[s.providerSessionId,s.sessionId].filter(a=>typeof a=="string"&&a.length>0);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Fm({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:l,setSearchParams:m,historyModalOpen:p,activeConv:u,isRefreshingHistory:f,ides:v,handleRefreshHistory:S}){const T=o.useRef(!1),d=o.useRef(!1),b=o.useRef(null),N=o.useRef(!1);o.useEffect(()=>{if(!e||T.current||s.length===0)return;if(!a){i();return}const h=r(e);if(!h)return;const w=n.get(h.tabKey)??0;c(_=>({..._,[w]:h.tabKey})),l(w),T.current=!0,d.current=!0,b.current!=null&&(window.clearTimeout(b.current),b.current=null),m(_=>{const y=new URLSearchParams(_);return y.delete("activeTab"),y},{replace:!0})},[e,s,r,n,a,i,c,l,m]),o.useEffect(()=>{if(!(d.current||a)&&s.length!==0){if(!e){i(),d.current=!0;return}if(T.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){N.current=!1;return}if(!u||N.current||f)return;const h=v.find(w=>w.id===u.routeId);h&&(!h.chats||h.chats.length===0||Um(h.chats,u))&&(N.current=!0,S())},[p,u,f,v,S]),o.useEffect(()=>{if(!u)return;let h=null,w=0,_=-1,y=0;const j=()=>{h=null;const k=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(x=>x.offsetParent!==null);if(k.length===0){w<18&&(w+=1,h=requestAnimationFrame(j));return}let g=0;for(const x of k)x.scrollTop=x.scrollHeight,g+=x.scrollHeight;g===_?y+=1:(y=0,_=g),w+=1,!(y>=2||w>=18)&&(h=requestAnimationFrame(j))};return h=requestAnimationFrame(j),()=>{h!=null&&cancelAnimationFrame(h)}},[u==null?void 0:u.tabKey])}function zm({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[m,p]=o.useState(null),[u,f]=o.useState(null),v=o.useMemo(()=>{if(e||!n)return null;const N=l(n);return N&&!et(N)&&!Ye(N)?N:null},[e,n,l]),S=o.useMemo(()=>{const N=m==null?void 0:m.routeId;if(!N)return null;const h=m!=null&&m.tabKey?i.find(w=>w.tabKey===m.tabKey):a?i.find(w=>w.tabKey===a):null;return(h==null?void 0:h.routeId)===N?h:Bt(i,N)},[i,m,a]),T=o.useMemo(()=>{if(S)return c.find(N=>N.id===S.routeId)},[c,S]);o.useEffect(()=>{v&&(p({routeId:v.routeId,tabKey:Ha(v)}),f(v),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,v]);const d=o.useCallback(N=>{N&&(p({routeId:N.routeId,tabKey:Ha(N)}),f(N))},[]),b=o.useCallback(()=>{p(null),f(null)},[]);return{remoteDialogConv:S,remoteDialogIdeEntry:T,remoteDialogActiveConv:u,setRemoteDialogActiveConv:f,openRemoteDialog:d,closeRemoteDialog:b}}function ws(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:et(e)||Ye(e)?{agentType:Dt(e)}:e.streamSource==="agent-stream"?{agentType:Dt(e)}:s}function Js(e){return e?er(e):""}function Ks(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function fn(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=[s.providerSessionId,s.sessionId].filter(a=>typeof a=="string"&&a.length>0);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function oo({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:a,setLocalUserMessages:i,setClearedTabs:c}){const[l,m]=o.useState(!1),[p,u]=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]),v=o.useCallback(async(d,b)=>{try{const N=d||(s==null?void 0:s.daemonId)||"",h=await e(N,"switch_chat",{id:b,sessionId:b,...ws(s)}),w=h==null?void 0:h.result;if((h==null?void 0:h.success)===!0||w==="switched"||w==="switched-by-title")return;w===!1||w==="not_found"?Ks(a,"⚠️ Session tab not found — try refreshing history"):typeof w=="string"&&w.startsWith("error:")?Ks(a,`⚠️ Switch error: ${w}`):Ks(a,"⚠️ Session switch failed")}catch(N){console.error("Switch failed",N),Ks(a,`❌ Switch failed: ${N.message||"connection error"}`)}},[s,e,a]),S=o.useCallback(async()=>{if(!(!s||l)){m(!0);try{const d=Js(s);await e(d,"new_chat",{...ws(s)}),c(b=>({...b,[s.tabKey]:Date.now()})),i(b=>({...b,[s.tabKey]:[]}))}catch(d){console.error("New chat failed",d)}finally{m(!1)}}},[s,l,e,c,i]),T=o.useCallback(async()=>{var d,b;if(!(!s||p)){u(!0);try{const N=Js(s),h=async()=>e(N,"list_chats",{forceExpand:!0,...ws(s)});let w=await h(),_=(w==null?void 0:w.chats)||((d=w==null?void 0:w.result)==null?void 0:d.chats);fn(_,s)&&(await new Promise(y=>setTimeout(y,450)),w=await h(),_=(w==null?void 0:w.chats)||((b=w==null?void 0:w.result)==null?void 0:b.chats)),w!=null&&w.success&&Array.isArray(_)&&(n(s.routeId,_),fn(_,s)&&!fn(r,s)&&Ks(a,"⚠️ History dialog did not fully open — try once more"))}catch(N){console.error("Refresh history failed",N)}finally{u(!1)}}},[s,r,p,e,n,a]);return{isCreatingChat:l,isRefreshingHistory:p,handleLaunchIde:f,handleSwitchSession:v,handleNewChat:S,handleRefreshHistory:T}}function Vm(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 Gm(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function io(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 fr(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 m=a[l];typeof m=="number"&&m>0&&i.set(c,m)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function co(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 qm(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 Ym(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 lo(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 uo(e){return Array(e).fill(100/e)}function Xm({groupAssignments:e,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:a,groupSizes:i,setGroupSizes:c,isMobile:l,visibleConversations:m,visibleTabKeys:p}){const u=o.useRef(null),f=o.useMemo(()=>fr(e,p),[e,p]),v=f.assignments,S=o.useMemo(()=>l?1:f.groupCount,[f.groupCount,l]),T=S>1,d=o.useCallback((y,j)=>{s(k=>{const g=new Map(fr(k,p).assignments);return j===0?g.delete(y):g.set(y,j),g}),n(k=>({...k,[j]:y})),r(j)},[s,p,n,r]),b=o.useCallback(y=>{s(j=>{const k=fr(j,p).assignments,g=new Map;for(const[x,$]of k)$!==y&&($>y?g.set(x,$-1):g.set(x,$));return g}),c(j=>{if(j.length<=1)return[];const k=[...j];k.splice(y,1);const g=k.reduce((x,$)=>x+$,0);return g>0?k.map(x=>x/g*100):[]}),r(0)},[s,p,c,r]),N=o.useCallback((y,j)=>{j.preventDefault();const k=u.current;if(!k)return;const g=j.clientX,x=k.offsetWidth,$=i.length===S?[...i]:uo(S),I=L=>{const R=(L.clientX-g)/x*100,C=[...$];C[y]=Math.max(15,$[y]+R),C[y+1]=Math.max(15,$[y+1]-R),c(C)},M=()=>{document.removeEventListener("mousemove",I),document.removeEventListener("mouseup",M),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",I),document.addEventListener("mouseup",M)},[i,S,c]),h=o.useCallback((y,j,k)=>{if(S>=4)return;const g=k==="left"?j:j+1;s(x=>{const $=fr(x,p).assignments,I=new Map;for(const M of m){const L=$.get(M.tabKey)??0,O=L>=g?L+1:L;O>0&&I.set(M.tabKey,O)}return g>0&&I.set(y,g),I}),c(x=>{const $=x.length===S?[...x]:uo(S),I=$[j]??100/S,M=Math.max(15,I/2),L=Math.max(15,I/2),O=[...$];O[j]=M,O.splice(g,0,L);const R=O.reduce((C,U)=>C+U,0);return O.map(C=>C/R*100)}),n(x=>{const $=lo(x,g);return $[g]=y,$}),a(x=>{const $=lo(x,g);return $[g]=[y],$}),r(g)},[S,s,p,m,c,n,a,r]);o.useEffect(()=>{Vm(e,v)||s(v)},[e,v,s]),o.useEffect(()=>{const{mapping:y,usedGroups:j}=f;n(k=>{const g=co(k,y);return io(k,g)?k:g}),a(k=>{const g=co(k,y);return io(k,g)?k:g}),r(k=>{const g=l?0:qm(k,j,y);return k===g?k:g}),c(k=>{const g=l?[]:Ym(k,j,f.groupCount);return Gm(k,g)?k:g})},[f,l,n,a,r,c]);const w=o.useMemo(()=>{const y=Array.from({length:S},()=>[]);for(const j of m){const k=v.get(j.tabKey)??0,g=Math.min(k,S-1);y[g].push(j)}return y},[m,v,S]),_=o.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:u,normalizedGroupAssignments:v,numGroups:S,isSplitMode:T,groupedConvs:w,moveTabToGroup:d,closeGroup:b,handleResizeStart:N,splitTabRelative:h,clearAllSplits:_}}function Qm({ides:e,sendDaemonCommand:s}){const r="0.8.69",n=o.useMemo(()=>e.filter(u=>u.type!=="adhdev-daemon"?!1:Li(u,r)).sort((u,f)=>Number(zs(f,r))-Number(zs(u,r))),[r,e]),a=o.useMemo(()=>n.some(u=>zs(u,r)),[r,n]),[i,c]=o.useState(!1),[l,m]=o.useState({}),p=o.useCallback(async u=>{var f,v;m(S=>({...S,[u]:"upgrading"}));try{const S=await s(u,"daemon_upgrade",{});(f=S==null?void 0:S.result)!=null&&f.upgraded||(v=S==null?void 0:S.result)!=null&&v.success?m(T=>({...T,[u]:"done"})):m(T=>({...T,[u]:"error"}))}catch{m(S=>({...S,[u]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:p}}const On="adhdev_dashboard_notifications_v1",fa=80;function Ir(e,s=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:s}function Br(e){return{...e,createdAt:Ir(e.createdAt),updatedAt:Ir(e.updatedAt,e.createdAt),lastEventAt:Ir(e.lastEventAt,e.updatedAt||e.createdAt)}}function Jm(e){return e.providerSessionId||e.sessionId||e.tabKey||e.id}function Zm(e){return[e.type,e.providerSessionId||e.sessionId||e.tabKey||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function ep(e,s){const r=Date.now(),n=[];for(const a of e){const i=a.sessionId?s.get(a.sessionId):void 0;if(i!=null&&i.surfaceHidden)continue;const c=(i==null?void 0:i.inboxBucket)||"idle",l=c==="needs_attention"?"needs_attention":c==="task_complete"&&(i!=null&&i.unread)?"task_complete":null;if(!l)continue;const m=Ir(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),p=Zm({type:l,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(i==null?void 0:i.lastUpdated)||a.lastUpdated});n.push(Br({id:p,dedupKey:p,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:a.title||a.displayPrimary||a.agentName||a.tabKey,preview:a.lastMessagePreview||a.displaySecondary||"",createdAt:m,updatedAt:m,lastEventAt:m}))}return n.sort((a,i)=>i.updatedAt-a.updatedAt)}function tp(e,s,r=fa){const n=new Map;for(const i of e)i.deletedAt||n.set(i.id,Br(i));for(const i of s){const c=Br(i),l=n.get(c.id);if(!l){n.set(c.id,c);continue}n.set(c.id,{...l,...c,createdAt:l.createdAt,readAt:l.readAt,deletedAt:l.deletedAt})}const a=new Map;for(const i of Array.from(n.values())){if(i.deletedAt)continue;const c=Jm(i),l=a.get(c);if(!l){a.set(c,i);continue}(i.updatedAt>l.updatedAt||i.updatedAt===l.updatedAt&&i.createdAt>l.createdAt)&&a.set(c,i)}return Array.from(a.values()).sort((i,c)=>{const l=c.updatedAt-i.updatedAt;return l!==0?l:c.createdAt-i.createdAt}).slice(0,Math.max(0,r))}function sp(e,s,r=Date.now()){return e.map(n=>n.id===s?{...n,readAt:r,updatedAt:Math.max(n.updatedAt,r)}:n)}function rp(e,s){return e.map(r=>{if(r.id!==s)return r;const n={...r};return delete n.readAt,n})}function np(e,s,r=Date.now()){return e.map(n=>{const a=!!s.sessionId&&n.sessionId===s.sessionId,i=!!s.providerSessionId&&n.providerSessionId===s.providerSessionId,c=!!s.tabKey&&n.tabKey===s.tabKey;return!a&&!i&&!c?n:{...n,readAt:r,updatedAt:Math.max(n.updatedAt,r)}})}function ap(e,s){return e.filter(r=>r.id!==s)}function op(e){return e.filter(s=>!s.readAt&&!s.deletedAt).length}function ip(e){const s=new Map;for(const r of e){if(r.deletedAt)continue;const n=[r.providerSessionId,r.sessionId,r.tabKey].filter(Boolean);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 cp(){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(On),s=e?JSON.parse(e):[];return Array.isArray(s)?s.map(r=>Br(r)).filter(r=>!r.deletedAt):[]}catch{return[]}}function lp(e){if(!(typeof window>"u"))try{const s=e.filter(r=>!r.deletedAt).slice(0,fa);if(s.length===0){window.localStorage.removeItem(On);return}window.localStorage.setItem(On,JSON.stringify(s))}catch{}}function dp(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.updatedAt===a.updatedAt&&r.createdAt===a.createdAt&&r.readAt===a.readAt&&r.preview===a.preview&&r.title===a.title&&r.deletedAt===a.deletedAt:!1})}function up(e){const{conversations:s,liveSessionInboxState:r,maxItems:n=fa}=e,a=o.useMemo(()=>ep(s,r),[s,r]),[i,c]=o.useState(()=>cp());o.useEffect(()=>{c(S=>{const T=tp(S,a,n);return dp(S,T)?S:T})},[a,n]),o.useEffect(()=>{lp(i)},[i]);const l=o.useMemo(()=>op(i),[i]),m=o.useMemo(()=>ip(i),[i]),p=o.useCallback((S,T)=>{c(d=>sp(d,S,T))},[]),u=o.useCallback(S=>{c(T=>rp(T,S))},[]),f=o.useCallback((S,T)=>{c(d=>np(d,S,T))},[]),v=o.useCallback(S=>{c(T=>ap(T,S))},[]);return{notifications:i,unreadCount:l,notificationStateBySessionId:m,markRead:p,markUnread:u,markTargetRead:f,deleteNotification:v}}function mp(e,s,r=2e3){return e?e.tabKey===s.tabKey&&e.message===s.message&&s.timestamp-e.timestamp<r:!1}function pp(e,s){return e?e.tabKey===s.tabKey&&e.message===s.message&&e.timestamp===s.timestamp?null:e:null}function mo(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function ha(e){return e instanceof Error?e.message:String(e||"")}function po(e){const s=ha(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function fo(e,s){const r=ha(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function Gr({sendDaemonCommand:e,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:a}){const[i,c]=o.useState(!1),[l,m]=o.useState(!1),p=o.useRef(!1),u=o.useRef(null),f=o.useCallback(async d=>{if(!s)return;const b=d.trim();if(!b||p.current)return;const N=Date.now(),h={tabKey:s.tabKey,message:b,timestamp:N};if(mp(u.current,h))return;p.current=!0,m(!0),u.current=h;const w=`${N}-${Math.random().toString(36).slice(2,8)}`,_={role:"user",content:b,timestamp:N,_localId:w},y=!(et(s)||Ye(s));y&&r(j=>({...j,[h.tabKey]:[...j[h.tabKey]||[],_]}));try{const j=Js(s);if(!j)return;const k=await e(j,"send_chat",{message:b,...ws(s)}),g=mo(k);if(y&&(g!=null&&g.deduplicated||(g==null?void 0:g.sent)===!1)){r(x=>({...x,[h.tabKey]:(x[h.tabKey]||[]).filter($=>$._localId!==w)}));return}if((g==null?void 0:g.success)===!1)throw new Error((g==null?void 0:g.error)||"Send failed");setTimeout(()=>{const x=Date.now()-6e4;r($=>{const I=$[h.tabKey];if(!I)return $;const M=I.filter(L=>L.timestamp>x);return M.length===I.length?$:{...$,[h.tabKey]:M}})},6e4)}catch(j){const k=ha(j);k.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",k):console.error("Send failed",j),u.current=pp(u.current,h),y&&r(g=>({...g,[h.tabKey]:(g[h.tabKey]||[]).filter(x=>x._localId!==w)})),n(g=>[...g,{routeId:h.tabKey,text:`❌ **Send failed** — ${k||"Unknown error"}`,timestamp:Date.now()}])}finally{p.current=!1,m(!1)}},[s,e,n,r]),v=o.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await e(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(d){console.error("Relaunch failed",d)}},[s,e]),S=o.useCallback(async d=>{if(s)try{const N=(s.modalButtons||[]).indexOf(d),h=d.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),w=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(h),_=Js(s);if(!_)return;const y=await e(_,"resolve_action",{button:d,action:w?"approve":"reject",...N>=0&&{buttonIndex:N},...ws(s)}),j=mo(y);j.success||n(k=>[...k,{routeId:s.tabKey,text:fo(d,j==null?void 0:j.error),timestamp:Date.now()}])}catch(b){po(b)||console.error("[ModalButton] Error:",b),n(N=>[...N,{routeId:s.tabKey,text:po(b)?fo(d,b):`❌ **${d}** error`,timestamp:Date.now()}])}},[s,e,n]),T=o.useCallback(async()=>{if(!(!s||i)){c(!0);try{await e(s.routeId,"focus_session",{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(d){console.error("Focus agent failed",d)}finally{c(!1)}}},[s,i,e]);return{isSendingChat:l,isFocusingAgent:i,handleSendChat:f,handleRelaunch:v,handleModalButton:S,handleFocusAgent:T}}const xa=o.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:m,isSendingChat:p,handleFocusAgent:u,isFocusingAgent:f,actionLogs:v,userName:S,scrollToBottomRequestNonce:T,isInputActive:d=!0}){const b=Bi(s),N=b.status||b.modalMessage||b.modalButtons?{...s,...b.status?{status:b.status}:{},...b.modalMessage!==void 0?{modalMessage:b.modalMessage}:{},...b.modalButtons!==void 0?{modalButtons:b.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(Qo,{activeConv:N,onModalButton:c}),N.transport!=="pty"&&N.transport!=="acp"&&N.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(ls,{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,N.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(du,{activeConv:N,clearToken:r,terminalRef:i,handleSendChat:m,isSendingChat:p,isVisible:n})}),!n&&t.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(Dn,{activeConv:N,ideEntry:a,handleSendChat:m,isSendingChat:p,handleFocusAgent:u,isFocusingAgent:f,actionLogs:v,userName:S,scrollToBottomRequestNonce:T,isInputActive:d})})]}):t.jsx(Dn,{activeConv:N,ideEntry:a,handleSendChat:m,isSendingChat:p,handleFocusAgent:u,isFocusingAgent:f,actionLogs:v,userName:S,scrollToBottomRequestNonce:T,isInputActive:d})]})},(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.handleFocusAgent===s.handleFocusAgent&&e.isFocusingAgent===s.isFocusingAgent&&e.actionLogs===s.actionLogs&&e.userName===s.userName&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&e.isInputActive===s.isInputActive);function fp({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,isFocusingAgent:l,onBack:m,onOpenNativeConversation:p,onOpenMachine:u,onOpenHistory:f,onOpenRemote:v,onHideConversation:S,onStopCli:T,cliViewMode:d,onSetCliViewMode:b,handleSendChat:N,handleFocusAgent:h,handleModalButton:w,handleRelaunch:_}){const y=o.useRef(null),j=et(e)&&!s,k=j&&d==="terminal",g=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:`flex items-center justify-between gap-3 ${g} 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:m,type:"button","aria-label":"Back",children:t.jsx(Gn,{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(ci,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>p(e),onOpenMachine:()=>u(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[j&&d&&t.jsx(na,{mode:d,onChange:b,compact:!0}),j&&T&&t.jsx("button",{onClick:()=>{T(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(kt,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:t.jsx(Yn,{size:14})}),!s&&!j&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>v(e),type:"button",children:t.jsx(It,{size:14})}),S&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(e),type:"button",title:"Close chat",children:t.jsx(kt,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(xa,{activeConv:e,clearToken:0,isCliTerminal:k,ideEntry:n,terminalRef:y,handleModalButton:w,handleRelaunch:_,handleSendChat:N,isSendingChat:c,handleFocusAgent:h,isFocusingAgent:l,actionLogs:a,userName:i})})]})}const hn={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 hp(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Gi(){const[e,s]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{s(hp())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(hn[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:hn[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:hn[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 qi({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:It},{key:"chats",label:"Chats",icon:Ht}];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 hr({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 xs({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 Ws({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 xr({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:m,isConnecting:p}=Rs(e.conversation),u=lt(e.conversation),f=ms(e.conversation),v=xi(e.conversation,{requiresAction:s==="needs_attention"}),S=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",T=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",N=c?"text-text-secondary opacity-80":"text-text-muted",h=c?"text-text-muted opacity-80":"text-text-muted",w="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] ${S}`,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 ${T}`,style:a?{color:"var(--accent-on-primary)"}:void 0,children:r(u)}),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:u}),!i&&t.jsx("span",{className:`text-[11px] font-medium shrink-0 ${h}`,children:Xo(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${b}`,children:[f,m?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${w} 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…"})]}):v==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:w,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${N}`,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 ho({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 xp({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:m,onShowConversation:p,onShowAllHidden:u,onOpenNewSession:f,onOpenMachine:v,onOpenSettings:S,onSectionChange:T,wsStatus:d="connected",isStandalone:b=!1}){const N=d==="disconnected"||d==="reconnecting"||d==="offline"||d==="auth_failed",h=c.length>0,w=s.length>0||r.length>0||n.length>0||a.length>0,_=e==="machines"?"Machines":"Chats",y=b?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",j=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 ${y}`,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(Ur,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:S,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(Or,{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] ${j}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:N?t.jsx(Ws,{icon:t.jsx(ho,{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(Ws,{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(Gi,{})})}):t.jsx(xs,{children:c.map((k,g)=>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] ${g>0?"border-t border-border-subtle/70":""}`,onClick:()=>v(k.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(k.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:k.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:k.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[k.unread," new"]}):k.total>0?`${k.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:k.subtitle}),k.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[k.total," chat",k.total!==1?"s":"",k.unread>0?` · ${k.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},k.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(hr,{title:"Needs attention",className:"mb-0"}),t.jsx(xs,{children:s.map((k,g)=>t.jsx("div",{className:g>0?"border-t border-border-subtle/70":"",children:t.jsx(xr,{item:k,type:"needs_attention",getAvatarText:l,onOpenConversation:m})},k.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(hr,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(xs,{children:r.map((k,g)=>t.jsx("div",{className:g>0?"border-t border-border-subtle/70":"",children:t.jsx(xr,{item:k,type:"task_complete",getAvatarText:l,onOpenConversation:m})},k.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(hr,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(xs,{children:n.map((k,g)=>t.jsx("div",{className:g>0?"border-t border-border-subtle/70":"",children:t.jsx(xr,{item:k,type:"working",getAvatarText:l,onOpenConversation:m})},k.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(hr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?t.jsx(xs,{children:a.map((k,g)=>t.jsx("div",{className:g>0?"border-t border-border-subtle/70":"",children:t.jsx(xr,{item:k,type:"earlier",getAvatarText:l,onOpenConversation:m})},k.conversation.tabKey))}):w?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):N?t.jsx(Ws,{icon:t.jsx(ho,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):h?t.jsx(Ws,{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(Ht,{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(Ws,{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:u,children:"Restore all"})]}),t.jsx(xs,{className:"bg-bg-secondary/25",children:i.map((k,g)=>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 ${g>0?"border-t border-border-subtle/70":""}`,onClick:()=>p(k),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(k))}),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(k)}),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:ms(k)}),t.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},k.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(qi,{section:e,onSectionChange:T})]})}function bp(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 Yi(e){const s=[e.workspace||"Workspace unknown"],r=ds(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=bp(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function qr(...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 gp(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 Yr(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=gp(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 yp(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 vp(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Xr(e,s,r){const n=await e(s,"file_list_browse",{path:r}),a=vp(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,u)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${u}`:p==="/"||p==="\\"?`${c}${u}`:`${p.replace(/[\\/]+$/,"")}${c}${u}`,m=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,u)=>p.name.localeCompare(u.name)):[];return{path:i,directories:m}}function Qr({title:e,description:s,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:m,onConfirm:p}){const[u,f]=o.useState(r);o.useEffect(()=>{f(r)},[r]);const v=yp(r),S=u.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(kt,{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:()=>{!v||a||m(v)},disabled:!v||a,children:[t.jsx(Gn,{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:u,onChange:T=>f(T.target.value),onKeyDown:T=>{T.key!=="Enter"||!S||a||(T.preventDefault(),m(S))},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:()=>{!S||a||m(S)},disabled:!S||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(T=>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:()=>m(T.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(Ss,{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:T.name}),t.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:T.path})]})]},T.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(S||r),disabled:!S&&!r||a,children:c})]})]})})}function ba({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:m=!1,showArgsInput:p,argsValue:u,onArgsChange:f,showModelInput:v,modelValue:S,onModelChange:T,historyProviderNode:d,onConfirm:b,onCancel:N}){const h=n==null?void 0:n.find(w=>w.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:N,"aria-label":"Close launch confirmation",children:t.jsx(kt,{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:w=>i(w.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:m,children:n.map(w=>t.jsx("option",{value:w.key,children:w.label},w.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(w=>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:w.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:w.value})]},`${w.label}:${w.value}`)),v&&T&&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:S||"",onChange:w=>T(w.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:m})]}),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:u||"",onChange:w=>f(w.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:m})]})]}),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:N,disabled:m,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:m,children:[t.jsx(Xn,{size:14}),m?l:c]})]})]})})}function xo(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function is(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 m of s.workspaces||[])i.push({key:`saved:${m.id}`,label:`${m.id===s.defaultWorkspaceId?"⭐ ":""}${xo(m.path,m.label)}`,description:m.path,workspaceId:m.id,workspacePath:m.path});const c=(r==null?void 0:r.trim())||"",l=c?(s.workspaces||[]).find(m=>m.path===c):null;if(c&&!l&&i.push({key:`custom:${c}`,label:xo(c),description:c,workspaceId:null,workspacePath:c}),n){const m=`saved:${n}`;if(i.some(p=>p.key===m))return{options:i,selectedKey:m}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function wp(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function jp(e){return[wp(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function kp(e){return e.lastLaunchedAt?Fr(e.lastLaunchedAt):""}function Xi(e){return{metaText:jp(e),updatedLabel:kp(e)}}function xn(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function Sp({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var dt,ut,ht,ot;const c=tr(),[l,m]=o.useState(!1),p=(((dt=e.detectedIdes)==null?void 0:dt.length)||0)>0,u=o.useMemo(()=>(e.workspaces||[]).map(de=>({id:de.id,path:de.path,label:de.label})),[e]),f=e.defaultWorkspaceId||null,[v,S]=o.useState(f||((ut=u[0])==null?void 0:ut.id)||""),[T,d]=o.useState(""),[b,N]=o.useState(""),[h,w]=o.useState([]),[_,y]=o.useState(!1),[j,k]=o.useState(""),[g,x]=o.useState(!1),[$,I]=o.useState(xn(p,s.length,r.length)),M=o.useRef(null),[L,O]=o.useState(null),R=o.useRef("__home__"),[C,U]=o.useState("__home__"),[G,A]=o.useState(""),[D,B]=o.useState(""),[W,X]=o.useState(""),[xe,Re]=o.useState([]),[ie,Ie]=o.useState(()=>gt().textQuery),[te,ce]=o.useState(()=>gt().workspaceQuery),[oe,ye]=o.useState(()=>gt().modelQuery),[ae,F]=o.useState(()=>gt().resumableOnly),[be,se]=o.useState(()=>gt().sortMode),[pe,J]=o.useState(!1),[le,ne]=o.useState(!1),ge=o.useRef(null),ue=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const E=v==="__custom__"?T.trim():((ht=u.find(de=>de.id===v))==null?void 0:ht.path)||"",ve=v==="__custom__"&&!!E&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),he=v!=="__custom__"&&((ot=u.find(de=>de.id===v))==null?void 0:ot.path)||"",Se=o.useMemo(()=>(e.recentLaunches||[]).map(de=>de.workspace),[e]),Q=o.useCallback(async de=>{y(!0),k("");try{const ze=await a(de);N(ze.path),d(ze.path),w(ze.directories)}catch(ze){k(ze instanceof Error?ze.message:"Could not load folder")}finally{y(!1)}},[a]),Ne=o.useCallback(()=>{var ze;S("__custom__"),x(!0);const de=Yr(e.platform,qr(T.trim(),he,Se,e.defaultWorkspacePath,(ze=u.find(Je=>Je.id===f))==null?void 0:ze.path,u.map(Je=>Je.path)));Q(de)},[T,f,Q,Se,he,e.platform,u]),Ue=o.useCallback(de=>{if(de!=null&&de.workspaceId){S(de.workspaceId),d("");return}if(de!=null&&de.workspacePath){S("__custom__"),d(de.workspacePath);return}S(""),d("")},[]),Ee=o.useCallback(de=>{if(S(de),de==="__custom__"){Ne();return}d("")},[Ne]),Ve=o.useCallback(de=>{S("__custom__"),d(de)},[]),Xe=o.useCallback((de,ze)=>{M.current=ze,R.current=de.selectedWorkspaceKey||"__home__",U(de.selectedWorkspaceKey||"__home__"),A(de.initialArgs||""),B(de.initialModel||""),X(""),Re([]);const Je=de.providerType?`${e.id}:${de.providerType}`:null;if(fu(ue.current,Je)){const tt=gt();Ie(tt.textQuery),ce(tt.workspaceQuery),ye(tt.modelQuery),F(tt.resumableOnly),se(tt.sortMode)}ue.current=Je,O(de),de.providerType&&i&&(J(!0),i(de.providerType).then(tt=>Re(tt||[])).catch(tt=>console.warn("Failed to load saved sessions",tt)).finally(()=>J(!1)))},[i,e.id]),Qe=o.useMemo(()=>yi(xe,{textQuery:ie,workspaceQuery:te,modelQuery:oe,resumableOnly:ae,sortMode:be}),[oe,ae,xe,be,ie,te]);o.useEffect(()=>{W&&(Qe.some(de=>de.providerSessionId===W)||X(""))},[Qe,W]);const ft=o.useCallback(()=>{M.current&&(ne(!0),M.current().finally(()=>{M.current=null,ne(!1),O(null)}))},[]),Ge=o.useCallback(()=>{M.current=null,O(null)},[]),bt=o.useCallback(de=>{R.current=de,U(de)},[]);return o.useEffect(()=>{var de;ge.current!==e.id&&(ge.current=e.id,S(f||((de=u[0])==null?void 0:de.id)||"__custom__"),d(""),N(""),w([]),k(""),x(!1),Ie(gt().textQuery),ce(gt().workspaceQuery),ye(gt().modelQuery),F(gt().resumableOnly),se(gt().sortMode),ue.current=null,I(xn(p,s.length,r.length)))},[r.length,s.length,f,p,e.id,u]),o.useEffect(()=>{var de;v!=="__custom__"&&(v&&u.some(ze=>ze.id===v)||S(f||((de=u[0])==null?void 0:de.id)||"__custom__"))},[f,v,u]),o.useEffect(()=>{$==="ide"&&p||$==="cli"&&s.length>0||$==="acp"&&r.length>0||I(xn(p,s.length,r.length))},[$,r.length,s.length,p]),{showAllRecent:l,setShowAllRecent:m,hasIdeOptions:p,workspaceRows:u,defaultWorkspaceId:f,workspaceChoice:v,customWorkspacePath:T,browseCurrentPath:b,browseDirectories:h,browseBusy:_,browseError:j,browseDialogOpen:g,activeLauncherKind:$,launchConfirm:L,launchConfirmWorkspaceKeyRef:R,launchConfirmWorkspaceKey:C,launchConfirmArgs:G,launchConfirmModel:D,launchConfirmResumeId:W,launchConfirmSavedSessions:xe,launchConfirmTextFilter:ie,launchConfirmWorkspaceFilter:te,launchConfirmModelFilter:oe,launchConfirmResumableOnly:ae,launchConfirmSortMode:be,filteredLaunchConfirmSavedSessions:Qe,launchConfirmSessionsLoading:pe,launchConfirmBusy:le,resolvedWorkspacePath:E,canCreateMissingWorkspace:ve,openBrowseDialog:Ne,loadBrowsePath:Q,handleWorkspaceChoiceChange:Ee,chooseCustomWorkspacePath:Ve,setCustomWorkspacePath:d,setBrowseDialogOpen:x,setActiveLauncherKind:I,openLaunchConfirm:Xe,handleConfirmLaunch:ft,closeLaunchConfirm:Ge,setWorkspaceSelectionFromOption:Ue,setLaunchConfirmWorkspaceKeyAndSync:bt,setLaunchConfirmArgs:A,setLaunchConfirmModel:B,setLaunchConfirmResumeId:X,setLaunchConfirmTextFilter:Ie,setLaunchConfirmWorkspaceFilter:ce,setLaunchConfirmModelFilter:ye,setLaunchConfirmResumableOnly:F,setLaunchConfirmSortMode:se}}function Np({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:m,section:p,showBottomNav:u,onBack:f,onSectionChange:v,onOpenConversation:S,onOpenRecent:T,onOpenMachineDetails:d,onMachineUpgrade:b,onLaunchDetectedIde:N,onAddWorkspace:h,onBrowseDirectory:w,onLaunchWorkspaceProvider:_,onListSavedSessions:y}){const j=C=>C==="ide"?"IDE":C==="cli"?"CLI":"ACP",k=r.slice(0,4),g=s.slice(0,3),x=Sp({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:w,onListSavedSessions:y}),$=o.useMemo(()=>k.map(C=>{const{metaText:U,updatedLabel:G}=Xi(C);return{key:`recent-launch:${C.id}`,primary:C.label,secondary:U,updatedLabel:G,onClick:()=>{const{options:A,selectedKey:D}=is({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspacePath:C.workspace});x.openLaunchConfirm({title:C.kind==="ide"?ss("restart-ide",C.label):C.providerSessionId?ia(C.label):ss("start-fresh",C.label),description:C.kind==="ide"?rs("restart-ide"):C.providerSessionId?ca():rs("start-fresh"),confirmLabel:C.kind==="ide"?Ts("restart-ide"):C.providerSessionId?Dr(!0):Ts("start-fresh"),busyLabel:C.kind==="ide"?Ms("restart-ide"):C.providerSessionId?aa(!0):Ms("start-fresh"),workspaceOptions:A,selectedWorkspaceKey:D,details:[{label:"Mode",value:j(C.kind)},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]},async()=>{const B=A.find(W=>W.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(B),await T({...C,workspace:(B==null?void 0:B.workspacePath)??null})})}}}),[x,T,k]),I=o.useMemo(()=>g.map(C=>({key:`recent-chat:${C.conversation.tabKey}`,primary:lt(C.conversation),secondary:ou(C.conversation,{timestampLabel:C.timestamp?Xo(C.timestamp):null}),unread:C.unread,onClick:()=>S(C.conversation)})),[S,g]),M=x.showAllRecent?$:$.slice(0,4),L=$.length>0,O=I.length>0,R=m?"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 ${R} 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(Gn,{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:Ct(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:[O&&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:I.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))})]}),L&&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:M.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))}),$.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 ${$.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?"⭐ ":"",Vr(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(Ss,{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:U,selectedKey:G}=is({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:U,selectedWorkspaceKey:G,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:C.name}]},async()=>{const A=U.find(D=>D.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(A),N(C.type,{workspacePath:(A==null?void 0:A.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 U=x.activeLauncherKind==="cli"?"cli":"acp",{options:G,selectedKey:A}=is({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 ${U.toUpperCase()}`,workspaceOptions:G,selectedWorkspaceKey:A,details:[{label:"Mode",value:U.toUpperCase()},{label:"Provider",value:C.displayName}],showArgsInput:!0,showModelInput:U==="acp",initialArgs:"",initialModel:"",providerType:C.type},async()=>{const D=G.find(B=>B.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(D),_(U,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(Qr,{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(ba,{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?Dr(!!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:oa()}),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:bu()}),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(G=>G.providerSessionId===x.launchConfirmResumeId);if(!C)return null;const U=Yi(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:U.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:U.providerSessionId}),t.jsx("div",{className:"mt-1",children:U.metaLine}),U.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:U.updatedLabel}),U.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:U.preview})]})})()]}),onConfirm:x.handleConfirmLaunch,onCancel:x.closeLaunchConfirm}),u&&t.jsx(qi,{section:p,onSectionChange:v})]})}function Qi(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 Cp(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:ds(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,m,p,u;const a=Xs(n)?"cli":vs(n)?"acp":"ide",i=ds(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(Xs(n)?n.cliName||n.type:vs(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:vs(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((u=(p=(m=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:m.at)==null?void 0:p.call(m,-1))==null?void 0:u.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function Ip(e,s){const r=new Map;for(const n of s){const a=qt(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,v)=>v.timestamp-f.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=Ln(n),m=a.filter(f=>f.unread||f.requiresAction).length,p=Qi(n),u=[n.platform||"machine",p].filter(Boolean);return{id:n.id,label:Ct(n,{fallbackId:n.id}),subtitle:u.join(" · "),unread:m,total:a.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?iu(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 br(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 Ap({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:m,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:v,onRequestedMobileSectionConsumed:S,setSelectedTabKey:T,setScreen:d,setSelectedMachineId:b,setSection:N,setMachineBackTarget:h,resetMachineAction:w,markNotificationTargetRead:_}){const y=o.useRef(null),j=o.useCallback(k=>{if(!(k!=null&&k.sessionId))return;const g=_r(k,c),x=Math.max(Date.now(),os(k),g.lastUpdated||0);br("mark_read:start",{tabKey:k.tabKey,sessionId:k.sessionId,displayPrimary:lt(k),inboxBucket:g.inboxBucket,unread:g.unread,lastSeenAt:g.lastSeenAt,lastUpdated:g.lastUpdated,activityAt:os(k),readAt:x}),_({sessionId:k.sessionId,tabKey:k.tabKey}),l(qt(k)||k.routeId,"mark_session_seen",{sessionId:k.sessionId,seenAt:x}).then($=>{br("mark_read:result",{tabKey:k.tabKey,sessionId:k.sessionId,result:$})}).catch($=>{br("mark_read:error",{tabKey:k.tabKey,sessionId:k.sessionId,error:$ instanceof Error?$.message:String($)})})},[c,l]);return o.useEffect(()=>{var g;if(!n){d("inbox"),T(((g=e[0])==null?void 0:g.tabKey)||null),y.current=null;return}if(i!=="chat"){y.current=null;return}const k=`${n.tabKey}:${n.sessionId||""}`;y.current!==k&&(y.current=k,j(n))},[e,j,i,n,d,T]),o.useEffect(()=>{if(!m)return;const k=e.find(g=>g.tabKey===m);k&&(T(k.tabKey),d("chat"),p==null||p())},[e,p,m,d,T]),o.useEffect(()=>{if(!u)return;const k=s.find(g=>g.id===u);k&&(b(k.id),w(),N("machines"),h("inbox"),d("machine"),f==null||f())},[s,f,u,w,h,d,N,b]),o.useEffect(()=>{v&&(N(v),d("inbox"),S==null||S())},[S,v,d,N]),o.useEffect(()=>{const k=r.filter(g=>g.inboxBucket==="task_complete"||g.unread);k.length!==0&&br("inbox_state",{screen:i,selectedTabKey:a,items:k.map(g=>{const x=_r(g.conversation,c);return{liveState:x,tabKey:g.conversation.tabKey,sessionId:g.conversation.sessionId,displayPrimary:lt(g.conversation),serverBucket:x.inboxBucket,computedBucket:g.inboxBucket,serverUnread:x.unread,computedUnread:g.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,activityAt:os(g.conversation)}})})},[r,c,i,a]),{markConversationRead:j}}function Tp(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function bo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Mp(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Lp({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[m,p]=o.useState(null),u=o.useCallback(()=>{i("idle"),l(""),p(null)},[]),f=o.useCallback(async(h,w,_)=>{var y;try{i("loading"),l(`Launching ${w}…`);const j={ideType:w,enableCdp:!0};(y=_==null?void 0:_.workspacePath)!=null&&y.trim()&&(j.workspace=_.workspacePath.trim()),await e(h,"launch_ide",j),i("done"),l(`${w} launch requested`)}catch(j){i("error"),l(j instanceof Error?j.message:"Launch IDE failed"),console.error("Launch IDE failed",j)}},[e]),v=o.useCallback(async(h,w,_)=>{if(w.trim())try{i("loading"),l(_!=null&&_.createIfMissing?"Creating folder…":"Saving workspace…");const y=await e(h,"workspace_add",{path:w.trim(),createIfMissing:(_==null?void 0:_.createIfMissing)===!0});if(y!=null&&y.success){i("done"),l(_!=null&&_.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((y==null?void 0:y.error)||"Could not save workspace")}catch(y){i("error"),l(y instanceof Error?y.message:"Could not save workspace")}},[e]),S=o.useCallback(async h=>{var w,_,y,j,k,g;try{i("loading"),l("Starting daemon upgrade…");const x=await e(h,"daemon_upgrade",{});if((w=x==null?void 0:x.result)!=null&&w.alreadyLatest){i("done"),l(`Already on v${((_=x==null?void 0:x.result)==null?void 0:_.version)||"latest"}.`);return}if((y=x==null?void 0:x.result)!=null&&y.upgraded||(j=x==null?void 0:x.result)!=null&&j.success){i("done"),l(`Upgrade to v${((k=x==null?void 0:x.result)==null?void 0:k.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((g=x==null?void 0:x.result)==null?void 0:g.error)||"Upgrade failed")}catch(x){i("error"),l(x instanceof Error?x.message:"Upgrade failed")}},[e]),T=o.useCallback(async(h,w,_,y)=>{var g,x,$;const j=Date.now(),k={machineId:h,kind:w,providerType:_,workspaceId:(y==null?void 0:y.workspaceId)||null,workspacePath:(y==null?void 0:y.workspacePath)||null,resumeSessionId:(y==null?void 0:y.resumeSessionId)||null,startedAt:j};try{i("loading"),l(`Launching ${_}…`),p(k);const I={cliType:_};(g=y==null?void 0:y.workspacePath)!=null&&g.trim()?I.dir=y.workspacePath.trim():y!=null&&y.workspaceId&&(I.workspaceId=y.workspaceId),y!=null&&y.resumeSessionId&&(I.resumeSessionId=y.resumeSessionId),(x=y==null?void 0:y.args)!=null&&x.trim()&&(I.cliArgs=y.args.trim().split(/\s+/).filter(Boolean)),($=y==null?void 0:y.model)!=null&&$.trim()&&(I.initialModel=y.model.trim());const M=await e(h,"launch_cli",I),L=(M==null?void 0:M.result)||M,O=(L==null?void 0:L.sessionId)||(L==null?void 0:L.id);if(M!=null&&M.success&&O){p(null),i("done"),l(`${_} launched`),s(`/dashboard?activeTab=${encodeURIComponent(O)}`);return}if(M!=null&&M.success){i("loading"),l(`${_} launch requested — waiting for session…`);return}p(null),i("error"),l((M==null?void 0:M.error)||(L==null?void 0:L.error)||`Could not launch ${w.toUpperCase()} workspace`)}catch(I){if(Mp(I)){i("loading"),l(`${_} launch requested — waiting for session…`);return}p(null),i("error"),l(I instanceof Error?I.message:`Could not launch ${w.toUpperCase()} workspace`)}},[s,e]),d=o.useCallback(async(h,w)=>{try{const _=await e(h,"list_saved_sessions",{providerType:w,kind:"cli",limit:30}),y=(_==null?void 0:_.result)??_;return Array.isArray(y==null?void 0:y.sessions)?y.sessions:[]}catch(_){return console.error("Failed to list saved sessions on mobile:",_),[]}},[e]),b=o.useCallback(async(h,w)=>Xr(e,h,w),[e]);o.useEffect(()=>{var y;if(!m)return;const h=bo(m.workspacePath),w=r.find(j=>{var M,L,O,R;if(!j||j.type==="adhdev-daemon"||Tp(j.daemonId||j.id)!==m.machineId||(j.transport==="acp"?"acp":j.transport==="pty"?"cli":null)!==m.kind||String(j.agentType||j.type||"")!==m.providerType)return!1;const $=String(j.providerSessionId||"");if(m.resumeSessionId&&$)return $===m.resumeSessionId;if(h){const C=bo(j.workspace||j.runtimeWorkspaceLabel);return C?C===h:!1}return Number(j.lastUpdated||j._lastUpdate||j.timestamp||((R=(O=(L=(M=j.activeChat)==null?void 0:M.messages)==null?void 0:L.at)==null?void 0:O.call(L,-1))==null?void 0:R.timestamp)||0)>=m.startedAt-5e3});if(!w)return;const _=typeof w.sessionId=="string"&&w.sessionId?w.sessionId:typeof w.instanceId=="string"&&w.instanceId?w.instanceId:(y=n.find(j=>j.routeId===w.id))==null?void 0:y.sessionId;_&&(p(null),i("done"),l(`${m.providerType} launched`),s(`/dashboard?activeTab=${encodeURIComponent(_)}`))},[n,r,s,m]),o.useEffect(()=>{if(!m)return;const h=window.setTimeout(()=>{p(w=>!w||w.startedAt!==m.startedAt?w:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(h)},[m]);const N=o.useCallback(async(h,w)=>{if(w.kind==="ide"&&w.providerType){await f(h,w.providerType,{workspacePath:w.workspace||null});return}(w.kind==="cli"||w.kind==="acp")&&w.providerType&&await T(h,w.kind,w.providerType,{workspacePath:w.workspace||null,resumeSessionId:w.providerSessionId||null})},[f,T]);return{machineAction:{state:a,message:c},resetMachineAction:u,handleLaunchDetectedIde:f,handleAddWorkspace:v,handleMachineUpgrade:S,handleLaunchWorkspaceProvider:T,handleListSavedSessions:d,handleBrowseDirectory:b,handleOpenRecent:N}}function _p({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:m,setMachineBackTarget:p}){const u=o.useCallback(N=>{i(N.tabKey),c("chat"),n(N)},[n,c,i]),f=o.useCallback(N=>{const h=e.find(w=>w.routeId===N.routeId&&w.streamSource==="native");h&&(i(h.tabKey),c("chat"),n(h))},[e,n,c,i]),v=o.useCallback(()=>{n(s),c("inbox")},[n,s,c]),S=o.useCallback((N,h="inbox")=>{l(N),a(),m("machines"),p(h),c("machine")},[a,p,c,m,l]),T=o.useCallback(N=>{const h=qt(N);h&&S(h,"chat")},[S]),d=o.useCallback(()=>{a(),c(r)},[r,a,c]),b=o.useCallback(N=>{m(N),c("inbox")},[c,m]);return{openConversation:u,openNativeConversation:f,backFromConversation:v,openMachine:S,openConversationMachine:T,backFromMachine:d,changeMachineSection:b}}function Rp(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function Pp(e){const s=e instanceof Error?e.message:String(e||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function gr(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Dp({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,userName:m,requestedActiveTabKey:p,onRequestedActiveTabConsumed:u,requestedMachineId:f,onRequestedMachineConsumed:v,requestedMobileSection:S,onRequestedMobileSectionConsumed:T,onOpenHistory:d,onOpenRemote:b,onStopCli:N,wsStatus:h,isConnected:w,onShowHiddenConversation:_,onShowAllHiddenConversations:y,onHideConversation:j,onOpenNewSession:k,notificationStateBySessionId:g,onMarkNotificationTargetRead:x}){const[$,I]=o.useState(()=>{var Q;return((Q=e[0])==null?void 0:Q.tabKey)||null}),[M,L]=o.useState(()=>e[0]?"chat":"inbox"),[O,R]=o.useState("chats"),[C,U]=o.useState(null),[G,A]=o.useState("inbox"),D=Ls(),B="0.8.69",W=o.useMemo(()=>e.find(Q=>Q.tabKey===$)||e[0]||null,[e,$]),X=o.useMemo(()=>W?r.find(Q=>Q.id===W.routeId):void 0,[r,W]),xe=o.useMemo(()=>!W||Ye(W)||!et(W)?null:Is(W),[W]),Re=o.useMemo(()=>r.filter(Q=>Q.type==="adhdev-daemon").sort(Zn),[r]),ie=o.useMemo(()=>Re.find(Q=>Q.id===C)||null,[Re,C]),Ie=o.useMemo(()=>zr(r),[r]),te=Gr({sendDaemonCommand:a,activeConv:W||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),ce=Lp({sendDaemonCommand:a,navigate:D,ides:r,conversations:e}),oe=o.useMemo(()=>e.map(Q=>{const Ne=M==="chat"&&(W==null?void 0:W.tabKey)===Q.tabKey,Ue=Jn(Q,Ie,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Ne,notificationStateBySessionId:g}),Ee=os(Q),Ve=hi(Q);return{conversation:Q,timestamp:Ee,preview:Ve,unread:Ue.unread,requiresAction:Ue.requiresAction,isWorking:Ue.isWorking,inboxBucket:Ue.inboxBucket}}),[e,Ie,g,M,W]),{markConversationRead:ye}=Ap({conversations:e,machineEntries:Re,items:oe,selectedConversation:W,selectedTabKey:$,screen:M,liveSessionInboxState:Ie,sendDaemonCommand:a,requestedActiveTabKey:p,onRequestedActiveTabConsumed:u,requestedMachineId:f,onRequestedMachineConsumed:v,requestedMobileSection:S,onRequestedMobileSectionConsumed:T,setSelectedTabKey:I,setScreen:L,setSelectedMachineId:U,setSection:R,setMachineBackTarget:A,resetMachineAction:ce.resetMachineAction,markNotificationTargetRead:x}),ae=_p({conversations:e,selectedConversation:W,machineBackTarget:G,markConversationRead:ye,resetMachineAction:ce.resetMachineAction,setSelectedTabKey:I,setScreen:L,setSelectedMachineId:U,setSection:R,setMachineBackTarget:A}),F=o.useMemo(()=>gr(oe.filter(Q=>Q.requiresAction)),[oe]),be=o.useMemo(()=>gr(oe.filter(Q=>Q.unread&&!Q.requiresAction)),[oe]),se=o.useMemo(()=>gr(oe.filter(Q=>!Q.unread&&!Q.requiresAction&&Q.isWorking)),[oe]),pe=o.useMemo(()=>gr(oe.filter(Q=>!Q.unread&&!Q.requiresAction&&!Q.isWorking)),[oe]),J=o.useMemo(()=>ie?oe.filter(Q=>qt(Q.conversation)===ie.id):[],[oe,ie]),le=o.useMemo(()=>Cp(ie,r),[r,ie]),ne=(ie==null?void 0:ie.version)||null,ge=!!ie&&!!ne&&!0&&ne!==B,ue=o.useMemo(()=>(ie==null?void 0:ie.availableProviders)||[],[ie]),E=o.useMemo(()=>ue.filter(Q=>Q.category==="cli"&&Q.installed!==!1).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[ue]),ve=o.useMemo(()=>ue.filter(Q=>Q.category==="acp"&&Q.installed!==!1).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[ue]),he=o.useMemo(()=>Ip(Re,oe),[oe,Re]),Se=o.useCallback(async Q=>{ie&&await ce.handleOpenRecent(ie.id,Q)},[ce,ie]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:M==="chat"&&W?t.jsx(fp,{selectedConversation:W,isAcp:Ye(W),isStandalone:l,selectedIdeEntry:X,actionLogs:n,userName:m,isSendingChat:te.isSendingChat,isFocusingAgent:te.isFocusingAgent,handleModalButton:te.handleModalButton,handleRelaunch:te.handleRelaunch,onBack:ae.backFromConversation,onOpenNativeConversation:ae.openNativeConversation,onOpenMachine:ae.openConversationMachine,onHideConversation:j,onOpenHistory:d,onOpenRemote:b,onStopCli:N,cliViewMode:xe,onSetCliViewMode:async Q=>{if(W&&xe!==Q)try{await a(qt(W)||W.routeId,"set_cli_view_mode",{targetSessionId:W.sessionId,cliType:Dt(W),mode:Q})}catch(Ne){Pp(Ne)?console.warn("Skipped CLI view mode switch:",Ne instanceof Error?Ne.message:String(Ne)):console.error("Failed to switch CLI view mode:",Ne)}},handleSendChat:te.handleSendChat,handleFocusAgent:te.handleFocusAgent}):M==="machine"&&ie?t.jsx(Np,{selectedMachineEntry:ie,selectedMachineConversations:J,selectedMachineRecentLaunches:le,cliProviders:E,acpProviders:ve,selectedMachineNeedsUpgrade:ge,appVersion:B,machineAction:ce.machineAction,isStandalone:l,section:O,showBottomNav:G==="inbox",onBack:ae.backFromMachine,onSectionChange:ae.changeMachineSection,onOpenConversation:ae.openConversation,onOpenRecent:Se,onOpenMachineDetails:()=>D(`/machines/${ie.id}`),onMachineUpgrade:()=>ce.handleMachineUpgrade(ie.id),onLaunchDetectedIde:(Q,Ne)=>ce.handleLaunchDetectedIde(ie.id,Q,Ne),onAddWorkspace:(Q,Ne)=>ce.handleAddWorkspace(ie.id,Q,Ne),onBrowseDirectory:Q=>ce.handleBrowseDirectory(ie.id,Q),onLaunchWorkspaceProvider:(Q,Ne,Ue)=>ce.handleLaunchWorkspaceProvider(ie.id,Q,Ne,Ue),onListSavedSessions:Q=>ce.handleListSavedSessions(ie.id,Q)}):t.jsx(xp,{section:O,attentionItems:F,unreadItems:be,workingItems:se,completedItems:pe,hiddenConversations:s,machineCards:he,getAvatarText:Rp,onOpenConversation:ae.openConversation,onShowConversation:_,onShowAllHidden:y,onOpenNewSession:k,onOpenMachine:ae.openMachine,onOpenSettings:()=>D("/settings"),onSectionChange:R,wsStatus:h,isConnected:w,isStandalone:l})})}function bn(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function Ep({conversations:e,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,m]=o.useState(!1),[p,u]=o.useState(null),f=o.useCallback(()=>{c.current=0,m(!1),u(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",f),window.addEventListener("drop",f),()=>{window.removeEventListener("dragend",f),window.removeEventListener("drop",f)}),[f]);const v=o.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,m(!0))},[]),S=o.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!bn(s,r)){u("merge");return}const N=b.currentTarget.getBoundingClientRect(),h=b.clientX-N.left,w=N.width/3;h<w?u("split-left"):h>w*2?u("split-right"):u("merge")},[s,r]),T=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,m(!1),u(null))},[]),d=o.useCallback(b=>{c.current=0,m(!1);const N=b.dataTransfer.getData("text/tab-key"),h=N?e.some(_=>_.tabKey===N):!1,w=p;if(u(null),i(),!!N){if(b.preventDefault(),w==="split-left"&&bn(s,r)){r==null||r(N,"split-left");return}if(w==="split-right"&&bn(s,r)){r==null||r(N,"split-right");return}if(h){a(N);return}n==null||n(N)}},[e,p,s,r,n,a,i]);return{dragOver:l,dropAction:p,resetDragState:f,handleDragEnter:v,handleDragOver:S,handleDragLeave:T,handleDrop:d}}function $p(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 Bp({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(s??null),[l,m]=o.useState(r??[]),[p,u]=o.useState(null),f=o.useRef(null),v=o.useRef(null),S=o.useRef(n),T=o.useRef(a);o.useEffect(()=>{S.current=n},[n]),o.useEffect(()=>{T.current=a},[a]),o.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),o.useEffect(()=>{m(k=>{const g=$p(k,e);return g.length===k.length&&g.every((x,$)=>x===k[$])?k:g})},[e]);const d=o.useMemo(()=>{const k=p??l;if(k.length===0)return e;const g=new Map(k.map((x,$)=>[x,$]));return[...e].sort((x,$)=>{const I=g.get(x.tabKey)??999,M=g.get($.tabKey)??999;return I-M})},[e,p,l]);o.useEffect(()=>{var g,x;if(d.length===0){i!==null&&(c(null),(g=S.current)==null||g.call(S,null));return}if(i&&d.some($=>$.tabKey===i))return;const k=d[0].tabKey;k!==i&&(c(k),(x=S.current)==null||x.call(S,k))},[d,i]);const b=o.useMemo(()=>d.find(k=>k.tabKey===i),[d,i]),N=o.useCallback(k=>{var g;c(k),(g=S.current)==null||g.call(S,k)},[]),h=o.useCallback((k,g,x)=>{m($=>{var O;const I=$.filter(R=>R!==k),M=I.indexOf(g);if(M<0)return $;const L=x==="left"?M:M+1;return I.splice(L,0,k),(O=T.current)==null||O.call(T,I),I}),u(null)},[]),w=o.useCallback((k,g,x)=>{const I=(l.length>0?l:e.map(O=>O.tabKey)).filter(O=>O!==k),M=I.indexOf(g);if(M<0)return;const L=x==="left"?M:M+1;I.splice(L,0,k),f.current=I,u(I)},[l,e]),_=o.useCallback(()=>{var g;const k=f.current;k&&(m(k),(g=T.current)==null||g.call(T,k))},[]),y=o.useCallback(()=>{f.current=null,u(null)},[]),j=o.useCallback(k=>{m(g=>{var $;const x=g.filter(I=>I!==k);return x.push(k),($=T.current)==null||$.call(T,x),x})},[]);return{activeTabId:i,activeConv:b,sortedConversations:d,previewOrderRef:f,draggingTabRef:v,selectTab:N,handleTabReorder:h,updatePreviewOrder:w,commitPreviewOrder:_,clearPreviewOrder:y,moveTabToEnd:j,setDraggingTabKey:k=>{v.current=k}}}function Kp({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 ga({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(Gi,{}),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 Ji="adhdev-tab-shortcuts";function Zi(){try{return JSON.parse(localStorage.getItem(Ji)||"{}")}catch{return{}}}function ec({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>Zi()),[l,m]=o.useState(null),p=o.useCallback(f=>{const v=[];return f.metaKey&&v.push(a?"⌘":"Meta"),f.ctrlKey&&v.push("Ctrl"),f.altKey&&v.push(a?"⌥":"Alt"),f.shiftKey&&v.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(v.push(f.key.length===1?f.key.toUpperCase():f.key),v.join("+"))},[a]),u=o.useCallback(f=>{c(f);try{localStorage.setItem(Ji,JSON.stringify(f))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const f=v=>{if(v.preventDefault(),v.stopPropagation(),v.key==="Escape"){m(null);return}const S=p(v);if(!S)return;const T={...i};for(const[d,b]of Object.entries(T))b===S&&delete T[d];T[l]=S,u(T),m(null)};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[e,l,i,u,p]),o.useEffect(()=>{if(!e)return;const f=v=>{if(!(!v.ctrlKey&&!v.metaKey&&!v.altKey)){for(const[S,T]of Object.entries(i))if(s.includes(S)&&p(v)===T){v.preventDefault(),r(),n(S);return}}};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,i,s,r,n,p]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:m,saveShortcuts:u}}const Wp=o.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:m,onSelectTab:p,onConversationActivated:u,onPreviewReorder:f,onReorderTab:v,onCommitPreviewOrder:S,onClearPreviewOrder:T,onDragStateReset:d,onDragTabKeyChange:b,onReceiveTab:N,onOpenContextMenu:h,longPressTimer:w,isGroupActive:_}){const y=Rs(s),j=y.isGenerating?"agent-tab-generating":y.isWaiting?"agent-tab-waiting":"",k=y.isReconnecting,g=o.useCallback(U=>{l.current=s.tabKey,b(s.tabKey),U.dataTransfer.setData("text/tab-key",s.tabKey),U.dataTransfer.effectAllowed="move"},[s.tabKey,l,b]),x=o.useCallback(()=>{l.current=null,b(null),S(),T(),d()},[l,b,S,T,d]),$=o.useCallback(U=>{const G=l.current;if(!(!G||G===s.tabKey)&&U.dataTransfer.types.includes("text/tab-key")){U.preventDefault(),U.stopPropagation();const A=U.currentTarget.getBoundingClientRect(),D=U.clientX<A.left+A.width/2?"left":"right";f(G,s.tabKey,D)}},[s.tabKey,l,f]),I=o.useCallback(U=>{U.preventDefault(),U.stopPropagation();const G=U.dataTransfer.getData("text/tab-key");if(G&&G!==s.tabKey){const A=U.currentTarget.getBoundingClientRect(),D=U.clientX<A.left+A.width/2?"left":"right";c.includes(G)?v(G,s.tabKey,D):N&&N(G)}T()},[s.tabKey,c,v,N,T]),M=o.useCallback(U=>{U.stopPropagation(),m(),p(s.tabKey),u(s)},[s,u,m,p]),L=o.useCallback(U=>{U.preventDefault(),h(U.clientX,U.clientY,s.tabKey)},[s.tabKey,h]),O=o.useCallback(U=>{const G=U.touches[0];w.current=setTimeout(()=>{h(G.clientX,G.clientY,s.tabKey)},600)},[s.tabKey,w,h]),R=o.useCallback(()=>{w.current&&clearTimeout(w.current)},[w]),C=["adhdev-dockview-tab",j,r&&"is-active",_&&"is-group-active",k&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:C,draggable:!0,onDragStart:g,onDragEnd:x,onDragOver:$,onDrop:I,onClick:M,onContextMenu:L,onTouchStart:O,onTouchEnd:R,onTouchMove:R,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:y.isGenerating?t.jsx("div",{className:"tab-spinner"}):y.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):k?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):y.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:k?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ts(s)}):y.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[ts(s),t.jsx("span",{className:"connecting-dots"})]}):ts(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 Op({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:m,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:f,onDragStateReset:v,onDragTabKeyChange:S,onReceiveTab:T,onHideTab:d,isGroupActive:b,allowTabShortcuts:N=!0}){const[h,w]=o.useState(null),_=o.useRef(null),y=o.useRef(null),j=o.useMemo(()=>e.map(L=>L.tabKey),[e]);Zs("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(h==null?void 0:h.tabKey)||null});const{isMac:k,tabShortcuts:g,shortcutListening:x,setShortcutListening:$,saveShortcuts:I}=ec({enabled:N,sortedTabKeys:e.map(L=>L.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!h)return;const L=O=>{const R=document.querySelector("[data-pane-context-menu]");R&&R.contains(O.target)||w(null)};return window.addEventListener("mousedown",L,!0),()=>window.removeEventListener("mousedown",L,!0)},[h]),o.useEffect(()=>{const L=y.current;if(!L)return;const O=R=>{Math.abs(R.deltaY)<=Math.abs(R.deltaX)||(R.preventDefault(),L.scrollLeft+=R.deltaY)};return L.addEventListener("wheel",O,{passive:!1}),()=>L.removeEventListener("wheel",O)},[]);const M=o.useCallback((L,O,R)=>{w({x:L,y:O,tabKey:R})},[]);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:y,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(L=>t.jsx(Wp,{conv:L,isActive:s===L.tabKey,isDraggedTab:a.current===L.tabKey,isTaskCompleteUnread:n.has(L.tabKey),shortcut:N?g[L.tabKey]:void 0,conversationKeys:j,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:m,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:f,onDragStateReset:v,onDragTabKeyChange:S,onReceiveTab:T,onOpenContextMenu:M,longPressTimer:_,isGroupActive:b},L.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:[N&&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:L=>{L.stopPropagation(),$(h.tabKey),w(null)},children:["⌨ ",g[h.tabKey]?`Change shortcut (${g[h.tabKey]})`:"Set shortcut"]}),g[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 L={...g};delete L[h.tabKey],I(L),w(null)},children:"✕ Remove shortcut"})]}),d&&t.jsxs(t.Fragment,{children:[N&&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),w(null)},children:"🚫 Hide from Dashboard"})]})]}),N&&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:()=>$(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:L=>L.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. ",k?"⌘+1":"Ctrl+1",", ",k?"⌥+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 Hp({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:m,userName:p,groupIndex:u,onFocus:f,isSplitMode:v,numGroups:S,onMoveTab:T,onReceiveTab:d,style:b,onActiveTabChange:N,initialActiveTabId:h,initialTabOrder:w,onTabOrderChange:_,onHideTab:y,isFocused:j,allowTabShortcuts:k=!0}){const{sendCommand:g}=At(),x=o.useRef(null),{activeTabId:$,activeConv:I,sortedConversations:M,draggingTabRef:L,selectTab:O,handleTabReorder:R,updatePreviewOrder:C,commitPreviewOrder:U,clearPreviewOrder:G,moveTabToEnd:A,setDraggingTabKey:D}=Bp({conversations:e,initialActiveTabId:h,initialTabOrder:w,onActiveTabChange:N,onTabOrderChange:_}),B=Gr({sendDaemonCommand:a,activeConv:I,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),{dragOver:W,dropAction:X,resetDragState:xe,handleDragEnter:Re,handleDragOver:ie,handleDragLeave:Ie,handleDrop:te}=Ep({conversations:e,numGroups:S,onMoveTab:T,onReceiveTab:d,onOwnTabDrop:A,onClearPreviewOrder:G}),ce=I&&!Ye(I)&&Is(I)==="terminal",oe=o.useMemo(()=>I?s.find(se=>se.id===I.routeId):void 0,[s,I]),ye=o.useMemo(()=>I?n.filter(se=>se.routeId===I.tabKey):[],[n,I]),ae=o.useMemo(()=>zr(s),[s]),F=o.useMemo(()=>new Set(M.filter(se=>Ol(se,ae,{isOpenConversation:se.tabKey===$})).map(se=>se.tabKey)),[$,ae,M]);Zs("PaneGroup",{groupIndex:u,conversationCount:e.length,activeTabId:$,dragOver:W});const be=o.useCallback(se=>{se.streamSource==="agent-stream"&&se.agentType&&g(se.routeId,"focus_session",{agentType:se.agentType,...se.sessionId&&{targetSessionId:se.sessionId}}).catch(()=>{})},[g]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:f,style:{...b,outline:W?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(Op,{conversations:M,activeTabId:$,groupIndex:u,numGroups:S,unreadTabKeys:F,draggingTabRef:L,onFocus:f,onSelectTab:O,onConversationActivated:be,onPreviewReorder:C,onReorderTab:R,onCommitPreviewOrder:U,onClearPreviewOrder:G,onDragStateReset:xe,onDragTabKeyChange:D,onMoveTab:T,onReceiveTab:d,onHideTab:y,isGroupActive:j??!1,allowTabShortcuts:k}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:Re,onDragOver:ie,onDragLeave:Ie,onDrop:te,children:[W&&t.jsx(Kp,{dropAction:X,canSplit:!!(S<4&&T)}),I?t.jsx(xa,{activeConv:I,clearToken:r[I.tabKey]||0,isCliTerminal:!!ce,ideEntry:oe,terminalRef:x,handleModalButton:B.handleModalButton,handleRelaunch:B.handleRelaunch,handleSendChat:B.handleSendChat,isSendingChat:B.isSendingChat,handleFocusAgent:B.handleFocusAgent,isFocusingAgent:B.isFocusingAgent,actionLogs:ye,userName:p,isInputActive:!v||!!j}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(ga,{conversationsCount:e.length,isSplitMode:v,isStandalone:l,hasRegisteredMachines:m})})]})]})}function Up({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:m,setLocalUserMessages:p,setActionLogs:u,isStandalone:f,hasRegisteredMachines:v,userName:S,focusedGroup:T,setFocusedGroup:d,moveTabToGroup:b,splitTabRelative:N,closeGroup:h,handleResizeStart:w,groupActiveTabIds:_,setGroupActiveTabIds:y,groupTabOrders:j,setGroupTabOrders:k,toggleHiddenTab:g,allowTabShortcuts:x=!0}){return t.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:a.map(($,I)=>{const M=s&&n.length===r?`${n[I]}%`:void 0;return t.jsxs(nt.Fragment,{children:[s&&I>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:L=>w(I-1,L),onDoubleClick:()=>h(I),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(Hp,{style:s?{flexBasis:M??`${100/r}%`,flexGrow:M?0:1,flexShrink:M?0:1}:void 0,conversations:$,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:m,setLocalUserMessages:p,setActionLogs:u,isStandalone:f,hasRegisteredMachines:v,userName:S,groupIndex:I,isFocused:s&&T===I,onFocus:()=>d(I),isSplitMode:s,numGroups:r,onMoveTab:(L,O)=>{O==="left"&&I>0?b(L,I-1):O==="right"&&I<r-1?b(L,I+1):O==="split-left"&&r<4?N(L,I,"left"):O==="split-right"&&r<4&&N(L,I,"right")},onReceiveTab:L=>b(L,I),onActiveTabChange:L=>y(O=>(O[I]??null)===(L??null)?O:{...O,[I]:L}),initialActiveTabId:_[I],initialTabOrder:j[I],onTabOrderChange:L=>k(O=>{const R=O[I]||[];return R.length===L.length&&R.every((C,U)=>C===L[U])?O:{...O,[I]:L}}),onHideTab:g,allowTabShortcuts:x})]},I)})})}function tc({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?pt.onScreenshot("ide-page",(u,f)=>{if(u!==e)return;const v=new FileReader;v.onload=()=>i(v.result),v.readAsDataURL(f)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var u;return e?((u=pt.onStatus)==null?void 0:u.call(pt,(f,v)=>{f===e&&v!=null&&v.screenshotUsage&&l(v.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,s]),o.useEffect(()=>{const p=e?pt.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 m=o.useCallback(async(p,u)=>{const f=e?pt.get(e):null;return!f||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):f.sendInput(p,u,s)},[e,r,s]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:m}}const sc="adhdev-dashboard-action-shortcuts",Fp=1200,zp={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Vp(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function rt(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 rc(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:rt("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:rt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:rt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:rt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:rt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:rt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:rt("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:rt("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:rt("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:rt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:rt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:rt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:rt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:rt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:rt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:rt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:rt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:rt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:rt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:rt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:rt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:rt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:rt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:rt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:rt("toggleCliView",e)}]}function Hn(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function Kr(e){const s=Object.fromEntries(rc(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(sc)||"{}"),n={...s,...r};for(const[a,i]of Object.entries(zp))n[a]===i&&(n[a]=s[a]);return n}catch{return s}}function nc(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Gp({enabled:e=!0,onTrigger:s}){const r=Vp(),[n,a]=o.useState(()=>Kr(r)),[i,c]=o.useState(null),[l,m]=o.useState([]),p=o.useRef({parts:[],timer:null}),u=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(nc(d.key)),b.join("+"))},[r]),f=o.useCallback(d=>{a(d);try{localStorage.setItem(sc,JSON.stringify(d))}catch{}},[]);o.useEffect(()=>{const d=Kr(r),b=Object.entries(n),N=Object.entries(d);b.length===N.length&&b.every(([h,w])=>d[h]===w)||f(d)},[n,r,f]);const v=o.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),S=o.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},Fp))},[]);o.useEffect(()=>{if(!i)return;const d=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){c(null),m([]);return}const N=u(b);if(!N)return;const w=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(N);if(l.length===0&&w){m([N]);return}const y=[...l,N].slice(0,2).join(" "),j={...n};for(const[k,g]of Object.entries(j))g===y&&delete j[k];j[i]=y,f(j),c(null),m([])};return window.addEventListener("keydown",d,!0),()=>window.removeEventListener("keydown",d,!0)},[n,u,f,i,l]),o.useEffect(()=>{if(!e||i)return;const d=b=>{if(b.defaultPrevented)return;const N=u(b);if(!N)return;const h=b.metaKey||b.ctrlKey||b.altKey;if(Hn(b.target)&&!h)return;const w=p.current.parts,_=h?[N]:[...w.slice(-1),N].slice(-2),y=_.join(" "),j=_[_.length-1],k=Object.entries(n).filter(([,M])=>!!M),g=k.find(([,M])=>M===y);if(g){b.preventDefault(),v(),s(g[0]);return}if(k.some(([,M])=>M.startsWith(`${y} `))){b.preventDefault(),p.current.parts=_,S();return}const $=k.find(([,M])=>M===j);if($){b.preventDefault(),v(),s($[0]);return}if(k.some(([,M])=>M.startsWith(`${j} `))){b.preventDefault(),p.current.parts=[j],S();return}v()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n,S,e,u,s,v,i]),o.useEffect(()=>()=>v(),[v]);const T=o.useMemo(()=>rc(r),[r]);return{isMac:r,actionDefinitions:T,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:m,saveShortcuts:f}}function qp({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"}),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 Yp(e){return e.some(s=>s.type!=="adhdev-daemon")||e.some(s=>s.type==="adhdev-daemon"&&!!s.machine)}function go({hasStoredLayout:e,initialDataLoaded:s,visibleConversationCount:r,ides:n}){return!e||r>0?!1:s?!Yp(n):!0}const ac=o.createContext(null);function Jr(){const e=o.useContext(ac);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Ar(e){return lt(e)||e.tabKey}function Xp(e){return`remote:${e}`}function zt(e){return e.startsWith("remote:")}function yo(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function gn(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,m;try{s.focus(),(m=(l=e==null?void 0:e.body)==null?void 0:l.focus)==null||m.call(l)}catch{}})}catch{}}function yr(e,s){e.classList.remove(An.className,Tn.className),e.classList.add(s==="light"?An.className:Tn.className)}function vo(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 Qp(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 Jp(e,s,r){var l;const n=[s];let a;for(const m of n){let p;for(const u of m){const f=e.addPanel({id:u.tabKey,component:"conversation",title:Ar(u),params:{kind:"conversation",tabKey:u.tabKey},...p?{position:{referencePanel:p,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});p||(p=f.id)}a=p??a}const i=r??((l=s[0])==null?void 0:l.tabKey)??null;if(!i)return;const c=e.getPanel(i);c&&c.group.model.openPanel(c)}function wo(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!==Ar(n)&&a.api.setTitle(Ar(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:Ar(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 jo(e,s,r){var m,p;const n=r?Xp(r):null;for(const u of[...e.panels])zt(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=Bt(s,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=gi(a);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((m=e.activePanel)==null?void 0:m.id)??((p=e.panels.find(u=>!zt(u.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 Zp({params:e,api:s}){var f;const r=Jr(),n=o.useRef(null),[a,i]=o.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=Gr({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(s.isActive);const v=[s.onDidActiveChange(S=>i(S.isActive)),s.onDidActiveGroupChange(S=>{if(!s.isActive&&!S.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const S of v)S.dispose()}},[s]);const m=o.useMemo(()=>c?r.ides.find(v=>v.id===c.routeId):void 0,[r.ides,c]),p=o.useMemo(()=>c?r.actionLogs.filter(v=>v.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(ga,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,suppressGuide:r.hasDetachedConversationPanels})});const u=!Ye(c)&&Is(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(xa,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:u,ideEntry:m,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 ef({params:e}){var m;const s=Jr(),r=o.useMemo(()=>Bt([...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)||((m=r==null?void 0:r.routeId)==null?void 0:m.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:l}=tc({doId:a,targetSessionId:r?sa(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(Yo,{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 tf(){const e=Jr();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(ga,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,suppressGuide:e.hasDetachedConversationPanels})})}function sf(e){var S,T;Qp(e);const s=Jr(),r=o.useCallback(d=>{"button"in d&&d.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const d=Bt([...s.conversationsByTabKey.values()],e.params.routeId),b=((S=e.api.group.activePanel)==null?void 0:S.id)===e.api.id,N=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${b?" is-active":""}${N?" 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=((T=e.api.group.activePanel)==null?void 0:T.id)===e.api.id,i=e.api.isGroupActive,c=Jn(n,s.liveSessionInboxState,{isOpenConversation:a,notificationStateBySessionId:s.notificationStateBySessionId}),l=c.isReconnecting,m=c.isConnecting,p=c.isGenerating,u=c.isWaiting,f=c.unread,v=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"}):u?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:"○"}):m?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:ts(n)}):m?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ts(n)}):t.jsx("span",{children:ts(n)})})]}),v&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:v,children:v})]})}function rf({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:m,initialDataLoaded:p,userName:u,toggleHiddenTab:f,actionShortcuts:v,registerActionHandlers:S,onActiveTabChange:T,requestedActiveTabKey:d,requestedRemoteIdeId:b,onRequestedActiveTabConsumed:N,scrollToBottomRequest:h,notificationStateBySessionId:w}){var q,Be,Pe;const{theme:_}=ua(),{sendCommand:y}=At(),j=o.useRef(null),k=o.useRef(null),g=o.useRef(!1),x=o.useRef(!1),$=o.useRef(!1),I=o.useRef(null),M=o.useRef([]),[L,O]=o.useState(null),[R,C]=o.useState(!1),[U,G]=o.useState(!1),[A,D]=o.useState(0),B=o.useRef(null),W=o.useMemo(()=>Ui(typeof window<"u"?window.innerWidth:1280),[]),X=o.useRef(typeof window>"u"?{}:Km(W)),xe=o.useMemo(()=>new Map(e.map(K=>[K.tabKey,K])),[e]),Re=o.useMemo(()=>zr(r),[r]),ie=o.useMemo(()=>{const K=j.current;return K?K.groups.some(H=>{try{const z=H.model.location.type;return z!=="floating"&&z!=="popout"?!1:H.panels.some(V=>xe.has(V.id))}catch{return!1}}):!1},[xe,A,e]),Ie=o.useCallback(()=>{var K;(K=j.current)==null||K.focus()},[]),te=o.useCallback(K=>{const H=document,z=K.document;for(const Ce of H.querySelectorAll('link[rel="stylesheet"]')){const We=z.createElement("link");We.rel="stylesheet",We.href=Ce.href,Ce.crossOrigin&&(We.crossOrigin=Ce.crossOrigin),z.head.appendChild(We)}for(const Ce of H.querySelectorAll("style")){const We=z.createElement("style");We.textContent=Ce.textContent,z.head.appendChild(We)}const V=[];for(const Ce of H.styleSheets)try{for(const We of Ce.cssRules)We instanceof CSSStyleRule&&(We.selectorText===":root"||We.selectorText==="html")&&V.push(We.cssText)}catch{}if(V.length>0){const Ce=z.createElement("style");Ce.textContent=V.join(`
|
|
44
44
|
`),z.head.appendChild(Ce)}const ee=H.documentElement.getAttribute("data-theme");ee&&z.documentElement.setAttribute("data-theme",ee),z.documentElement.style.colorScheme=ee==="light"?"light":"dark",z.body.className=H.body.className;const je=H.documentElement.getAttribute("style");je&&z.documentElement.setAttribute("style",je);const Ae=z.getElementById("dv-popout-window");Ae instanceof HTMLElement&&(Ae.classList.add("adhdev-dockview"),yr(Ae,_))},[_]),ce=o.useCallback(()=>{var H;const K=j.current;if(K)for(const z of K.groups)try{const V=(H=z.element)==null?void 0:H.ownerDocument;if(!V||V===document)continue;const ee=V.getElementById("dv-popout-window");ee instanceof HTMLElement&&(ee.classList.add("adhdev-dockview"),yr(ee,_));const je=document.documentElement.getAttribute("data-theme");je&&V.documentElement.setAttribute("data-theme",je),V.documentElement.style.colorScheme=je==="light"?"light":"dark",V.body.className=document.body.className;const Ae=document.documentElement.getAttribute("style");Ae?V.documentElement.setAttribute("style",Ae):V.documentElement.removeAttribute("style")}catch{}},[_]),oe=o.useCallback(()=>{var H;const K=j.current;if(K)for(const z of K.groups)try{const V=(H=z.element)==null?void 0:H.ownerDocument;if(!V||V===document)continue;const ee=V.getElementById("dv-popout-window");if(!(ee instanceof HTMLElement))continue;ee.classList.add("adhdev-dockview"),yr(ee,_),ee.classList.toggle("is-showing-dockview-overlay",U),ee.classList.toggle("is-dragging-dockview",R)}catch{}},[R,U,_]),ye=o.useCallback(K=>{const H=j.current;if(!H)return;const z=H.getPanel(K);z&&H.addPopoutGroup(z,{popoutUrl:"/popout.html",onDidOpen:({window:V})=>{te(V),ge();const ee=xe.get(K);V.document.title=ee?`${lt(ee)} — ADHDev`:"ADHDev — Popout"}})},[xe,te]),ae=o.useCallback(K=>{const H=j.current,z=H==null?void 0:H.getPanel(K);if(!H||!z)return;const V=H.groups.filter(ee=>{var je;try{return((je=ee.element)==null?void 0:je.ownerDocument)===document}catch{return!0}});V.length>0?z.api.moveTo({group:V[0],position:"center"}):z.api.moveTo({position:"center"}),z.api.setActive()},[]),F=o.useCallback(K=>{var V;const H=j.current;if(!H)return!1;const z=H.getPanel(K);if(!z)return!1;try{return((V=z.group.element)==null?void 0:V.ownerDocument)!==document}catch{return!1}},[]),be=o.useCallback(K=>{F(K)&&ae(K),f(K)},[F,ae,f]),se=o.useCallback(K=>{const H=j.current,z=H==null?void 0:H.getPanel(K);!H||!z||H.addFloatingGroup(z,{width:600,height:500})},[]),pe=o.useCallback(K=>{var z;const H=(z=j.current)==null?void 0:z.getPanel(K);if(!H)return!1;try{return H.group.model.location.type==="floating"}catch{return!1}},[]),J=o.useCallback(()=>{var H,z;const K=(z=(H=j.current)==null?void 0:H.activePanel)==null?void 0:z.id;return!K||zt(K)?null:xe.has(K)?K:null},[xe]),le=o.useCallback(K=>{const H=j.current,z=H==null?void 0:H.getPanel(K);if(!H||!z)return;const V=H.groups.filter(ee=>{try{return ee.model.location.type==="grid"}catch{return!0}});V.length>0?z.api.moveTo({group:V[0],position:"center"}):z.api.moveTo({position:"center"}),z.api.setActive()},[]),ne=o.useCallback(()=>{var je;const K=j.current;if(!K)return;const z=K.groups.filter(Ae=>{var Ce;try{return((Ce=Ae.element)==null?void 0:Ce.ownerDocument)===document&&Ae.model.location.type==="grid"}catch{return!1}})[0]||null,V=[...K.panels];for(const Ae of V){const Ce=(je=Ae.group.element)==null?void 0:je.ownerDocument,We=Ae.group.model.location.type;Ce===document&&We==="grid"||(z&&z.id!==Ae.group.id?Ae.api.moveTo({group:z,position:"center"}):Ae.api.moveTo({position:"center"}))}const ee=K.activePanel;ee&&(ee.group.model.openPanel(ee),ee.api.setActive()),gn(document)},[]),ge=o.useCallback(()=>{var H,z;const K=j.current;if(K)for(const V of K.groups){const ee=(H=V.element)==null?void 0:H.ownerDocument;if(!ee||ee===document)continue;const je=ee.getElementById("dv-popout-window");if(!(je instanceof HTMLElement))continue;let Ae=null,Ce=ee.title||"ADHDev",We="Popout workspace";const Oe=V.activePanel;if(Oe)if(Ae=Oe.id,zt(Oe.id)){const Te=((z=Oe.params)==null?void 0:z.routeId)||Oe.id.slice(7),Ke=Bt([...xe.values()],Te);Ce=gi(Ke),We=Ke!=null&&Ke.machineName?`Remote view · ${Ke.machineName}`:"Remote view"}else{const Te=xe.get(Oe.id);Ce=Te?lt(Te):Oe.title||Oe.id,We=Te?ts(Te):"Dockview panel"}ee.title=`${Ce} — ADHDev`;let Ze=ee.getElementById("adhdev-popout-header");Ze instanceof HTMLElement||(Ze=ee.createElement("div"),Ze.id="adhdev-popout-header",ee.body.appendChild(Ze)),Ze.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(";")),Ze.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>
|
|
@@ -64,9 +64,9 @@ This will disconnect CDP and optionally kill the process.`))try{const D=await r(
|
|
|
64
64
|
✅ Auto-fix completed!`]),N.current&&clearInterval(N.current))}catch{}},3e3)},[e,s.type,r,a]),j=async()=>{if(m.length!==0){i("running"),S(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${m.join(", ")}`,u?`💬 Comment: ${u}`:"",""]),d("");try{const g=await r(e,"provider_auto_fix",{providerType:s.type,functions:m,agent:c,...u?{comment:u}:{}});g!=null&&g.success&&(g!=null&&g.started||g!=null&&g.running)?(S(x=>[...x,"✅ Agent started. Monitoring progress..."]),y()):(i("error"),d((g==null?void 0:g.error)||"Failed to start auto-fix"))}catch(g){i("error"),d((g==null?void 0:g.message)||"Connection failed")}}},k=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:s.type}),S(g=>[...g,`
|
|
65
65
|
⚠️ Auto-fix cancelled.`]),i("done"),N.current&&clearInterval(N.current)}catch{}};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:t.jsxs("div",{className:"w-full max-w-[560px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[85vh] overflow-hidden rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:g=>g.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:s.icon||"🔧"}),t.jsxs("div",{children:[t.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",s.displayName]}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),t.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),t.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[a==="config"&&t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),t.jsx("div",{className:"flex gap-2",children:Df.map(g=>t.jsxs("button",{onClick:()=>l(g.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===g.value?g.color+"66":"var(--border-subtle)",background:c===g.value?g.color+"0d":"transparent"},children:[t.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===g.value?g.color:"var(--text-primary)"},children:g.label}),t.jsx("div",{className:"text-[10px] text-text-muted",children:g.desc})]},g.value))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:w,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),t.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),t.jsx("button",{onClick:_,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Io.map(g=>t.jsxs("button",{onClick:()=>h(g),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:m.includes(g)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:m.includes(g)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:m.includes(g)?"#a78bfa":"var(--text-secondary)"},children:[m.includes(g)?"☑ ":"☐ ",g]},g))})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",t.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),t.jsx("textarea",{value:u,onChange:g=>f(g.target.value),placeholder:"e.g. Also search buttons inside Shadow DOM, preserve code block formatting in readChat...",rows:2,className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] resize-none placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]})]}),(a==="running"||a==="done"||a==="error")&&t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),t.jsxs("div",{className:"rounded-lg border border-border-subtle bg-[#0d0d0d] p-3 font-mono text-[11px] leading-relaxed text-text-secondary overflow-y-auto",style:{maxHeight:320,minHeight:200},children:[v.map((g,x)=>t.jsx("div",{className:g.startsWith("✅")?"text-green-400":"",style:g.startsWith("❌")||g.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:g},x)),a==="running"&&t.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),t.jsx("div",{ref:b})]}),T&&t.jsx("div",{className:"mt-2 px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:T})]})]}),t.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[t.jsxs("div",{className:"text-[10px] text-text-muted",children:[a==="config"&&m.length>0&&`${m.length} script(s) selected`,a==="running"&&"Agent is generating...",a==="done"&&"Run `adhdev provider verify` to validate"]}),t.jsxs("div",{className:"flex gap-2",children:[a==="config"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:j,disabled:m.length===0,className:"machine-btn",style:{background:m.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:m.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:m.length>0?"#a78bfa":void 0,opacity:m.length===0?.4:1},children:"🚀 Start Fix"})]}),a==="running"&&t.jsx("button",{onClick:k,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(a==="done"||a==="error")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{i("config"),S([]),d("")},className:"machine-btn",children:"← Back"}),t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function $f({machineId:e,providers:s,sendDaemonCommand:r,onClose:n,onCreated:a}){var y;const i=s.filter(j=>j.category==="ide"),[c,l]=o.useState(((y=i[0])==null?void 0:y.type)||""),[m,p]=o.useState(""),[u,f]=o.useState(""),[v,S]=o.useState(!1),[T,d]=o.useState(""),[b,N]=o.useState(!1),h=j=>{const k=j.toLowerCase().replace(/[^a-z0-9-]/g,"");p(k),(!u||u===w(m))&&f(w(k))},w=j=>j.split("-").map(k=>k.charAt(0).toUpperCase()+k.slice(1)).join(" "),_=async()=>{if(!(!m||!u||!c)){S(!0),d("");try{const j=await r(e,"provider_clone",{type:m,name:u,category:"ide",location:"user",cloneFrom:c});j!=null&&j.success||j!=null&&j.created?(N(!0),a==null||a(m)):d((j==null?void 0:j.error)||"Failed to create provider")}catch(j){d((j==null?void 0:j.message)||"Connection failed")}S(!1)}};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:t.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick:j=>j.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[t.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children:b?t.jsxs("div",{className:"text-center py-6",children:[t.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),t.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[t.jsx("code",{className:"text-violet-400",children:m})," has been created at ",t.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",m,"/"]})]}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",t.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",m]})," or use Auto-Fix to implement scripts."]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:i.map(j=>t.jsxs("button",{onClick:()=>l(j.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===j.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===j.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[t.jsx("div",{className:"text-lg",children:j.icon}),t.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===j.type?"#a78bfa":"var(--text-secondary)"},children:j.displayName})]},j.type))})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),t.jsx("input",{value:m,onChange:j=>h(j.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),t.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",t.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",m||"...","/"]})]})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),t.jsx("input",{value:u,onChange:j=>f(j.target.value),placeholder:"My Custom IDE",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]}),T&&t.jsx("div",{className:"px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:T})]})}),t.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:b?t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:_,disabled:!m||!u||v,className:"machine-btn",style:{background:m&&u?"rgba(34,197,94,0.12)":void 0,borderColor:m&&u?"rgba(34,197,94,0.3)":void 0,color:m&&u?"#86efac":void 0,opacity:!m||!u||v?.4:1},children:v?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Bf({machineId:e,providers:s,sendDaemonCommand:r}){var I;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,m]=o.useState(null),[p,u]=o.useState("all"),[f,v]=o.useState(null),[S,T]=o.useState(!1),[d,b]=o.useState(null),[N,h]=o.useState("normal"),[w,_]=o.useState(""),[y,j]=o.useState(!1),k=o.useCallback(async()=>{if(e)try{const M=await r(e,"get_provider_source_config",{}),L=Co(M);L&&(b(L),h(L.sourceMode),_(L.explicitProviderDir||""))}catch{}},[e,r]),g=o.useCallback(async()=>{if(e){c(!0);try{const M=await r(e,"get_provider_settings",{}),L=_f(M);if(L){const O=Rf(L,s);O.sort((R,C)=>R.category.localeCompare(C.category)||R.displayName.localeCompare(C.displayName)),a(O)}}catch{}c(!1)}},[e,s,r]);o.useEffect(()=>{n.length===0&&g(),d||k()},[]);const x=async(M,L,O)=>{m(`${M}.${L}`),a(R=>R.map(C=>C.type===M?{...C,values:{...C.values,[L]:O}}:C));try{const R=await r(e,"set_provider_setting",{providerType:M,key:L,value:O});R!=null&&R.success||g()}catch{g()}m(null)},$=async()=>{j(!0);try{const M=await r(e,"set_provider_source_config",{providerSourceMode:N,providerDir:Pf(w)}),L=Co(M);L?(b(L),h(L.sourceMode),_(L.explicitProviderDir||"")):await k(),await g()}catch{await k()}j(!1)};return t.jsxs("div",{children:[t.jsxs("div",{className:"flex justify-between items-center mb-4",children:[t.jsxs("div",{className:"flex gap-1 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(M=>t.jsx("button",{onClick:()=>u(M),className:`machine-btn text-[10px] px-2 py-0.5 ${p===M?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:M.toUpperCase()},M))]}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:()=>T(!0),className:"machine-btn text-[10px] bg-green-500/[0.06] border-green-500/20 text-green-400 hover:bg-green-500/[0.12]",children:"✨ Create Provider"}),t.jsx("button",{onClick:g,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Affects provider resolution, fix/verify flows, and new launches. Existing running sessions may need restart."})]}),t.jsx("button",{onClick:k,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),t.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),t.jsxs("select",{value:N,onChange:M=>h(M.target.value),className:"machine-input text-[11px]",children:[t.jsx("option",{value:"normal",children:"normal"}),t.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),t.jsx("input",{type:"text",value:w,onChange:M=>_(M.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),t.jsx("button",{onClick:()=>void $(),disabled:y,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:y?"Applying…":"Apply + Reload"})]}),t.jsxs("div",{className:"mt-3 grid gap-1 text-[11px] text-text-muted",children:[t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Effective user root:"})," ",(d==null?void 0:d.userDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(d==null?void 0:d.upstreamDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((I=d==null?void 0:d.providerRoots)==null?void 0:I.join(" → "))||"loading…"]})]})]}),p!=="all"&&n.filter(M=>M.category===p).length>1&&(()=>{const M=n.filter(C=>C.category===p),L=new Map;for(const C of M)for(const U of C.schema){if(U.type!=="boolean")continue;const G=L.get(U.key),A=!!(C.values[U.key]??U.default);G?(G.onCount+=A?1:0,G.total+=1):L.set(U.key,{label:U.label||U.key,onCount:A?1:0,total:1})}const O=[...L.entries()].filter(([,C])=>C.total===M.length);if(O.length===0)return null;const R=async(C,U)=>{for(const G of M)await x(G.type,C,U)};return t.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[t.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",p.toUpperCase()," providers (",M.length,")"]}),t.jsx("div",{className:"flex flex-wrap gap-2",children:O.map(([C,U])=>{const G=U.onCount===U.total,A=U.onCount===0;return t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[t.jsx("span",{className:"text-text-secondary font-medium",children:U.label}),t.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",U.onCount,"/",U.total,")"]}),t.jsx("button",{onClick:()=>void R(C,!0),disabled:G,className:`machine-btn text-[9px] px-1.5 py-px ${G?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),t.jsx("button",{onClick:()=>void R(C,!1),disabled:A,className:`machine-btn text-[9px] px-1.5 py-px ${A?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},C)})})]})})(),i&&n.length===0?t.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):t.jsx("div",{className:"flex flex-col gap-2",children:n.filter(M=>p==="all"||M.category===p).map(M=>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 items-center gap-2 mb-2.5",children:[t.jsx("span",{className:"text-lg",children:M.icon}),t.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:M.displayName}),t.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:M.category==="acp"?"rgba(139,92,246,0.08)":M.category==="cli"?"rgba(59,130,246,0.08)":M.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:M.category==="acp"?"#a78bfa":M.category==="cli"?"#60a5fa":M.category==="ide"?"#86efac":"var(--status-warning)"},children:M.category}),M.category==="ide"&&t.jsx("button",{onClick:()=>v(s.find(L=>L.type===M.type)||{type:M.type,name:M.displayName,displayName:M.displayName,icon:M.icon,category:M.category}),className:"ml-auto machine-btn text-[9px] px-2 py-0.5 bg-violet-500/[0.06] border-violet-500/20 text-violet-400 hover:bg-violet-500/[0.12]",children:"🔧 Auto-Fix"})]}),t.jsx("div",{className:"flex flex-col gap-2",children:M.schema.map(L=>t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("div",{className:"text-xs font-medium text-text-primary",children:[L.label||L.key,l===`${M.type}.${L.key}`&&t.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),L.description&&t.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:L.description})]}),t.jsx("div",{className:"shrink-0",children:L.type==="boolean"?t.jsx("button",{onClick:()=>x(M.type,L.key,!(M.values[L.key]??L.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:M.values[L.key]??L.default?"#8b5cf6":"var(--border-subtle)"},children:t.jsx("div",{className:"w-4 h-4 rounded-full bg-white absolute top-[3px] transition-[left] duration-200 shadow-[0_1px_3px_rgba(0,0,0,0.3)]",style:{left:M.values[L.key]??L.default?21:3}})}):L.type==="number"?t.jsx("input",{type:"number",value:Number(M.values[L.key]??L.default??0)||0,min:L.min,max:L.max,onChange:O=>{const R=parseInt(O.target.value)||0;L.min!==void 0&&R<L.min||L.max!==void 0&&R>L.max||x(M.type,L.key,R)},className:"machine-input w-20 text-center text-[11px]"}):L.type==="select"&&L.options?t.jsx("select",{value:String(M.values[L.key]??L.default??""),onChange:O=>x(M.type,L.key,O.target.value),className:"machine-input text-[11px]",children:L.options.map(O=>t.jsx("option",{value:O,children:O},O))}):t.jsx("input",{type:"text",value:String(M.values[L.key]??L.default??""),onBlur:O=>x(M.type,L.key,O.target.value),className:"machine-input w-[120px] text-[11px]"})})]},L.key))})]},M.type))}),f&&t.jsx(Ef,{machineId:e,provider:f,sendDaemonCommand:r,onClose:()=>v(null)}),S&&t.jsx($f,{machineId:e,providers:s,sendDaemonCommand:r,onClose:()=>T(!1),onCreated:()=>{T(!1),g()}})]})}const Kf=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Wf({count:e,since:s,category:r}){return{count:e,since:s,...r==="all"?{}:{category:r}}}function Of(e,s){return s==="all"?e:e.filter(r=>r.category===s)}function Ao(e){if(!e||Object.keys(e).length===0)return"";try{const s=JSON.stringify(e);return s.length>220?`${s.slice(0,220)}…`:s}catch{return"[unserializable payload]"}}function Hf({machineId:e,sendDaemonCommand:s}){const[r,n]=o.useState([]),[a,i]=o.useState([]),[c,l]=o.useState([]),[m,p]=o.useState(0),[u,f]=o.useState(0),[v,S]=o.useState(!0),[T,d]=o.useState("debug"),[b,N]=o.useState("all"),h=o.useRef(null),w=o.useRef(!1),_=Of(a,b);return o.useEffect(()=>{if(!e||!v)return;const y=async()=>{try{const[k,g]=await Promise.all([s(e,"get_logs",{count:200,minLevel:T,since:m}),s(e,"get_debug_trace",Wf({count:120,since:u,category:b}))]),x=(k==null?void 0:k.result)||k;if(k!=null&&k.success&&Array.isArray(x==null?void 0:x.logs)&&x.logs.length>0){n(M=>[...M,...x.logs.map(O=>({timestamp:O.ts,level:O.level,message:`[${O.category}] ${O.message}`}))].slice(-300));const I=Math.max(...x.logs.map(M=>M.ts));p(I)}const $=(g==null?void 0:g.result)||g;if(g!=null&&g.success&&Array.isArray($==null?void 0:$.trace)){i($.trace.slice(-120));const I=$.trace.reduce((M,L)=>Math.max(M,Number(L.ts||0)),u);I>u&&f(I)}}catch{}l(ks.list({limit:120}))};y();const j=setInterval(y,3e3);return()=>clearInterval(j)},[e,v,m,u,T,b,s]),o.useEffect(()=>{if(v&&(r.length>0||a.length>0||c.length>0)){const y=w.current?"smooth":"instant";setTimeout(()=>{var j;(j=h.current)==null||j.scrollIntoView({behavior:y}),w.current=!0},50)}},[r.length,a.length,c.length,v]),o.useEffect(()=>{i([]),f(0)},[b]),t.jsxs("div",{children:[t.jsxs("div",{className:"flex justify-between items-center mb-3",children:[t.jsxs("div",{className:"flex gap-1 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Level"}),["debug","info","warn","error"].map(y=>t.jsx("button",{onClick:()=>{d(y),n([]),p(0)},className:`machine-btn text-[10px] px-2 py-0.5 ${T===y?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:y.toUpperCase()},y))]}),t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsxs("span",{className:"text-[10px] text-text-muted",children:["logs=",r.length," trace=",_.length," web=",c.length]}),t.jsx("button",{onClick:()=>S(!v),className:`machine-btn ${v?"text-green-500 border-green-500/30":""}`,children:v?"⏸ Pause":"▶ Resume"}),t.jsx("button",{onClick:()=>{n([]),i([]),l([]),p(0),f(0),ks.clear()},className:"machine-btn",children:"Clear"})]})]}),t.jsxs("div",{className:"grid gap-3",children:[t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl p-3 min-h-[180px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[t.jsx("div",{className:"mb-2 text-[10px] uppercase tracking-wider text-text-muted",children:"Daemon logs"}),r.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs..."}),r.map((y,j)=>t.jsxs("div",{className:"flex gap-2 py-px",style:{color:y.level==="error"?"#ef4444":y.level==="warn"?"var(--status-warning)":y.level==="debug"?"#64748b":"#94a3b8"},children:[t.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(y.timestamp).toLocaleTimeString()}),t.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:y.level==="error"?"ERR":y.level==="warn"?"WRN":y.level==="debug"?"DBG":"INF"}),t.jsx("span",{children:y.message})]},`log-${j}`))]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl p-3 min-h-[180px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[t.jsxs("div",{className:"mb-2 flex flex-wrap items-center justify-between gap-2",children:[t.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Structured daemon trace",b==="session_host"?" · session_host only":""]}),t.jsx("div",{className:"flex gap-1 items-center",children:Kf.map(y=>t.jsx("button",{onClick:()=>N(y.value),className:`machine-btn text-[10px] px-2 py-0.5 ${b===y.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:y.label},y.value))})]}),_.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:b==="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."}),_.map(y=>t.jsxs("div",{className:"py-1 border-b border-white/5 last:border-b-0",children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted",children:[t.jsx("span",{children:new Date(y.ts).toLocaleTimeString()}),t.jsx("span",{children:y.level.toUpperCase()}),t.jsxs("span",{children:[y.category,".",y.stage]}),y.interactionId&&t.jsxs("span",{children:["ix=",y.interactionId]})]}),t.jsx("div",{children:Ao(y.payload)})]},y.id))]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl p-3 min-h-[160px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[t.jsx("div",{className:"mb-2 text-[10px] uppercase tracking-wider text-text-muted",children:"Browser debug events"}),c.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No browser debug events captured yet."}),c.map(y=>t.jsxs("div",{className:"py-1 border-b border-white/5 last:border-b-0",children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted",children:[t.jsx("span",{children:new Date(y.ts).toLocaleTimeString()}),t.jsx("span",{children:y.kind}),y.topic&&t.jsxs("span",{children:["topic=",y.topic]}),y.interactionId&&t.jsxs("span",{children:["ix=",y.interactionId]})]}),t.jsx("div",{children:Ao(y.payload)})]},y.id))]})]}),t.jsx("div",{ref:h})]})}function kn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Sn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function To(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 Uf(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Ff(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 zf(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 Vf({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,m]=o.useState(!1),p=$i(e,{enabled:!!e,includeSessions:!0,limit:12,intervalMs:8e3}),u=p.diagnostics,f=p.loading,v=p.applyDiagnostics,S=o.useMemo(()=>cf({diagnostics:u,loading:f,refreshing:l,error:n}),[u,f,l,n]),T=o.useMemo(()=>new Map(s.map(I=>[I.sessionId||I.id,I])),[s]),d=o.useCallback(async()=>{if(e){m(!0);try{const I=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:12}),M=kn(I);if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Could not load hosted runtime diagnostics");v(M.diagnostics||M.result||null),a("")}catch(I){const M=I instanceof Error?I.message:"Could not load hosted runtime diagnostics";a(M)}finally{m(!1)}}},[v,e,r]);o.useEffect(()=>{!e||u||f||l||d()},[u,f,e,d,l]);const b=o.useCallback(async(I,M)=>{const L=`${I}:${M.sessionId}`;if(!(I==="session_host_stop_session"&&!window.confirm(`Stop ${M.displayName}?
|
|
66
66
|
This will terminate the hosted runtime.`))){c(L);try{const O=await r(e,I,{sessionId:M.sessionId}),R=kn(O);if(!(R!=null&&R.success))throw new Error((R==null?void 0:R.error)||"Session host action failed");const C=I==="session_host_resume_session"?"resumed":I==="session_host_restart_session"?"restarted":"stopped";ct.showToast(`Session host ${C}: ${M.displayName}`,"success"),await d()}catch(O){const R=O instanceof Error?O.message:"Session host action failed";ct.showToast(R,"warning"),a(R)}finally{c(O=>O===L?null:O)}}},[e,d,r]),N=o.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
67
|
-
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 M=await r(e,"session_host_prune_duplicate_sessions",{}),L=kn(M);if(!(L!=null&&L.success))throw new Error((L==null?void 0:L.error)||"Duplicate prune failed");const O=L.result||{},R=Array.isArray(O.prunedSessionIds)?O.prunedSessionIds.length:0,C=typeof O.duplicateGroupCount=="number"?O.duplicateGroupCount:0;ct.showToast(`Pruned ${R} duplicate runtime(s) across ${C} group(s)`,"success"),await d()}catch(M){const L=M instanceof Error?M.message:"Duplicate prune failed";ct.showToast(L,"warning"),a(L)}finally{c(M=>M==="session_host_prune_duplicate_sessions"?null:M)}}},[e,d,r]),h=o.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((I,M)=>(M.lastActivityAt||0)-(I.lastActivityAt||0)),[u==null?void 0:u.sessions]),w=o.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:uc(h),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,h]),_=w.liveRuntimes,y=w.recoverySnapshots,j=w.inactiveRecords,k=o.useMemo(()=>zf(_),[_]),g=o.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),x=o.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(I=>I.level==="warn"||I.level==="error")||null,[u==null?void 0:u.recentLogs]),$=(I,M)=>{var B;const L=i===`session_host_resume_session:${I.sessionId}`,O=i===`session_host_restart_session:${I.sessionId}`,R=i===`session_host_stop_session:${I.sessionId}`,C=ya(I.meta),U=T.get(I.sessionId),G=I.attachedClients.length===1?"1 client":`${I.attachedClients.length} clients`,A=M==="recovery"?"Recover":"Resume",D=mc(M);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:I.displayName||(U==null?void 0:U.cliName)||I.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Ff(I.lifecycle)}`,children:I.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:I.workspaceLabel||(U==null?void 0:U.runtimeWorkspaceLabel)||I.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:I.runtimeKey}),I.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",I.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((B=I.writeOwner)==null?void 0:B.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Uf(I.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(qn,{size:11})," ",G]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",To(I.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:[M==="recovery"&&(I.lifecycle==="interrupted"||I.lifecycle==="failed"||I.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{b("session_host_resume_session",I)},children:L?`${A}ing…`:A}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{b("session_host_restart_session",I)},children:O?"Restarting…":"Restart"}),M==="live"&&(I.lifecycle==="running"||I.lifecycle==="starting"||I.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",I)},children:R?"Stopping…":"Stop"})]})]})},I.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(Ot,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:yu()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[k>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{N()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${k})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${S.toneClass}`,children:S.label}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{d()},disabled:f||l,children:[t.jsx(_s,{size:13}),f||l?"Refreshing…":"Refresh"]})]})]}),n&&!u&&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(ls,{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})]})]})}),u&&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:u.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:y.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:u.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:To(u.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Sn(u.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(ls,{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:[Sn(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(Hr,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:js("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(I=>$(I,"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(Ot,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:js("recovery")}),y.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:y.map(I=>$(I,"recovery"))})]}),j.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:js("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:j.map(I=>$(I,"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"}),g.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:g.map(I=>{var L;const M=h.find(O=>O.sessionId===I.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:(M==null?void 0:M.displayName)||((L=T.get(I.sessionId))==null?void 0:L.cliName)||I.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[I.action,I.lifecycle?` · ${I.lifecycle}`:"",I.detail?` · ${I.detail}`:"",I.error?` · ${I.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${I.success===!1?"text-red-300":"text-text-secondary"}`,children:Sn(I.timestamp)})]},`${I.sessionId}:${I.timestamp}:${I.action}`)})})]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",t.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),n?t.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function Gf({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 Nn({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 Cn({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 qf({machineEntry:e,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),m=r.slice(0,4),u=zs(e,"0.8.68");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(Nn,{icon:t.jsx(Ht,{size:13}),children:"Current Chats"}),t.jsx(Cn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(f=>{const v=Kn(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)}),v>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Fr(v)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ms(f)})]},f.tabKey)})})})]}),m.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Nn,{icon:t.jsx(zo,{size:13}),children:"Recent Launches"}),t.jsx(Cn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:m.map(f=>{const{metaText:v,updatedLabel:S}=Xi(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}),S&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:S})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:v})]},f.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Nn,{icon:t.jsx(ls,{size:13}),children:"Daemon Update"}),t.jsx(Cn,{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:u?"Daemon update required":"Version mismatch detected"}),t.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:u?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),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(_s,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Yf(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Xf(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const Qf={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 wr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Jf(e){const s=e instanceof Error?e.message:String(e||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function In({category:e,machine:s,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:m,initialWorkspacePath:p}){const u=Ls(),{handleLaunchIde:f,handleStopCli:v,handleRestartIde:S,handleStopIde:T,handleDetectIdes:d,launchingIde:b,launchingAgentType:N,addLog:h}=c,[w,_]=o.useState(null),y=o.useCallback(P=>{P&&u(Yf(P))},[u]),j=Qf[e],k=e==="ide",g=e==="acp",x=o.useMemo(()=>n.filter(P=>P.category===e&&(e==="ide"||P.installed!==!1)),[e,n]),$=o.useMemo(()=>new Map(x.map(P=>[P.type,P.displayName||P.type])),[x]),[I,M]=o.useState(""),[L,O]=o.useState(""),[R,C]=o.useState([]),[U,G]=o.useState(""),[A,D]=o.useState(""),[B,W]=o.useState([]),[X,xe]=o.useState(!1),[Re,ie]=o.useState(""),[Ie,te]=o.useState(!1),[ce,oe]=o.useState(()=>gt()),[ye,ae]=o.useState(null),[F,be]=o.useState(p?"__custom__":m||s.defaultWorkspaceId||""),[se,pe]=o.useState(p||""),[J,le]=o.useState([]),[ne,ge]=o.useState(!1),[ue,E]=o.useState(""),[ve,he]=o.useState([]),[Se,Q]=o.useState(!1),[Ne,Ue]=o.useState(""),Ee=o.useRef(null),[Ve,Xe]=o.useState(null),Qe=o.useRef("__home__"),[ft,Ge]=o.useState("__home__"),[bt,dt]=o.useState(!1),ut=o.useRef(0),ht=J.filter(P=>!a.some(Y=>Y.type===P&&jt(Y.status)!=="stopped")),ot=o.useRef({});o.useEffect(()=>{s.defaultWorkspaceId&&!F&&be(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),o.useEffect(()=>{if(p){be("__custom__"),pe(p);return}m&&(be(m),pe(""))},[m,p]),o.useEffect(()=>{k||I&&(x.some(P=>P.type===I)||(M(""),D("")))},[x,k,I]);const de=(()=>{if(F==="__custom__")return se.trim();if(!F)return"";const P=(s.workspaces||[]).find(Y=>Y.id===F);return(P==null?void 0:P.path)||""})(),ze=o.useCallback(P=>{const Y=ot.current[P];Y&&(clearTimeout(Y),delete ot.current[P]),le(re=>re.includes(P)?re.filter(De=>De!==P):re)},[]),Je=o.useRef(new Set),tt=o.useCallback(async P=>{if(l){Q(!0),Ue("");try{const Y=await Xr(l,r,P);E(Y.path),pe(Y.path),he(Y.directories)}catch(Y){Ue(Y instanceof Error?Y.message:"Could not load folder")}finally{Q(!1)}}},[r,l]),xt=o.useCallback(()=>{if(!l)return;be("__custom__"),ge(!0);const P=a.map(re=>re.workspace),Y=Yr(s.platform,qr(se.trim(),de,p,P,s.defaultWorkspacePath,(s.workspaces||[]).map(re=>re.path)));tt(Y)},[se,p,tt,s.defaultWorkspacePath,s.platform,s.workspaces,a,de,l]),yt=o.useCallback(P=>{const Y=String(P.workspace||"").trim();if(!Y)return;const re=(s.workspaces||[]).find(De=>wr(De.path)===wr(Y));if(re){be(re.id),pe("");return}be("__custom__"),pe(Y)},[s.workspaces]),_t=o.useCallback(P=>{const Y=String(P.workspace||"").trim();if(!Y)return{workspaceId:null,workspacePath:"",useHome:!0};const re=(s.workspaces||[]).find(De=>wr(De.path)===wr(Y));return re?{workspaceId:re.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:Y,useHome:!1}},[s.workspaces]),St=o.useCallback(async P=>{if(!l||!P||e!=="cli"){W([]),xe(!1),ie("");return}const Y=ut.current+1;ut.current=Y,xe(!0),ie("");try{const re=await l(r,"list_saved_sessions",{providerType:P,kind:"cli",limit:30});if(ut.current!==Y)return;const De=(re==null?void 0:re.result)??re;W(Array.isArray(De==null?void 0:De.sessions)?De.sessions:[])}catch(re){if(ut.current!==Y)return;W([]),ie(re instanceof Error?re.message:"Could not load saved sessions")}finally{ut.current===Y&&xe(!1)}},[e,r,l]),Tt=o.useMemo(()=>{if(e!=="cli"||!I)return null;const P=$.get(I)||I;return{routeId:r,daemonId:r,providerSessionId:A||void 0,transport:"pty",mode:"chat",agentName:P,agentType:I,status:"idle",title:P,messages:[],ideType:I,workspaceName:de,displayPrimary:P,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${I}`}},[e,r,$,de,A,I]),q=o.useCallback(P=>{if(e==="ide"||!P){C([]);return}C(lc(r,P))},[e,r]);o.useEffect(()=>{if(D(""),q(I),e!=="cli"||!I){W([]),ie(""),xe(!1);return}St(I)},[e,q,St,I]);const Be=o.useMemo(()=>B.find(P=>P.providerSessionId===A)||null,[B,A]);o.useEffect(()=>{if(!A)return;const P=B.find(Y=>Y.providerSessionId===A);P!=null&&P.canResume||D("")},[B,A]);const Pe=o.useCallback((P,Y)=>{Ee.current=Y,Qe.current=P.selectedWorkspaceKey||"__home__",Ge(P.selectedWorkspaceKey||"__home__"),Xe(P)},[]),K=o.useCallback(()=>{Ee.current&&(dt(!0),Ee.current().finally(()=>{Ee.current=null,dt(!1),Xe(null)}))},[]),H=o.useCallback(P=>{if(!P)return;le(re=>re.includes(P)?re:[...re,P]);const Y=ot.current[P];Y&&clearTimeout(Y),ot.current[P]=setTimeout(()=>{le(re=>re.includes(P)?re.filter(De=>De!==P):re),delete ot.current[P]},2e4)},[]);o.useEffect(()=>{for(const Y of a)jt(Y.status)!=="stopped"&&(J.includes(Y.type)&&!Je.current.has(Y.type)&&(Je.current.add(Y.type),h("info",`${$.get(Y.type)||Y.type} launched`,!0)),ze(Y.type));const P=new Set(a.filter(Y=>jt(Y.status)!=="stopped").map(Y=>Y.type));Je.current.forEach(Y=>{!J.includes(Y)&&!P.has(Y)&&Je.current.delete(Y)})},[h,ze,a,J,$]),o.useEffect(()=>()=>{Object.values(ot.current).forEach(clearTimeout),ot.current={}},[]);const[z,V]=o.useState({}),[ee,je]=o.useState(null);o.useEffect(()=>{if(!k||!r||!l)return;(async()=>{try{const Y=await l(r,"get_ide_extensions",{}),re=(Y==null?void 0:Y.result)||Y;re!=null&&re.success&&(re!=null&&re.ideExtensions)&&V(re.ideExtensions)}catch{}})()},[k,r,l]);const Ae=P=>k?at(P.type):e==="cli"?P.cliName:P.acpName,Ce=k?s.detectedIdes||[]:[],We=o.useCallback(async P=>{const Y=(P==null?void 0:P.type)||I,re=(P==null?void 0:P.workspacePath)??de;if(k){await f(Y,re?{workspace:re}:void 0)&&H(Y);return}const De=await c.runLaunchCliCore({cliType:Y,dir:P!=null&&P.workspaceId?void 0:re||void 0,workspaceId:(P==null?void 0:P.workspaceId)||void 0,useHome:(P==null?void 0:P.useHome)||!(P!=null&&P.workspaceId)&&!re,argsStr:(P==null?void 0:P.argsStr)??(L||void 0),model:(P==null?void 0:P.model)??(g&&U||void 0),resumeSessionId:(P==null?void 0:P.resumeSessionId)||!g&&e==="cli"&&Y===I&&A||void 0});if(De.success||De.pending){const Me=(P==null?void 0:P.argsStr)??L;!k&&(Me!=null&&Me.trim())&&(dc(r,Y,Me),q(Y)),H(Y),De.success&&De.sessionId&&y(De.sessionId)}},[c,f,g,k,L,U,q,H,r,y,de,A,I]),Oe=vi(k?"ide":g?"acp":"cli",!k&&!g&&!!A),Ze=wi(k?"ide":g?"acp":"cli",!k&&!g&&!!A),Le=()=>{var Me;const P=k?at(I):$.get(I)||I,Y=!k&&!g&&!!A,{options:re,selectedKey:De}=is({machine:s,currentWorkspaceId:F&&F!=="__custom__"?F:null,currentWorkspacePath:de});Pe({title:Y?ia(P):ss("start-fresh",P),description:Y?ca():rs("start-fresh"),confirmLabel:Oe,busyLabel:Ze,workspaceOptions:re,selectedWorkspaceKey:De,details:[{label:"Mode",value:j.label},{label:"Provider",value:P},...!k&&e==="cli"&&A?[{label:"Resume",value:((Me=B.find($e=>$e.providerSessionId===A))==null?void 0:Me.title)||A}]:[],...!k&&L.trim()?[{label:"Arguments",value:L.trim()}]:[],...g&&U.trim()?[{label:"Model",value:U.trim()}]:[]]},async()=>{const $e=re.find(we=>we.key===Qe.current);$e!=null&&$e.workspaceId?(be($e.workspaceId),pe("")):$e!=null&&$e.workspacePath?(be("__custom__"),pe($e.workspacePath)):(be(""),pe("")),await We({workspaceId:($e==null?void 0:$e.workspaceId)??null,workspacePath:($e==null?void 0:$e.workspacePath)??"",useHome:!($e!=null&&$e.workspaceId)&&!($e!=null&&$e.workspacePath)})})},Z=P=>{k?T(P):v(P.type,P.workspace,P.id)},Te=o.useCallback(async(P,Y,re=!1)=>{if(P.mode===Y){re&&P.sessionId&&y(P.sessionId);return}if(!l||!P.sessionId){re&&P.sessionId&&y(P.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:P.sessionId,cliType:P.type,mode:Y}),re&&y(P.sessionId)}catch(De){Jf(De)?console.warn("Skipped CLI view mode switch:",De instanceof Error?De.message:String(De)):console.error("Failed to switch CLI view mode:",De)}},[r,y,l]),Ke=t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:F,onChange:P=>{const Y=P.target.value;if(be(Y),Y==="__custom__"&&l){xt();return}Y!=="__custom__"&&pe("")},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(P=>t.jsxs("option",{value:P.id,children:[P.id===s.defaultWorkspaceId?"⭐ ":"",Vr(P.path,P.label)]},P.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…"})]})}),F==="__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:xt,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:se,onChange:P=>pe(P.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:F==="__custom__"?de?t.jsx("span",{className:"font-mono truncate block",title:de,children:de}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":de?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:F===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:de,children:de})]}):"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 ${j.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 ",j.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:k?Ce.length>0?Ce.map(P=>{const Y=a.find(we=>(we.type||"").toLowerCase()===(P.type||"").toLowerCase()&&jt(we.status)!=="stopped"),re=P.running||!!Y,De=!!Y&&Y.cdpConnected,Me=J.includes(P.type||P.id||""),$e=I===(P.type||"");return t.jsxs("button",{onClick:()=>{if(De&&Y){const we=Y.sessionId;we?u(`/dashboard?activeTab=${encodeURIComponent(we)}`,{state:{openRemoteForTabKey:we}}):u("/dashboard",{state:{openRemoteForTabKey:Y.id}});return}Me||M(we=>we===(P.type||"")?"":P.type||"")},disabled:!!b||Me,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${De?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":$e?"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!==P.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(P.type)}),re&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${De?"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:P.name||at(P.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${De?"text-green-400":Me?"text-orange-400":$e?"text-accent-primary":"text-text-muted"}`,children:De?"Open Session":Me?"Starting...":$e?"Configure":"Select"})]})]},P.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(ol,{size:14})," Scan System"]})]}):x.length>0?x.map(P=>{const Y=I===P.type,re=J.includes(P.type),Me=!!a.find($e=>$e.type===P.type&&jt($e.status)!=="stopped");return t.jsxs("button",{onClick:()=>M($e=>$e===P.type?"":P.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Y?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:P.icon}),Me&&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:P.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${re?"text-orange-400":Y?"text-accent-primary":"text-text-muted"}`,children:re?"Starting...":Y?"Configure":"Select"})]})]},P.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."})]})}),I&&(k?Ce.find(P=>P.type===I):x.find(P=>P.type===I))&&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:k?at(I):$.get(I)||I})]}),Ke,!k&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!g&&e==="cli"&&t.jsx(pc,{busy:!!N||!!b||J.includes(I),savedSessionsLoading:X,savedSessionsError:Re,selectedSession:Be,onRefresh:()=>void St(I),onOpenHistory:()=>{I&&(te(!0),St(I))},onClearSelection:()=>D("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[g&&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:U,onChange:P=>G(P.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:L,onChange:P=>O(P.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"}),R.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:R.map(P=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>O(P),title:P,children:P},P))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:Le,disabled:!!N||!!b||J.includes(I),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:N===I||b===I?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+J.filter(P=>!a.some(Y=>Y.type===P&&jt(Y.status)!=="stopped")).length,")"]}),a.length===0&&ht.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 ",j.plural," running"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[ht.map(P=>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(P)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:k?at(P):$.get(P)||P}),t.jsx("div",{className:"text-[11px] text-text-muted",children:N===P?"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:${P}`)),a.map(P=>{const Y=k?P:null,re=!k&&!g?P:null,De=jt(P.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(P.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Ae(P),(Y==null?void 0:Y.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",Y.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[t.jsx("span",{children:P.workspace||"—"}),(re==null?void 0:re.mode)&&t.jsx("span",{className:re.mode==="chat"?"text-violet-400":"text-text-secondary",children:re.mode==="chat"?"Chat view":"Terminal view"})]}),re&&(re.runtimeKey||re.runtimeWriteOwner)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[re.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 ",re.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 Me;(Me=navigator.clipboard)==null||Me.writeText(`adhdev attach ${re.runtimeKey}`),_(re.runtimeKey||null),window.setTimeout(()=>{_($e=>$e===re.runtimeKey?null:$e)},1200)},children:w===re.runtimeKey?"Copied":"Copy"})]}),re.runtimeWriteOwner&&t.jsx("span",{style:{color:re.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:re.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Xf(re.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 ${De==="stopped"?"bg-red-500/[0.08] text-red-500":De==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:De}),k&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const Me=P.sessionId;if(Me){u(`/dashboard?activeTab=${encodeURIComponent(Me)}`,{state:{openRemoteForTabKey:Me}});return}u("/dashboard",{state:{openRemoteForTabKey:P.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(It,{size:13})}),t.jsx("button",{onClick:()=>{const Me=P.workspace||"",{options:$e,selectedKey:we}=is({machine:s,currentWorkspacePath:Me});Pe({title:ss("restart-ide",at(P.type)),description:rs("restart-ide"),confirmLabel:Ts("restart-ide"),busyLabel:Ms("restart-ide"),workspaceOptions:$e,selectedWorkspaceKey:we,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:at(P.type)}]},async()=>{const st=$e.find(Ft=>Ft.key===Qe.current),it=(st==null?void 0:st.workspacePath)??"";if(it&&it!==Me){await We({type:P.type,workspacePath:it});return}await S(P)})},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(_s,{size:14})})]}),g&&t.jsx("button",{onClick:()=>{const Me=P.sessionId;Me&&y(Me)},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:!P.sessionId,children:t.jsx(Ht,{size:14})}),re&&De!=="stopped"&&t.jsxs(t.Fragment,{children:[re.mode&&t.jsx(na,{mode:re.mode,onChange:Me=>void Te(re,Me,!1),compact:!0}),t.jsx("button",{onClick:()=>{const Me=P.sessionId;Me&&y(Me)},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:!P.sessionId,children:re.mode==="chat"?t.jsx(Ht,{size:14}):t.jsx(It,{size:13})})]}),De==="stopped"?t.jsx("button",{onClick:()=>{const Me=P.workspace||"",$e=k?at(P.type):Ae(P),{options:we,selectedKey:st}=is({machine:s,currentWorkspacePath:Me});Pe({title:ss("restart-stopped",$e),description:rs("restart-stopped"),confirmLabel:Ts("restart-stopped"),busyLabel:Ms("restart-stopped"),workspaceOptions:we,selectedWorkspaceKey:st,details:[{label:"Mode",value:j.label},{label:"Provider",value:$e}]},async()=>{const it=we.find(Ft=>Ft.key===Qe.current);await We({type:P.type,workspaceId:(it==null?void 0:it.workspaceId)??null,workspacePath:(it==null?void 0:it.workspacePath)??"",useHome:!(it!=null&&it.workspaceId)&&!(it!=null&&it.workspacePath)})})},disabled:J.includes(P.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:J.includes(P.type)?"⏳":t.jsx(Xn,{size:14})}):t.jsx("button",{onClick:()=>Z(P),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(kt,{size:14})})]})]}),Y&&Y.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:Y.aiAgents.map(Me=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Jo(Me.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Me.name," · ",jt(Me.status)]},Me.id))}),Y&&(z[Y.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:(z[Y.type]||[]).map(Me=>t.jsxs("button",{disabled:ee===`${Y.type}.${Me.type}`,onClick:async()=>{const $e=`${Y.type}.${Me.type}`;je($e);try{await l(r,"set_ide_extension",{ideType:Y.type,extensionType:Me.type,enabled:!Me.enabled}),V(we=>({...we,[Y.type]:(we[Y.type]||[]).map(st=>st.type===Me.type?{...st,enabled:!st.enabled}:st)}))}catch(we){console.error("Extension toggle failed:",we)}finally{je(null)}},className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-medium border transition-colors duration-150 cursor-pointer ${Me.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 ${Me.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Me.name,t.jsx("span",{className:"text-[9px] font-normal",children:Me.enabled?"ON":"OFF"})]},Me.type))})]})]},P.id)})]}),ne&&l&&t.jsx(Qr,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:ue,directories:ve,busy:Se,error:Ne,confirmLabel:"Use this folder",onClose:()=>ge(!1),onNavigate:P=>{tt(P)},onConfirm:P=>{pe(P),be("__custom__"),ge(!1)}}),Ve&&t.jsx(ba,{title:Ve.title,description:Ve.description,details:Ve.details,workspaceOptions:Ve.workspaceOptions,selectedWorkspaceKey:ft,onWorkspaceChange:P=>{Qe.current=P,Ge(P)},confirmLabel:Ve.confirmLabel,busyLabel:Ve.busyLabel,busy:bt,onConfirm:K,onCancel:()=>{Ee.current=null,Xe(null)}}),Ie&&Tt&&t.jsx(la,{activeConv:Tt,ides:[],isCreatingChat:!1,isRefreshingHistory:X,savedSessions:B,isSavedSessionsLoading:X,isResumingSavedSessionId:ye,savedHistoryFilters:ce,onSavedHistoryFiltersChange:oe,onClose:()=>te(!1),onNewChat:()=>{D(""),te(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{St(I)},onResumeSavedSession:P=>{if(!P.canResume||ye)return;const Y=_t(P);D(P.providerSessionId),yt(P),ae(P.providerSessionId),te(!1),We({type:P.providerType,workspaceId:Y.workspaceId,workspacePath:Y.workspacePath,useHome:Y.useHome,resumeSessionId:P.providerSessionId}).finally(()=>{ae(re=>re===P.providerSessionId?null:re)})}})]})}const Mo=[{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 Zf({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:m="ide",initialWorkspaceId:p,initialWorkspacePath:u,sendDaemonCommand:f}){var d;const[v,S]=o.useState(m);o.useEffect(()=>{S(m)},[m]);const T=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:Mo.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 ${v===b.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>S(b.id),children:[t.jsx("span",{children:b.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${v===b.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:T[b.id]})]},b.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(d=Mo.find(b=>b.id===v))==null?void 0:d.helper})]}),v==="ide"&&t.jsx(In,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:u}),v==="cli"&&t.jsx(In,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:u}),v==="acp"&&t.jsx(In,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:u})]})}function eh({onNicknameSynced:e}={}){var F,be,se,pe,J,le,ne,ge,ue;const{id:s}=Hc(),r=Ls(),n=Vn(),{sendCommand:a}=At(),i=tr(),c=pi(),l=c.ides||[],m=c.initialLoaded??!0,p=l.find(E=>E.id===s&&E.type==="adhdev-daemon"),u=l.some(E=>E.type==="adhdev-daemon"),[f,v]=o.useState("workspace"),[S,T]=o.useState("ide"),d=o.useRef(null),[b,N]=o.useState(null),h=o.useRef("__home__"),[w,_]=o.useState("__home__"),[y,j]=o.useState(!1),k=o.useRef(null);o.useEffect(()=>{!s||!p||!(!p.workspaces||!p.availableProviders||!p.detectedIdes||!p.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,p,s]),dm(s&&f==="overview"?[s]:[],{enabled:f==="overview",intervalMs:15e3});const g=()=>{if(u){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},x=Mf({machineId:s,registeredMachineId:(p==null?void 0:p.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:k});o.useEffect(()=>ct.onToast(ve=>{c.setToasts(Se=>{if(Se.some(Ue=>Ue.message===ve.message&&ve.timestamp-Ue.timestamp<3e3))return Se;const Ne={id:ve.id,message:ve.message,type:ve.type,timestamp:ve.timestamp,targetKey:ve.targetKey,actions:ve.actions};return[...Se.slice(-4),Ne]});const he=ve.duration||5e3;setTimeout(()=>c.setToasts(Se=>Se.filter(Q=>Q.id!==ve.id)),he)}),[c]);const $=(p==null?void 0:p.availableProviders)||[],I={};for(const E of $)I[E.type]=E.icon;const M=E=>I[E]||"",L=p?{id:p.id,hostname:Zo(p,{fallbackId:p.id}),platform:((F=p.machine)==null?void 0:F.platform)||"unknown",arch:((be=p.machine)==null?void 0:be.arch)||"",cpus:((se=p.machine)==null?void 0:se.cpus)||0,totalMem:((pe=p.machine)==null?void 0:pe.totalMem)||0,freeMem:(J=p.machine)==null?void 0:J.freeMem,availableMem:(le=p.machine)==null?void 0:le.availableMem,loadavg:(ne=p.machine)==null?void 0:ne.loadavg,uptime:(ge=p.machine)==null?void 0:ge.uptime,release:((ue=p.machine)==null?void 0:ue.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,O=l.filter(E=>E.daemonId===s&&E.type!=="adhdev-daemon").filter(E=>!Xs(E)&&!vs(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,version:E.version||"",instanceId:E.instanceId||"",status:E.status,workspace:E.workspace||null,terminals:E.terminals||0,aiAgents:Ql(E.aiAgents||(E.agents||[]).map(ve=>({id:ve.name,name:ve.name,status:ve.status,version:ve.version}))),activeChat:E.activeChat||null,chats:E.chats||[],childSessions:E.childSessions||[],cdpConnected:E.cdpConnected||!1,daemonId:s})),R=l.filter(E=>E.daemonId===s&&Xs(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,cliName:E.cliName||E.type,status:E.status,workspace:E.workspace||"",activeChat:E.activeChat||null,providerSessionId:E.providerSessionId,mode:E.mode,runtimeKey:E.runtimeKey,runtimeDisplayName:E.runtimeDisplayName,runtimeWorkspaceLabel:E.runtimeWorkspaceLabel,runtimeWriteOwner:E.runtimeWriteOwner||null,runtimeAttachedClients:E.runtimeAttachedClients||[],daemonId:s})),C=l.filter(E=>E.daemonId===s&&vs(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,acpName:E.cliName||E.type,status:E.status,workspace:E.workspace||"",activeChat:E.activeChat||null,providerSessionId:E.providerSessionId,daemonId:s})),U=p?Ct(p,{fallbackId:s}):"",G="workspace",A=n.state,D=A==null?void 0:A.initialMachineTab,B=A==null?void 0:A.initialWorkspaceCategory,W=A==null?void 0:A.initialWorkspaceId,X=A==null?void 0:A.initialWorkspacePath,xe=D==="ides"||D==="clis"||D==="acps"?"workspace":D||G,Re=D==="ides"?"ide":D==="clis"?"cli":D==="acps"?"acp":B,ie=[...O.map(E=>{var ve,he,Se,Q,Ne;return{id:`ide:${E.type}:${E.workspace||""}`,label:((ve=E.activeChat)==null?void 0:ve.title)||E.type,kind:"ide",providerType:E.type,subtitle:E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:((Ne=(Q=(Se=(he=E.activeChat)==null?void 0:he.messages)==null?void 0:Se.at)==null?void 0:Q.call(Se,-1))==null?void 0:Ne.timestamp)||0}}),...R.map(E=>{var ve,he,Se,Q,Ne;return{id:`cli:${E.type}:${E.workspace||""}`,label:((ve=E.activeChat)==null?void 0:ve.title)||E.cliName,kind:"cli",providerType:E.type,providerSessionId:E.providerSessionId,subtitle:E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:((Ne=(Q=(Se=(he=E.activeChat)==null?void 0:he.messages)==null?void 0:Se.at)==null?void 0:Q.call(Se,-1))==null?void 0:Ne.timestamp)||0}}),...C.map(E=>{var ve,he,Se,Q,Ne;return{id:`acp:${E.type}:${E.workspace||""}`,label:((ve=E.activeChat)==null?void 0:ve.title)||E.acpName,kind:"acp",providerType:E.type,providerSessionId:E.providerSessionId,subtitle:ds(E.summaryMetadata)||E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:((Ne=(Q=(Se=(he=E.activeChat)==null?void 0:he.messages)==null?void 0:Se.at)==null?void 0:Q.call(Se,-1))==null?void 0:Ne.timestamp)||0}})].sort((E,ve)=>(ve.lastLaunchedAt||0)-(E.lastLaunchedAt||0)),Ie=((p==null?void 0:p.recentLaunches)||[]).length>0?((p==null?void 0:p.recentLaunches)||[]).map(E=>({id:E.id,label:E.title||E.providerName||E.providerType,kind:E.kind,providerType:E.providerType,providerSessionId:E.providerSessionId,subtitle:ds(E.summaryMetadata)||E.workspace||void 0,workspace:E.workspace,summaryMetadata:E.summaryMetadata,lastLaunchedAt:E.lastLaunchedAt})):ie,te=o.useMemo(()=>{var ve;const E=((ve=c.connectionStates)==null?void 0:ve[s||""])||void 0;return l.filter(he=>he.daemonId===s&&he.type!=="adhdev-daemon").flatMap(he=>da(he,{},{connectionStates:s&&E?{[s]:E}:void 0,defaultConnectionState:E})).filter(he=>!(he.transport==="pty"&&he.mode==="terminal")).sort((he,Se)=>Kn(Se)-Kn(he))},[l,c.connectionStates,s]),ce=o.useCallback(E=>{const ve=E.sessionId||E.tabKey;ve&&r(`/dashboard?activeTab=${encodeURIComponent(ve)}`)},[r]),oe=o.useCallback(()=>{d.current&&(j(!0),d.current().finally(()=>{d.current=null,j(!1),N(null)}))},[]),ye=o.useCallback(E=>{if(!L)return;const{options:ve,selectedKey:he}=is({machine:L,currentWorkspacePath:E.workspace}),Se=async()=>{T(E.kind),v("workspace")};d.current=async()=>{const Q=ve.find(Ee=>Ee.key===h.current),Ne=(Q==null?void 0:Q.workspacePath)??null,Ue=(Q==null?void 0:Q.workspaceId)??null;if(E.kind==="ide"&&E.providerType){await x.handleLaunchIde(E.providerType,Ne?{workspace:Ne}:void 0);return}if((E.kind==="cli"||E.kind==="acp")&&E.providerType){await x.runLaunchCliCore({cliType:E.providerType,dir:Ue?void 0:Ne||"",workspaceId:Ue||void 0,model:E.kind==="acp"&&ti(E.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:E.providerSessionId});return}await Se()},h.current=he,_(he),N({title:E.kind==="ide"?ss("restart-ide",E.label):E.providerSessionId?ia(E.label):ss("start-fresh",E.label),description:E.kind==="ide"?rs("restart-ide"):E.providerSessionId?ca():rs("start-fresh"),confirmLabel:E.kind==="ide"?Ts("restart-ide"):E.providerSessionId?Dr(!0):Ts("start-fresh"),busyLabel:E.kind==="ide"?Ms("restart-ide"):E.providerSessionId?aa(!0):Ms("start-fresh"),workspaceOptions:ve,details:[{label:"Mode",value:E.kind.toUpperCase()},...E.providerType?[{label:"Provider",value:E.providerType}]:[]]})},[x,L]);if(o.useEffect(()=>{v(xe)},[G,xe,s]),o.useEffect(()=>{Re&&T(Re)},[Re,s]),!L)return m?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:g,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 ae=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(It,{size:14})," Workspace"]}),count:O.length+R.length+C.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ot,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Or,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(il,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(nl,{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:g,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),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:E=>x.setNicknameInput(E.target.value),onKeyDown:E=>{E.key==="Enter"&&x.handleSaveNickname(),E.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(L.machineNickname||"")},title:"Click to set nickname",children:U}),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:[L.platform," · ",L.arch]}),t.jsxs("span",{children:[L.cpus," cores"]}),(p==null?void 0:p.version)&&t.jsxs("span",{children:["v",p.version]}),L.p2p.available&&t.jsxs("span",{children:["P2P ",L.p2p.state==="connected"?"connected":L.p2p.state]}),L.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:L.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ae.map(E=>t.jsxs("button",{onClick:()=>v(E.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${f===E.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[E.label,E.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${f===E.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:E.count})]},E.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(qf,{machineEntry:p,providers:$,recentLaunches:Ie,currentConversations:te,onUpgradeDaemon:async()=>{try{await a(s,"daemon_upgrade",{})}catch{}},onOpenRecent:ye,onOpenConversation:ce}),t.jsx(Zf,{machine:L,machineId:s,providers:$,ideSessions:O,cliSessions:R,acpSessions:C,actions:x,getIcon:M,initialCategory:S,initialWorkspaceId:W,initialWorkspacePath:X,sendDaemonCommand:a})]}),f==="providers"&&t.jsx(Bf,{machineId:s,providers:$,sendDaemonCommand:a}),f==="overview"&&t.jsx(Lf,{machineId:s,machine:L,ideSessions:O,cliSessions:R,acpSessions:C,actions:x,sendDaemonCommand:a}),f==="session-host"&&t.jsx(Vf,{machineId:s,cliSessions:R,sendDaemonCommand:a}),f==="logs"&&t.jsx(Hf,{machineId:s,sendDaemonCommand:a})]})})}),x.launchPick&&L&&t.jsx(Gf,{machine:L,launchPick:x.launchPick,actions:x}),b&&t.jsx(ba,{title:b.title,description:b.description,details:b.details,workspaceOptions:b.workspaceOptions,selectedWorkspaceKey:w,onWorkspaceChange:E=>{h.current=E,_(E)},confirmLabel:b.confirmLabel,busyLabel:b.busyLabel,busy:y,onConfirm:oe,onCancel:()=>{d.current=null,N(null)}}),t.jsx(ji,{toasts:c.toasts||[],onDismiss:E=>c.setToasts(ve=>ve.filter(he=>he.id!==E)),onClickToast:E=>{E.targetKey&&r(`/dashboard?activeTab=${encodeURIComponent(E.targetKey)}`)}}),t.jsx("style",{children:`
|
|
67
|
+
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 M=await r(e,"session_host_prune_duplicate_sessions",{}),L=kn(M);if(!(L!=null&&L.success))throw new Error((L==null?void 0:L.error)||"Duplicate prune failed");const O=L.result||{},R=Array.isArray(O.prunedSessionIds)?O.prunedSessionIds.length:0,C=typeof O.duplicateGroupCount=="number"?O.duplicateGroupCount:0;ct.showToast(`Pruned ${R} duplicate runtime(s) across ${C} group(s)`,"success"),await d()}catch(M){const L=M instanceof Error?M.message:"Duplicate prune failed";ct.showToast(L,"warning"),a(L)}finally{c(M=>M==="session_host_prune_duplicate_sessions"?null:M)}}},[e,d,r]),h=o.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((I,M)=>(M.lastActivityAt||0)-(I.lastActivityAt||0)),[u==null?void 0:u.sessions]),w=o.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:uc(h),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,h]),_=w.liveRuntimes,y=w.recoverySnapshots,j=w.inactiveRecords,k=o.useMemo(()=>zf(_),[_]),g=o.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),x=o.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(I=>I.level==="warn"||I.level==="error")||null,[u==null?void 0:u.recentLogs]),$=(I,M)=>{var B;const L=i===`session_host_resume_session:${I.sessionId}`,O=i===`session_host_restart_session:${I.sessionId}`,R=i===`session_host_stop_session:${I.sessionId}`,C=ya(I.meta),U=T.get(I.sessionId),G=I.attachedClients.length===1?"1 client":`${I.attachedClients.length} clients`,A=M==="recovery"?"Recover":"Resume",D=mc(M);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:I.displayName||(U==null?void 0:U.cliName)||I.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Ff(I.lifecycle)}`,children:I.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:I.workspaceLabel||(U==null?void 0:U.runtimeWorkspaceLabel)||I.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:I.runtimeKey}),I.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",I.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((B=I.writeOwner)==null?void 0:B.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Uf(I.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(qn,{size:11})," ",G]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",To(I.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:[M==="recovery"&&(I.lifecycle==="interrupted"||I.lifecycle==="failed"||I.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{b("session_host_resume_session",I)},children:L?`${A}ing…`:A}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{b("session_host_restart_session",I)},children:O?"Restarting…":"Restart"}),M==="live"&&(I.lifecycle==="running"||I.lifecycle==="starting"||I.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",I)},children:R?"Stopping…":"Stop"})]})]})},I.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(Ot,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:yu()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[k>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{N()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${k})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${S.toneClass}`,children:S.label}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{d()},disabled:f||l,children:[t.jsx(_s,{size:13}),f||l?"Refreshing…":"Refresh"]})]})]}),n&&!u&&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(ls,{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})]})]})}),u&&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:u.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:y.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:u.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:To(u.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Sn(u.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(ls,{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:[Sn(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(Hr,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:js("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(I=>$(I,"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(Ot,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:js("recovery")}),y.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:y.map(I=>$(I,"recovery"))})]}),j.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:js("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:j.map(I=>$(I,"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"}),g.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:g.map(I=>{var L;const M=h.find(O=>O.sessionId===I.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:(M==null?void 0:M.displayName)||((L=T.get(I.sessionId))==null?void 0:L.cliName)||I.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[I.action,I.lifecycle?` · ${I.lifecycle}`:"",I.detail?` · ${I.detail}`:"",I.error?` · ${I.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${I.success===!1?"text-red-300":"text-text-secondary"}`,children:Sn(I.timestamp)})]},`${I.sessionId}:${I.timestamp}:${I.action}`)})})]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",t.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),n?t.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function Gf({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 Nn({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 Cn({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 qf({machineEntry:e,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),m=r.slice(0,4),u=zs(e,"0.8.69");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(Nn,{icon:t.jsx(Ht,{size:13}),children:"Current Chats"}),t.jsx(Cn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(f=>{const v=Kn(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)}),v>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Fr(v)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ms(f)})]},f.tabKey)})})})]}),m.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Nn,{icon:t.jsx(zo,{size:13}),children:"Recent Launches"}),t.jsx(Cn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:m.map(f=>{const{metaText:v,updatedLabel:S}=Xi(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}),S&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:S})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:v})]},f.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Nn,{icon:t.jsx(ls,{size:13}),children:"Daemon Update"}),t.jsx(Cn,{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:u?"Daemon update required":"Version mismatch detected"}),t.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:u?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),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(_s,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Yf(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Xf(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const Qf={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 wr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Jf(e){const s=e instanceof Error?e.message:String(e||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function In({category:e,machine:s,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:m,initialWorkspacePath:p}){const u=Ls(),{handleLaunchIde:f,handleStopCli:v,handleRestartIde:S,handleStopIde:T,handleDetectIdes:d,launchingIde:b,launchingAgentType:N,addLog:h}=c,[w,_]=o.useState(null),y=o.useCallback(P=>{P&&u(Yf(P))},[u]),j=Qf[e],k=e==="ide",g=e==="acp",x=o.useMemo(()=>n.filter(P=>P.category===e&&(e==="ide"||P.installed!==!1)),[e,n]),$=o.useMemo(()=>new Map(x.map(P=>[P.type,P.displayName||P.type])),[x]),[I,M]=o.useState(""),[L,O]=o.useState(""),[R,C]=o.useState([]),[U,G]=o.useState(""),[A,D]=o.useState(""),[B,W]=o.useState([]),[X,xe]=o.useState(!1),[Re,ie]=o.useState(""),[Ie,te]=o.useState(!1),[ce,oe]=o.useState(()=>gt()),[ye,ae]=o.useState(null),[F,be]=o.useState(p?"__custom__":m||s.defaultWorkspaceId||""),[se,pe]=o.useState(p||""),[J,le]=o.useState([]),[ne,ge]=o.useState(!1),[ue,E]=o.useState(""),[ve,he]=o.useState([]),[Se,Q]=o.useState(!1),[Ne,Ue]=o.useState(""),Ee=o.useRef(null),[Ve,Xe]=o.useState(null),Qe=o.useRef("__home__"),[ft,Ge]=o.useState("__home__"),[bt,dt]=o.useState(!1),ut=o.useRef(0),ht=J.filter(P=>!a.some(Y=>Y.type===P&&jt(Y.status)!=="stopped")),ot=o.useRef({});o.useEffect(()=>{s.defaultWorkspaceId&&!F&&be(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),o.useEffect(()=>{if(p){be("__custom__"),pe(p);return}m&&(be(m),pe(""))},[m,p]),o.useEffect(()=>{k||I&&(x.some(P=>P.type===I)||(M(""),D("")))},[x,k,I]);const de=(()=>{if(F==="__custom__")return se.trim();if(!F)return"";const P=(s.workspaces||[]).find(Y=>Y.id===F);return(P==null?void 0:P.path)||""})(),ze=o.useCallback(P=>{const Y=ot.current[P];Y&&(clearTimeout(Y),delete ot.current[P]),le(re=>re.includes(P)?re.filter(De=>De!==P):re)},[]),Je=o.useRef(new Set),tt=o.useCallback(async P=>{if(l){Q(!0),Ue("");try{const Y=await Xr(l,r,P);E(Y.path),pe(Y.path),he(Y.directories)}catch(Y){Ue(Y instanceof Error?Y.message:"Could not load folder")}finally{Q(!1)}}},[r,l]),xt=o.useCallback(()=>{if(!l)return;be("__custom__"),ge(!0);const P=a.map(re=>re.workspace),Y=Yr(s.platform,qr(se.trim(),de,p,P,s.defaultWorkspacePath,(s.workspaces||[]).map(re=>re.path)));tt(Y)},[se,p,tt,s.defaultWorkspacePath,s.platform,s.workspaces,a,de,l]),yt=o.useCallback(P=>{const Y=String(P.workspace||"").trim();if(!Y)return;const re=(s.workspaces||[]).find(De=>wr(De.path)===wr(Y));if(re){be(re.id),pe("");return}be("__custom__"),pe(Y)},[s.workspaces]),_t=o.useCallback(P=>{const Y=String(P.workspace||"").trim();if(!Y)return{workspaceId:null,workspacePath:"",useHome:!0};const re=(s.workspaces||[]).find(De=>wr(De.path)===wr(Y));return re?{workspaceId:re.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:Y,useHome:!1}},[s.workspaces]),St=o.useCallback(async P=>{if(!l||!P||e!=="cli"){W([]),xe(!1),ie("");return}const Y=ut.current+1;ut.current=Y,xe(!0),ie("");try{const re=await l(r,"list_saved_sessions",{providerType:P,kind:"cli",limit:30});if(ut.current!==Y)return;const De=(re==null?void 0:re.result)??re;W(Array.isArray(De==null?void 0:De.sessions)?De.sessions:[])}catch(re){if(ut.current!==Y)return;W([]),ie(re instanceof Error?re.message:"Could not load saved sessions")}finally{ut.current===Y&&xe(!1)}},[e,r,l]),Tt=o.useMemo(()=>{if(e!=="cli"||!I)return null;const P=$.get(I)||I;return{routeId:r,daemonId:r,providerSessionId:A||void 0,transport:"pty",mode:"chat",agentName:P,agentType:I,status:"idle",title:P,messages:[],ideType:I,workspaceName:de,displayPrimary:P,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${I}`}},[e,r,$,de,A,I]),q=o.useCallback(P=>{if(e==="ide"||!P){C([]);return}C(lc(r,P))},[e,r]);o.useEffect(()=>{if(D(""),q(I),e!=="cli"||!I){W([]),ie(""),xe(!1);return}St(I)},[e,q,St,I]);const Be=o.useMemo(()=>B.find(P=>P.providerSessionId===A)||null,[B,A]);o.useEffect(()=>{if(!A)return;const P=B.find(Y=>Y.providerSessionId===A);P!=null&&P.canResume||D("")},[B,A]);const Pe=o.useCallback((P,Y)=>{Ee.current=Y,Qe.current=P.selectedWorkspaceKey||"__home__",Ge(P.selectedWorkspaceKey||"__home__"),Xe(P)},[]),K=o.useCallback(()=>{Ee.current&&(dt(!0),Ee.current().finally(()=>{Ee.current=null,dt(!1),Xe(null)}))},[]),H=o.useCallback(P=>{if(!P)return;le(re=>re.includes(P)?re:[...re,P]);const Y=ot.current[P];Y&&clearTimeout(Y),ot.current[P]=setTimeout(()=>{le(re=>re.includes(P)?re.filter(De=>De!==P):re),delete ot.current[P]},2e4)},[]);o.useEffect(()=>{for(const Y of a)jt(Y.status)!=="stopped"&&(J.includes(Y.type)&&!Je.current.has(Y.type)&&(Je.current.add(Y.type),h("info",`${$.get(Y.type)||Y.type} launched`,!0)),ze(Y.type));const P=new Set(a.filter(Y=>jt(Y.status)!=="stopped").map(Y=>Y.type));Je.current.forEach(Y=>{!J.includes(Y)&&!P.has(Y)&&Je.current.delete(Y)})},[h,ze,a,J,$]),o.useEffect(()=>()=>{Object.values(ot.current).forEach(clearTimeout),ot.current={}},[]);const[z,V]=o.useState({}),[ee,je]=o.useState(null);o.useEffect(()=>{if(!k||!r||!l)return;(async()=>{try{const Y=await l(r,"get_ide_extensions",{}),re=(Y==null?void 0:Y.result)||Y;re!=null&&re.success&&(re!=null&&re.ideExtensions)&&V(re.ideExtensions)}catch{}})()},[k,r,l]);const Ae=P=>k?at(P.type):e==="cli"?P.cliName:P.acpName,Ce=k?s.detectedIdes||[]:[],We=o.useCallback(async P=>{const Y=(P==null?void 0:P.type)||I,re=(P==null?void 0:P.workspacePath)??de;if(k){await f(Y,re?{workspace:re}:void 0)&&H(Y);return}const De=await c.runLaunchCliCore({cliType:Y,dir:P!=null&&P.workspaceId?void 0:re||void 0,workspaceId:(P==null?void 0:P.workspaceId)||void 0,useHome:(P==null?void 0:P.useHome)||!(P!=null&&P.workspaceId)&&!re,argsStr:(P==null?void 0:P.argsStr)??(L||void 0),model:(P==null?void 0:P.model)??(g&&U||void 0),resumeSessionId:(P==null?void 0:P.resumeSessionId)||!g&&e==="cli"&&Y===I&&A||void 0});if(De.success||De.pending){const Me=(P==null?void 0:P.argsStr)??L;!k&&(Me!=null&&Me.trim())&&(dc(r,Y,Me),q(Y)),H(Y),De.success&&De.sessionId&&y(De.sessionId)}},[c,f,g,k,L,U,q,H,r,y,de,A,I]),Oe=vi(k?"ide":g?"acp":"cli",!k&&!g&&!!A),Ze=wi(k?"ide":g?"acp":"cli",!k&&!g&&!!A),Le=()=>{var Me;const P=k?at(I):$.get(I)||I,Y=!k&&!g&&!!A,{options:re,selectedKey:De}=is({machine:s,currentWorkspaceId:F&&F!=="__custom__"?F:null,currentWorkspacePath:de});Pe({title:Y?ia(P):ss("start-fresh",P),description:Y?ca():rs("start-fresh"),confirmLabel:Oe,busyLabel:Ze,workspaceOptions:re,selectedWorkspaceKey:De,details:[{label:"Mode",value:j.label},{label:"Provider",value:P},...!k&&e==="cli"&&A?[{label:"Resume",value:((Me=B.find($e=>$e.providerSessionId===A))==null?void 0:Me.title)||A}]:[],...!k&&L.trim()?[{label:"Arguments",value:L.trim()}]:[],...g&&U.trim()?[{label:"Model",value:U.trim()}]:[]]},async()=>{const $e=re.find(we=>we.key===Qe.current);$e!=null&&$e.workspaceId?(be($e.workspaceId),pe("")):$e!=null&&$e.workspacePath?(be("__custom__"),pe($e.workspacePath)):(be(""),pe("")),await We({workspaceId:($e==null?void 0:$e.workspaceId)??null,workspacePath:($e==null?void 0:$e.workspacePath)??"",useHome:!($e!=null&&$e.workspaceId)&&!($e!=null&&$e.workspacePath)})})},Z=P=>{k?T(P):v(P.type,P.workspace,P.id)},Te=o.useCallback(async(P,Y,re=!1)=>{if(P.mode===Y){re&&P.sessionId&&y(P.sessionId);return}if(!l||!P.sessionId){re&&P.sessionId&&y(P.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:P.sessionId,cliType:P.type,mode:Y}),re&&y(P.sessionId)}catch(De){Jf(De)?console.warn("Skipped CLI view mode switch:",De instanceof Error?De.message:String(De)):console.error("Failed to switch CLI view mode:",De)}},[r,y,l]),Ke=t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:F,onChange:P=>{const Y=P.target.value;if(be(Y),Y==="__custom__"&&l){xt();return}Y!=="__custom__"&&pe("")},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(P=>t.jsxs("option",{value:P.id,children:[P.id===s.defaultWorkspaceId?"⭐ ":"",Vr(P.path,P.label)]},P.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…"})]})}),F==="__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:xt,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:se,onChange:P=>pe(P.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:F==="__custom__"?de?t.jsx("span",{className:"font-mono truncate block",title:de,children:de}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":de?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:F===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:de,children:de})]}):"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 ${j.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 ",j.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:k?Ce.length>0?Ce.map(P=>{const Y=a.find(we=>(we.type||"").toLowerCase()===(P.type||"").toLowerCase()&&jt(we.status)!=="stopped"),re=P.running||!!Y,De=!!Y&&Y.cdpConnected,Me=J.includes(P.type||P.id||""),$e=I===(P.type||"");return t.jsxs("button",{onClick:()=>{if(De&&Y){const we=Y.sessionId;we?u(`/dashboard?activeTab=${encodeURIComponent(we)}`,{state:{openRemoteForTabKey:we}}):u("/dashboard",{state:{openRemoteForTabKey:Y.id}});return}Me||M(we=>we===(P.type||"")?"":P.type||"")},disabled:!!b||Me,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${De?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":$e?"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!==P.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(P.type)}),re&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${De?"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:P.name||at(P.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${De?"text-green-400":Me?"text-orange-400":$e?"text-accent-primary":"text-text-muted"}`,children:De?"Open Session":Me?"Starting...":$e?"Configure":"Select"})]})]},P.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(ol,{size:14})," Scan System"]})]}):x.length>0?x.map(P=>{const Y=I===P.type,re=J.includes(P.type),Me=!!a.find($e=>$e.type===P.type&&jt($e.status)!=="stopped");return t.jsxs("button",{onClick:()=>M($e=>$e===P.type?"":P.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Y?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:P.icon}),Me&&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:P.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${re?"text-orange-400":Y?"text-accent-primary":"text-text-muted"}`,children:re?"Starting...":Y?"Configure":"Select"})]})]},P.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."})]})}),I&&(k?Ce.find(P=>P.type===I):x.find(P=>P.type===I))&&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:k?at(I):$.get(I)||I})]}),Ke,!k&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!g&&e==="cli"&&t.jsx(pc,{busy:!!N||!!b||J.includes(I),savedSessionsLoading:X,savedSessionsError:Re,selectedSession:Be,onRefresh:()=>void St(I),onOpenHistory:()=>{I&&(te(!0),St(I))},onClearSelection:()=>D("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[g&&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:U,onChange:P=>G(P.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:L,onChange:P=>O(P.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"}),R.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:R.map(P=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>O(P),title:P,children:P},P))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:Le,disabled:!!N||!!b||J.includes(I),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:N===I||b===I?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+J.filter(P=>!a.some(Y=>Y.type===P&&jt(Y.status)!=="stopped")).length,")"]}),a.length===0&&ht.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 ",j.plural," running"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[ht.map(P=>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(P)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:k?at(P):$.get(P)||P}),t.jsx("div",{className:"text-[11px] text-text-muted",children:N===P?"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:${P}`)),a.map(P=>{const Y=k?P:null,re=!k&&!g?P:null,De=jt(P.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(P.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Ae(P),(Y==null?void 0:Y.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",Y.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[t.jsx("span",{children:P.workspace||"—"}),(re==null?void 0:re.mode)&&t.jsx("span",{className:re.mode==="chat"?"text-violet-400":"text-text-secondary",children:re.mode==="chat"?"Chat view":"Terminal view"})]}),re&&(re.runtimeKey||re.runtimeWriteOwner)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[re.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 ",re.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 Me;(Me=navigator.clipboard)==null||Me.writeText(`adhdev attach ${re.runtimeKey}`),_(re.runtimeKey||null),window.setTimeout(()=>{_($e=>$e===re.runtimeKey?null:$e)},1200)},children:w===re.runtimeKey?"Copied":"Copy"})]}),re.runtimeWriteOwner&&t.jsx("span",{style:{color:re.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:re.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Xf(re.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 ${De==="stopped"?"bg-red-500/[0.08] text-red-500":De==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:De}),k&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const Me=P.sessionId;if(Me){u(`/dashboard?activeTab=${encodeURIComponent(Me)}`,{state:{openRemoteForTabKey:Me}});return}u("/dashboard",{state:{openRemoteForTabKey:P.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(It,{size:13})}),t.jsx("button",{onClick:()=>{const Me=P.workspace||"",{options:$e,selectedKey:we}=is({machine:s,currentWorkspacePath:Me});Pe({title:ss("restart-ide",at(P.type)),description:rs("restart-ide"),confirmLabel:Ts("restart-ide"),busyLabel:Ms("restart-ide"),workspaceOptions:$e,selectedWorkspaceKey:we,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:at(P.type)}]},async()=>{const st=$e.find(Ft=>Ft.key===Qe.current),it=(st==null?void 0:st.workspacePath)??"";if(it&&it!==Me){await We({type:P.type,workspacePath:it});return}await S(P)})},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(_s,{size:14})})]}),g&&t.jsx("button",{onClick:()=>{const Me=P.sessionId;Me&&y(Me)},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:!P.sessionId,children:t.jsx(Ht,{size:14})}),re&&De!=="stopped"&&t.jsxs(t.Fragment,{children:[re.mode&&t.jsx(na,{mode:re.mode,onChange:Me=>void Te(re,Me,!1),compact:!0}),t.jsx("button",{onClick:()=>{const Me=P.sessionId;Me&&y(Me)},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:!P.sessionId,children:re.mode==="chat"?t.jsx(Ht,{size:14}):t.jsx(It,{size:13})})]}),De==="stopped"?t.jsx("button",{onClick:()=>{const Me=P.workspace||"",$e=k?at(P.type):Ae(P),{options:we,selectedKey:st}=is({machine:s,currentWorkspacePath:Me});Pe({title:ss("restart-stopped",$e),description:rs("restart-stopped"),confirmLabel:Ts("restart-stopped"),busyLabel:Ms("restart-stopped"),workspaceOptions:we,selectedWorkspaceKey:st,details:[{label:"Mode",value:j.label},{label:"Provider",value:$e}]},async()=>{const it=we.find(Ft=>Ft.key===Qe.current);await We({type:P.type,workspaceId:(it==null?void 0:it.workspaceId)??null,workspacePath:(it==null?void 0:it.workspacePath)??"",useHome:!(it!=null&&it.workspaceId)&&!(it!=null&&it.workspacePath)})})},disabled:J.includes(P.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:J.includes(P.type)?"⏳":t.jsx(Xn,{size:14})}):t.jsx("button",{onClick:()=>Z(P),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(kt,{size:14})})]})]}),Y&&Y.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:Y.aiAgents.map(Me=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Jo(Me.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Me.name," · ",jt(Me.status)]},Me.id))}),Y&&(z[Y.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:(z[Y.type]||[]).map(Me=>t.jsxs("button",{disabled:ee===`${Y.type}.${Me.type}`,onClick:async()=>{const $e=`${Y.type}.${Me.type}`;je($e);try{await l(r,"set_ide_extension",{ideType:Y.type,extensionType:Me.type,enabled:!Me.enabled}),V(we=>({...we,[Y.type]:(we[Y.type]||[]).map(st=>st.type===Me.type?{...st,enabled:!st.enabled}:st)}))}catch(we){console.error("Extension toggle failed:",we)}finally{je(null)}},className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-medium border transition-colors duration-150 cursor-pointer ${Me.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 ${Me.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Me.name,t.jsx("span",{className:"text-[9px] font-normal",children:Me.enabled?"ON":"OFF"})]},Me.type))})]})]},P.id)})]}),ne&&l&&t.jsx(Qr,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:ue,directories:ve,busy:Se,error:Ne,confirmLabel:"Use this folder",onClose:()=>ge(!1),onNavigate:P=>{tt(P)},onConfirm:P=>{pe(P),be("__custom__"),ge(!1)}}),Ve&&t.jsx(ba,{title:Ve.title,description:Ve.description,details:Ve.details,workspaceOptions:Ve.workspaceOptions,selectedWorkspaceKey:ft,onWorkspaceChange:P=>{Qe.current=P,Ge(P)},confirmLabel:Ve.confirmLabel,busyLabel:Ve.busyLabel,busy:bt,onConfirm:K,onCancel:()=>{Ee.current=null,Xe(null)}}),Ie&&Tt&&t.jsx(la,{activeConv:Tt,ides:[],isCreatingChat:!1,isRefreshingHistory:X,savedSessions:B,isSavedSessionsLoading:X,isResumingSavedSessionId:ye,savedHistoryFilters:ce,onSavedHistoryFiltersChange:oe,onClose:()=>te(!1),onNewChat:()=>{D(""),te(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{St(I)},onResumeSavedSession:P=>{if(!P.canResume||ye)return;const Y=_t(P);D(P.providerSessionId),yt(P),ae(P.providerSessionId),te(!1),We({type:P.providerType,workspaceId:Y.workspaceId,workspacePath:Y.workspacePath,useHome:Y.useHome,resumeSessionId:P.providerSessionId}).finally(()=>{ae(re=>re===P.providerSessionId?null:re)})}})]})}const Mo=[{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 Zf({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:m="ide",initialWorkspaceId:p,initialWorkspacePath:u,sendDaemonCommand:f}){var d;const[v,S]=o.useState(m);o.useEffect(()=>{S(m)},[m]);const T=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:Mo.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 ${v===b.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>S(b.id),children:[t.jsx("span",{children:b.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${v===b.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:T[b.id]})]},b.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(d=Mo.find(b=>b.id===v))==null?void 0:d.helper})]}),v==="ide"&&t.jsx(In,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:u}),v==="cli"&&t.jsx(In,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:u}),v==="acp"&&t.jsx(In,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:u})]})}function eh({onNicknameSynced:e}={}){var F,be,se,pe,J,le,ne,ge,ue;const{id:s}=Hc(),r=Ls(),n=Vn(),{sendCommand:a}=At(),i=tr(),c=pi(),l=c.ides||[],m=c.initialLoaded??!0,p=l.find(E=>E.id===s&&E.type==="adhdev-daemon"),u=l.some(E=>E.type==="adhdev-daemon"),[f,v]=o.useState("workspace"),[S,T]=o.useState("ide"),d=o.useRef(null),[b,N]=o.useState(null),h=o.useRef("__home__"),[w,_]=o.useState("__home__"),[y,j]=o.useState(!1),k=o.useRef(null);o.useEffect(()=>{!s||!p||!(!p.workspaces||!p.availableProviders||!p.detectedIdes||!p.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,p,s]),dm(s&&f==="overview"?[s]:[],{enabled:f==="overview",intervalMs:15e3});const g=()=>{if(u){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},x=Mf({machineId:s,registeredMachineId:(p==null?void 0:p.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:k});o.useEffect(()=>ct.onToast(ve=>{c.setToasts(Se=>{if(Se.some(Ue=>Ue.message===ve.message&&ve.timestamp-Ue.timestamp<3e3))return Se;const Ne={id:ve.id,message:ve.message,type:ve.type,timestamp:ve.timestamp,targetKey:ve.targetKey,actions:ve.actions};return[...Se.slice(-4),Ne]});const he=ve.duration||5e3;setTimeout(()=>c.setToasts(Se=>Se.filter(Q=>Q.id!==ve.id)),he)}),[c]);const $=(p==null?void 0:p.availableProviders)||[],I={};for(const E of $)I[E.type]=E.icon;const M=E=>I[E]||"",L=p?{id:p.id,hostname:Zo(p,{fallbackId:p.id}),platform:((F=p.machine)==null?void 0:F.platform)||"unknown",arch:((be=p.machine)==null?void 0:be.arch)||"",cpus:((se=p.machine)==null?void 0:se.cpus)||0,totalMem:((pe=p.machine)==null?void 0:pe.totalMem)||0,freeMem:(J=p.machine)==null?void 0:J.freeMem,availableMem:(le=p.machine)==null?void 0:le.availableMem,loadavg:(ne=p.machine)==null?void 0:ne.loadavg,uptime:(ge=p.machine)==null?void 0:ge.uptime,release:((ue=p.machine)==null?void 0:ue.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,O=l.filter(E=>E.daemonId===s&&E.type!=="adhdev-daemon").filter(E=>!Xs(E)&&!vs(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,version:E.version||"",instanceId:E.instanceId||"",status:E.status,workspace:E.workspace||null,terminals:E.terminals||0,aiAgents:Ql(E.aiAgents||(E.agents||[]).map(ve=>({id:ve.name,name:ve.name,status:ve.status,version:ve.version}))),activeChat:E.activeChat||null,chats:E.chats||[],childSessions:E.childSessions||[],cdpConnected:E.cdpConnected||!1,daemonId:s})),R=l.filter(E=>E.daemonId===s&&Xs(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,cliName:E.cliName||E.type,status:E.status,workspace:E.workspace||"",activeChat:E.activeChat||null,providerSessionId:E.providerSessionId,mode:E.mode,runtimeKey:E.runtimeKey,runtimeDisplayName:E.runtimeDisplayName,runtimeWorkspaceLabel:E.runtimeWorkspaceLabel,runtimeWriteOwner:E.runtimeWriteOwner||null,runtimeAttachedClients:E.runtimeAttachedClients||[],daemonId:s})),C=l.filter(E=>E.daemonId===s&&vs(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,acpName:E.cliName||E.type,status:E.status,workspace:E.workspace||"",activeChat:E.activeChat||null,providerSessionId:E.providerSessionId,daemonId:s})),U=p?Ct(p,{fallbackId:s}):"",G="workspace",A=n.state,D=A==null?void 0:A.initialMachineTab,B=A==null?void 0:A.initialWorkspaceCategory,W=A==null?void 0:A.initialWorkspaceId,X=A==null?void 0:A.initialWorkspacePath,xe=D==="ides"||D==="clis"||D==="acps"?"workspace":D||G,Re=D==="ides"?"ide":D==="clis"?"cli":D==="acps"?"acp":B,ie=[...O.map(E=>{var ve,he,Se,Q,Ne;return{id:`ide:${E.type}:${E.workspace||""}`,label:((ve=E.activeChat)==null?void 0:ve.title)||E.type,kind:"ide",providerType:E.type,subtitle:E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:((Ne=(Q=(Se=(he=E.activeChat)==null?void 0:he.messages)==null?void 0:Se.at)==null?void 0:Q.call(Se,-1))==null?void 0:Ne.timestamp)||0}}),...R.map(E=>{var ve,he,Se,Q,Ne;return{id:`cli:${E.type}:${E.workspace||""}`,label:((ve=E.activeChat)==null?void 0:ve.title)||E.cliName,kind:"cli",providerType:E.type,providerSessionId:E.providerSessionId,subtitle:E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:((Ne=(Q=(Se=(he=E.activeChat)==null?void 0:he.messages)==null?void 0:Se.at)==null?void 0:Q.call(Se,-1))==null?void 0:Ne.timestamp)||0}}),...C.map(E=>{var ve,he,Se,Q,Ne;return{id:`acp:${E.type}:${E.workspace||""}`,label:((ve=E.activeChat)==null?void 0:ve.title)||E.acpName,kind:"acp",providerType:E.type,providerSessionId:E.providerSessionId,subtitle:ds(E.summaryMetadata)||E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:((Ne=(Q=(Se=(he=E.activeChat)==null?void 0:he.messages)==null?void 0:Se.at)==null?void 0:Q.call(Se,-1))==null?void 0:Ne.timestamp)||0}})].sort((E,ve)=>(ve.lastLaunchedAt||0)-(E.lastLaunchedAt||0)),Ie=((p==null?void 0:p.recentLaunches)||[]).length>0?((p==null?void 0:p.recentLaunches)||[]).map(E=>({id:E.id,label:E.title||E.providerName||E.providerType,kind:E.kind,providerType:E.providerType,providerSessionId:E.providerSessionId,subtitle:ds(E.summaryMetadata)||E.workspace||void 0,workspace:E.workspace,summaryMetadata:E.summaryMetadata,lastLaunchedAt:E.lastLaunchedAt})):ie,te=o.useMemo(()=>{var ve;const E=((ve=c.connectionStates)==null?void 0:ve[s||""])||void 0;return l.filter(he=>he.daemonId===s&&he.type!=="adhdev-daemon").flatMap(he=>da(he,{},{connectionStates:s&&E?{[s]:E}:void 0,defaultConnectionState:E})).filter(he=>!(he.transport==="pty"&&he.mode==="terminal")).sort((he,Se)=>Kn(Se)-Kn(he))},[l,c.connectionStates,s]),ce=o.useCallback(E=>{const ve=E.sessionId||E.tabKey;ve&&r(`/dashboard?activeTab=${encodeURIComponent(ve)}`)},[r]),oe=o.useCallback(()=>{d.current&&(j(!0),d.current().finally(()=>{d.current=null,j(!1),N(null)}))},[]),ye=o.useCallback(E=>{if(!L)return;const{options:ve,selectedKey:he}=is({machine:L,currentWorkspacePath:E.workspace}),Se=async()=>{T(E.kind),v("workspace")};d.current=async()=>{const Q=ve.find(Ee=>Ee.key===h.current),Ne=(Q==null?void 0:Q.workspacePath)??null,Ue=(Q==null?void 0:Q.workspaceId)??null;if(E.kind==="ide"&&E.providerType){await x.handleLaunchIde(E.providerType,Ne?{workspace:Ne}:void 0);return}if((E.kind==="cli"||E.kind==="acp")&&E.providerType){await x.runLaunchCliCore({cliType:E.providerType,dir:Ue?void 0:Ne||"",workspaceId:Ue||void 0,model:E.kind==="acp"&&ti(E.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:E.providerSessionId});return}await Se()},h.current=he,_(he),N({title:E.kind==="ide"?ss("restart-ide",E.label):E.providerSessionId?ia(E.label):ss("start-fresh",E.label),description:E.kind==="ide"?rs("restart-ide"):E.providerSessionId?ca():rs("start-fresh"),confirmLabel:E.kind==="ide"?Ts("restart-ide"):E.providerSessionId?Dr(!0):Ts("start-fresh"),busyLabel:E.kind==="ide"?Ms("restart-ide"):E.providerSessionId?aa(!0):Ms("start-fresh"),workspaceOptions:ve,details:[{label:"Mode",value:E.kind.toUpperCase()},...E.providerType?[{label:"Provider",value:E.providerType}]:[]]})},[x,L]);if(o.useEffect(()=>{v(xe)},[G,xe,s]),o.useEffect(()=>{Re&&T(Re)},[Re,s]),!L)return m?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:g,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 ae=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(It,{size:14})," Workspace"]}),count:O.length+R.length+C.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ot,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Or,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(il,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(nl,{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:g,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),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:E=>x.setNicknameInput(E.target.value),onKeyDown:E=>{E.key==="Enter"&&x.handleSaveNickname(),E.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(L.machineNickname||"")},title:"Click to set nickname",children:U}),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:[L.platform," · ",L.arch]}),t.jsxs("span",{children:[L.cpus," cores"]}),(p==null?void 0:p.version)&&t.jsxs("span",{children:["v",p.version]}),L.p2p.available&&t.jsxs("span",{children:["P2P ",L.p2p.state==="connected"?"connected":L.p2p.state]}),L.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:L.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ae.map(E=>t.jsxs("button",{onClick:()=>v(E.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${f===E.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[E.label,E.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${f===E.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:E.count})]},E.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(qf,{machineEntry:p,providers:$,recentLaunches:Ie,currentConversations:te,onUpgradeDaemon:async()=>{try{await a(s,"daemon_upgrade",{})}catch{}},onOpenRecent:ye,onOpenConversation:ce}),t.jsx(Zf,{machine:L,machineId:s,providers:$,ideSessions:O,cliSessions:R,acpSessions:C,actions:x,getIcon:M,initialCategory:S,initialWorkspaceId:W,initialWorkspacePath:X,sendDaemonCommand:a})]}),f==="providers"&&t.jsx(Bf,{machineId:s,providers:$,sendDaemonCommand:a}),f==="overview"&&t.jsx(Lf,{machineId:s,machine:L,ideSessions:O,cliSessions:R,acpSessions:C,actions:x,sendDaemonCommand:a}),f==="session-host"&&t.jsx(Vf,{machineId:s,cliSessions:R,sendDaemonCommand:a}),f==="logs"&&t.jsx(Hf,{machineId:s,sendDaemonCommand:a})]})})}),x.launchPick&&L&&t.jsx(Gf,{machine:L,launchPick:x.launchPick,actions:x}),b&&t.jsx(ba,{title:b.title,description:b.description,details:b.details,workspaceOptions:b.workspaceOptions,selectedWorkspaceKey:w,onWorkspaceChange:E=>{h.current=E,_(E)},confirmLabel:b.confirmLabel,busyLabel:b.busyLabel,busy:y,onConfirm:oe,onCancel:()=>{d.current=null,N(null)}}),t.jsx(ji,{toasts:c.toasts||[],onDismiss:E=>c.setToasts(ve=>ve.filter(he=>he.id!==E)),onClickToast:E=>{E.targetKey&&r(`/dashboard?activeTab=${encodeURIComponent(E.targetKey)}`)}}),t.jsx("style",{children:`
|
|
68
68
|
@keyframes toast-in {
|
|
69
69
|
from { opacity: 0; transform: translateX(40px); }
|
|
70
70
|
to { opacity: 1; transform: translateX(0); }
|
|
71
71
|
}
|
|
72
|
-
`})]})}class th{constructor(){qe(this,"adapters",new Map);qe(this,"states",new Map);qe(this,"runtimeListeners",new Map);qe(this,"screenshotCallbacks",new Map);qe(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}sendPtyResize(s,r,n,a){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 fetch(`/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 Kt=new th;function sh(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=new URLSearchParams(window.location.search).get("token");return n?`${s}?token=${encodeURIComponent(n)}`:s}const jr=sh(),Lo=3e3,rh=3e4;let $t=null,nh=0;const Wr=new Map;let Zt=null,Gs=null;function _o(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function Os(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function ah(e){return e==="connected"?"connected":e}async function Tr(e,s,r){const n=Lu(e,r||{}),a=$t;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++nh}_${Date.now()}`;return new Promise((c,l)=>{const m=setTimeout(()=>{Wr.delete(i),l(new Error(`WS command timeout: ${s}`))},3e4);Wr.set(i,{resolve:p=>{clearTimeout(m),c(p)},reject:p=>{clearTimeout(m),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 Un(e,s){const r=$t;if(!r||r.readyState!==WebSocket.OPEN)return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class oh{constructor(s){qe(this,"daemonId");qe(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return($t==null?void 0:$t.readyState)===WebSocket.OPEN}get connectionState(){return($t==null?void 0:$t.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return Tr(this.daemonId,s,r)}async sendInput(s,r){return Tr(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,Zt&&(clearInterval(Zt),Zt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Tr(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const a=await fetch(`data:image/jpeg;base64,${n.base64}`).then(i=>i.blob());Kt.emitScreenshot(this.daemonId,a)}}catch{}};r(),Zt=setInterval(r,2e3)}stopScreenshots(s){Zt&&(clearInterval(Zt),Zt=null)}}let Lt=null;function ih(e){return(!Lt||Lt.daemonId!==e)&&(Lt=new oh(e)),Lt}function ch({children:e}){const s=o.useRef(Lr()),r=Lr();s.current=r;const{setUserName:n}=cs(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),m=o.useCallback((d,b)=>{l(d),Gs==null||Gs(d,b)},[]),p=o.useRef(null),u=o.useRef(),f=o.useRef(Lo),v=o.useRef(!0),S=o.useRef(!1),T=o.useRef("initial_connect");return o.useEffect(()=>{v.current=!0,S.current=!1;function d(){var h,w;if(!v.current||((h=p.current)==null?void 0:h.readyState)===WebSocket.OPEN||((w=p.current)==null?void 0:w.readyState)===WebSocket.CONNECTING)return;m("connecting"),console.log(`[Standalone WS] Connecting to ${jr}...`),Os("connect_attempt",{url:jr,reason:T.current,delayMs:f.current});let N;try{N=new WebSocket(jr)}catch(_){console.error("[Standalone WS] Failed to create WebSocket:",_),b();return}p.current=N,N.onopen=()=>{if(!v.current){N.close();return}m("connected"),f.current=Lo,Os("open",{url:jr,reason:T.current}),Gt.resubscribeAll({sendData:Un}),console.log("[Standalone WS] Connected")},$t=N,N.onmessage=_=>{var y,j;try{const k=JSON.parse(_.data);if((k.type==="command_result"||k.type==="error")&&k.requestId){const g=Wr.get(k.requestId);g&&(Wr.delete(k.requestId),k.type==="error"?g.reject(new Error(((y=k.data)==null?void 0:y.message)||"Command failed")):g.resolve(k.data));return}if(k.type==="session_output"){const g=k.sessionId||k.cliId||k.cliType;g&&Kt.emitSessionOutput(g,typeof k.data=="string"?k.data:"",typeof k.seq=="number"?k.seq:void 0);return}if(k.type==="runtime_snapshot"){Kt.emitRuntimeSnapshot(k.sessionId,typeof k.text=="string"?k.text:"",typeof k.seq=="number"?k.seq:0,!!k.truncated);return}if(k.type==="topic_update"){const g=k.update;g&&Gt.publish(g);return}if(k.type==="status"||k.type==="initial_state"){const g=k.data;if(!g)return;const{injectEntries:x,markLoaded:$,getIdes:I}=s.current,M=g.instanceId||"standalone",L=I().find(C=>C.id===M),O=ih(M);Kt.register(M,O),Kt.setState(M,"connected"),m("connected",M),Kt.emitStatus(M,g);const R=Pr(g,{daemonId:M,existingDaemon:L,existingEntries:I()});_o("ws_status",{type:k.type,daemonId:M,sessions:(g.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:(g.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),_o("entries",{daemonId:M,entries:R.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}))}),R.length>0&&x(R,{authoritativeDaemonIds:[M]}),$(),c.current!==M&&((j=i.current)==null||j.call(i),c.current=M,i.current=Gt.subscribe({sendData:Un},M,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${M}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const U=s.current.getIdes(),G=U.find(D=>D.id===M),A=Pr(C.status,{daemonId:M,existingDaemon:G,existingEntries:U,timestamp:C.timestamp});A.length>0&&s.current.injectEntries(A),C.userName&&a.current&&a.current(C.userName)}))}}catch(k){console.error("[Standalone WS] Parse error:",k)}},N.onclose=_=>{v.current&&(Lt==null||Lt.stopScreenshots(),Lt&&Kt.setState(Lt.daemonId,"disconnected"),m("disconnected"),p.current=null,T.current=`close:${_.code}${_.wasClean?":clean":":unclean"}`,Os("close",{code:_.code,reason:_.reason||"",wasClean:_.wasClean}),b())},N.onerror=_=>{S.current||!v.current||(T.current="error",Os("error",{message:_ instanceof Event?"event":String(_),readyState:N.readyState}),console.warn("[Standalone WS] Error, will reconnect:",_))}}function b(){if(!v.current)return;clearTimeout(u.current);const N=f.current;console.log(`[Standalone WS] Reconnecting in ${N}ms...`),Os("schedule_reconnect",{reason:T.current,delayMs:N}),u.current=setTimeout(()=>{f.current=Math.min(f.current*1.5,rh),d()},N)}return d(),()=>{var N;v.current=!1,S.current=!0,(N=i.current)==null||N.call(i),i.current=null,c.current=null,clearTimeout(u.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,$t=null),Lt&&(Lt.stopScreenshots(),Kt.unregister(Lt.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function lh({children:e}){const[s,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(Gs=(c,l)=>{r(c),l&&a(l)},()=>{Gs=null}),[]);const i=o.useMemo(()=>{const c=s==="connected",l=ah(s),m={};return n&&(m[n]=l),m.standalone=l,{wsStatus:s,isConnected:c,connectionStates:m}},[s,n]);return t.jsx(Xc,{connectionOverrides:i,children:t.jsx(ch,{children:e})})}const dh=[{id:"dashboard",path:"/dashboard",icon:t.jsx(Wo,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(Ot,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx(Or,{}),label:"Settings"}];function uh({children:e}){const s=Ls(),r=Vn(),[n,a]=o.useState(!1),[i,c]=o.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),l=u=>{s(u),a(!1)},m=()=>{c(u=>{const f=!u;try{localStorage.setItem("sidebar-collapsed",f?"1":"0")}catch{}return f})},p=u=>`nav-item${r.pathname.startsWith(u)?" 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:u=>u.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(kt,{size:16})})]}),t.jsx("nav",{className:"sidebar-nav",children:dh.map(u=>t.jsxs("div",{className:p(u.path),id:`nav-${u.id}`,onClick:()=>l(u.path),title:i?u.label:void 0,children:[t.jsx("span",{className:"nav-icon",children:u.icon}),!i&&u.label]},u.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(Oo,{})}),!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(Ho,{})}),!i&&"About"]}),!i&&t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.68"]}),t.jsx(Fu,{collapsed:i}),t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:m,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 mh=[{icon:t.jsx(Ot,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(Ht,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(Uo,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(It,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(Ys,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(Oo,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],ph=[{icon:t.jsx(dl,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(Wo,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(Ur,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(rl,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(qn,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(al,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],fh=[{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 hh(){return t.jsxs(Ai,{icon:t.jsx(Ho,{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.68"]}),children:[t.jsx(Pt,{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(Pt,{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:mh.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(Pt,{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:Ni.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Ii.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Ci.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(Pt,{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:ph.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(Pt,{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:fh.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(Ti,{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(vl,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function xh(){const{ides:e}=cs(),s=e.find(f=>f.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=At(),{userName:a}=cs(),[i,c]=o.useState(a||"");o.useEffect(()=>{a!==void 0&&c(a)},[a]);const l=f=>{const v=f.target.value.trim();s!=null&&s.id&&v!==a&&n(s.id,"set_user_name",{userName:v}).catch(console.error)},[m,p]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),u=f=>{p(f);try{localStorage.setItem("adhdev_sound",f?"1":"0")}catch{}};return t.jsxs(Ai,{icon:t.jsx(Or,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(Bu,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost."}),t.jsx(Pt,{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.68"]}),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:"WebSocket"}),t.jsx("span",{className:"font-mono text-xs",children:"ws://localhost:19222"}),t.jsx("span",{className:"text-text-muted",children:"HTTP"}),t.jsx("span",{className:"font-mono text-xs",children:"http://localhost:19280"})]})}),t.jsx(Pt,{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(f=>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 ${f.running?"bg-green-400":"bg-text-muted/30"}`}),t.jsx("span",{className:"text-sm font-medium",children:f.name})]}),t.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:f.type})]},f.type))})}),t.jsx(Pt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(qu,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),t.jsx(Pt,{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(Ju,{})]}),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(om,{})]}),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(cm,{})]})]})}),t.jsx(Pt,{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(zu,{}),t.jsx(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(yl,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:m,onChange:u})]})}),t.jsx(Pt,{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(sl,{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:f=>c(f.target.value),onBlur:l,onKeyDown:f=>{f.key==="Enter"&&f.currentTarget.blur()}})]})})})]})}Uu();nm();const bh=Bo({baseUrl:""});function Ro(){const{ides:e,initialLoaded:s}=cs();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(Mn,{to:`/machines/${r.id}`,replace:!0}):t.jsx(Mn,{to:"/dashboard",replace:!0})}function gh(){const e=o.useMemo(()=>({sendCommand:Tr,sendData:Un}),[]);return t.jsx(Uc,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(Zc,{client:bh,children:t.jsx(lh,{children:t.jsx(tl,{value:e,children:t.jsx(uh,{children:t.jsxs(Fc,{children:[t.jsx(Qt,{path:"/dashboard",element:t.jsx(Tf,{})}),t.jsx(Qt,{path:"/machine",element:t.jsx(Ro,{})}),t.jsx(Qt,{path:"/machines/:id",element:t.jsx(eh,{})}),t.jsx(Qt,{path:"/machines",element:t.jsx(Ro,{})}),t.jsx(Qt,{path:"/about",element:t.jsx(hh,{})}),t.jsx(Qt,{path:"/settings",element:t.jsx(xh,{})}),t.jsx(Qt,{path:"*",element:t.jsx(Mn,{to:"/dashboard",replace:!0})})]})})})})})})}au({connectionManager:Kt});zc(document.getElementById("root")).render(t.jsx(gh,{}));
|
|
72
|
+
`})]})}class th{constructor(){qe(this,"adapters",new Map);qe(this,"states",new Map);qe(this,"runtimeListeners",new Map);qe(this,"screenshotCallbacks",new Map);qe(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}sendPtyResize(s,r,n,a){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 fetch(`/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 Kt=new th;function sh(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=new URLSearchParams(window.location.search).get("token");return n?`${s}?token=${encodeURIComponent(n)}`:s}const jr=sh(),Lo=3e3,rh=3e4;let $t=null,nh=0;const Wr=new Map;let Zt=null,Gs=null;function _o(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function Os(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function ah(e){return e==="connected"?"connected":e}async function Tr(e,s,r){const n=Lu(e,r||{}),a=$t;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++nh}_${Date.now()}`;return new Promise((c,l)=>{const m=setTimeout(()=>{Wr.delete(i),l(new Error(`WS command timeout: ${s}`))},3e4);Wr.set(i,{resolve:p=>{clearTimeout(m),c(p)},reject:p=>{clearTimeout(m),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 Un(e,s){const r=$t;if(!r||r.readyState!==WebSocket.OPEN)return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class oh{constructor(s){qe(this,"daemonId");qe(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return($t==null?void 0:$t.readyState)===WebSocket.OPEN}get connectionState(){return($t==null?void 0:$t.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return Tr(this.daemonId,s,r)}async sendInput(s,r){return Tr(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,Zt&&(clearInterval(Zt),Zt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Tr(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const a=await fetch(`data:image/jpeg;base64,${n.base64}`).then(i=>i.blob());Kt.emitScreenshot(this.daemonId,a)}}catch{}};r(),Zt=setInterval(r,2e3)}stopScreenshots(s){Zt&&(clearInterval(Zt),Zt=null)}}let Lt=null;function ih(e){return(!Lt||Lt.daemonId!==e)&&(Lt=new oh(e)),Lt}function ch({children:e}){const s=o.useRef(Lr()),r=Lr();s.current=r;const{setUserName:n}=cs(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),m=o.useCallback((d,b)=>{l(d),Gs==null||Gs(d,b)},[]),p=o.useRef(null),u=o.useRef(),f=o.useRef(Lo),v=o.useRef(!0),S=o.useRef(!1),T=o.useRef("initial_connect");return o.useEffect(()=>{v.current=!0,S.current=!1;function d(){var h,w;if(!v.current||((h=p.current)==null?void 0:h.readyState)===WebSocket.OPEN||((w=p.current)==null?void 0:w.readyState)===WebSocket.CONNECTING)return;m("connecting"),console.log(`[Standalone WS] Connecting to ${jr}...`),Os("connect_attempt",{url:jr,reason:T.current,delayMs:f.current});let N;try{N=new WebSocket(jr)}catch(_){console.error("[Standalone WS] Failed to create WebSocket:",_),b();return}p.current=N,N.onopen=()=>{if(!v.current){N.close();return}m("connected"),f.current=Lo,Os("open",{url:jr,reason:T.current}),Gt.resubscribeAll({sendData:Un}),console.log("[Standalone WS] Connected")},$t=N,N.onmessage=_=>{var y,j;try{const k=JSON.parse(_.data);if((k.type==="command_result"||k.type==="error")&&k.requestId){const g=Wr.get(k.requestId);g&&(Wr.delete(k.requestId),k.type==="error"?g.reject(new Error(((y=k.data)==null?void 0:y.message)||"Command failed")):g.resolve(k.data));return}if(k.type==="session_output"){const g=k.sessionId||k.cliId||k.cliType;g&&Kt.emitSessionOutput(g,typeof k.data=="string"?k.data:"",typeof k.seq=="number"?k.seq:void 0);return}if(k.type==="runtime_snapshot"){Kt.emitRuntimeSnapshot(k.sessionId,typeof k.text=="string"?k.text:"",typeof k.seq=="number"?k.seq:0,!!k.truncated);return}if(k.type==="topic_update"){const g=k.update;g&&Gt.publish(g);return}if(k.type==="status"||k.type==="initial_state"){const g=k.data;if(!g)return;const{injectEntries:x,markLoaded:$,getIdes:I}=s.current,M=g.instanceId||"standalone",L=I().find(C=>C.id===M),O=ih(M);Kt.register(M,O),Kt.setState(M,"connected"),m("connected",M),Kt.emitStatus(M,g);const R=Pr(g,{daemonId:M,existingDaemon:L,existingEntries:I()});_o("ws_status",{type:k.type,daemonId:M,sessions:(g.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:(g.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),_o("entries",{daemonId:M,entries:R.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}))}),R.length>0&&x(R,{authoritativeDaemonIds:[M]}),$(),c.current!==M&&((j=i.current)==null||j.call(i),c.current=M,i.current=Gt.subscribe({sendData:Un},M,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${M}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const U=s.current.getIdes(),G=U.find(D=>D.id===M),A=Pr(C.status,{daemonId:M,existingDaemon:G,existingEntries:U,timestamp:C.timestamp});A.length>0&&s.current.injectEntries(A),C.userName&&a.current&&a.current(C.userName)}))}}catch(k){console.error("[Standalone WS] Parse error:",k)}},N.onclose=_=>{v.current&&(Lt==null||Lt.stopScreenshots(),Lt&&Kt.setState(Lt.daemonId,"disconnected"),m("disconnected"),p.current=null,T.current=`close:${_.code}${_.wasClean?":clean":":unclean"}`,Os("close",{code:_.code,reason:_.reason||"",wasClean:_.wasClean}),b())},N.onerror=_=>{S.current||!v.current||(T.current="error",Os("error",{message:_ instanceof Event?"event":String(_),readyState:N.readyState}),console.warn("[Standalone WS] Error, will reconnect:",_))}}function b(){if(!v.current)return;clearTimeout(u.current);const N=f.current;console.log(`[Standalone WS] Reconnecting in ${N}ms...`),Os("schedule_reconnect",{reason:T.current,delayMs:N}),u.current=setTimeout(()=>{f.current=Math.min(f.current*1.5,rh),d()},N)}return d(),()=>{var N;v.current=!1,S.current=!0,(N=i.current)==null||N.call(i),i.current=null,c.current=null,clearTimeout(u.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,$t=null),Lt&&(Lt.stopScreenshots(),Kt.unregister(Lt.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function lh({children:e}){const[s,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(Gs=(c,l)=>{r(c),l&&a(l)},()=>{Gs=null}),[]);const i=o.useMemo(()=>{const c=s==="connected",l=ah(s),m={};return n&&(m[n]=l),m.standalone=l,{wsStatus:s,isConnected:c,connectionStates:m}},[s,n]);return t.jsx(Xc,{connectionOverrides:i,children:t.jsx(ch,{children:e})})}const dh=[{id:"dashboard",path:"/dashboard",icon:t.jsx(Wo,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(Ot,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx(Or,{}),label:"Settings"}];function uh({children:e}){const s=Ls(),r=Vn(),[n,a]=o.useState(!1),[i,c]=o.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),l=u=>{s(u),a(!1)},m=()=>{c(u=>{const f=!u;try{localStorage.setItem("sidebar-collapsed",f?"1":"0")}catch{}return f})},p=u=>`nav-item${r.pathname.startsWith(u)?" 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:u=>u.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(kt,{size:16})})]}),t.jsx("nav",{className:"sidebar-nav",children:dh.map(u=>t.jsxs("div",{className:p(u.path),id:`nav-${u.id}`,onClick:()=>l(u.path),title:i?u.label:void 0,children:[t.jsx("span",{className:"nav-icon",children:u.icon}),!i&&u.label]},u.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(Oo,{})}),!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(Ho,{})}),!i&&"About"]}),!i&&t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.69"]}),t.jsx(Fu,{collapsed:i}),t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:m,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 mh=[{icon:t.jsx(Ot,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(Ht,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(Uo,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(It,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(Ys,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(Oo,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],ph=[{icon:t.jsx(dl,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(Wo,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(Ur,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(rl,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(qn,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(al,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],fh=[{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 hh(){return t.jsxs(Ai,{icon:t.jsx(Ho,{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.69"]}),children:[t.jsx(Pt,{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(Pt,{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:mh.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(Pt,{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:Ni.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Ii.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Ci.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(Pt,{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:ph.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(Pt,{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:fh.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(Ti,{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(vl,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function xh(){const{ides:e}=cs(),s=e.find(f=>f.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=At(),{userName:a}=cs(),[i,c]=o.useState(a||"");o.useEffect(()=>{a!==void 0&&c(a)},[a]);const l=f=>{const v=f.target.value.trim();s!=null&&s.id&&v!==a&&n(s.id,"set_user_name",{userName:v}).catch(console.error)},[m,p]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),u=f=>{p(f);try{localStorage.setItem("adhdev_sound",f?"1":"0")}catch{}};return t.jsxs(Ai,{icon:t.jsx(Or,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(Bu,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost."}),t.jsx(Pt,{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.69"]}),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:"WebSocket"}),t.jsx("span",{className:"font-mono text-xs",children:"ws://localhost:19222"}),t.jsx("span",{className:"text-text-muted",children:"HTTP"}),t.jsx("span",{className:"font-mono text-xs",children:"http://localhost:19280"})]})}),t.jsx(Pt,{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(f=>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 ${f.running?"bg-green-400":"bg-text-muted/30"}`}),t.jsx("span",{className:"text-sm font-medium",children:f.name})]}),t.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:f.type})]},f.type))})}),t.jsx(Pt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(qu,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),t.jsx(Pt,{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(Ju,{})]}),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(om,{})]}),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(cm,{})]})]})}),t.jsx(Pt,{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(zu,{}),t.jsx(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(yl,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:m,onChange:u})]})}),t.jsx(Pt,{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(sl,{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:f=>c(f.target.value),onBlur:l,onKeyDown:f=>{f.key==="Enter"&&f.currentTarget.blur()}})]})})})]})}Uu();nm();const bh=Bo({baseUrl:""});function Ro(){const{ides:e,initialLoaded:s}=cs();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(Mn,{to:`/machines/${r.id}`,replace:!0}):t.jsx(Mn,{to:"/dashboard",replace:!0})}function gh(){const e=o.useMemo(()=>({sendCommand:Tr,sendData:Un}),[]);return t.jsx(Uc,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(Zc,{client:bh,children:t.jsx(lh,{children:t.jsx(tl,{value:e,children:t.jsx(uh,{children:t.jsxs(Fc,{children:[t.jsx(Qt,{path:"/dashboard",element:t.jsx(Tf,{})}),t.jsx(Qt,{path:"/machine",element:t.jsx(Ro,{})}),t.jsx(Qt,{path:"/machines/:id",element:t.jsx(eh,{})}),t.jsx(Qt,{path:"/machines",element:t.jsx(Ro,{})}),t.jsx(Qt,{path:"/about",element:t.jsx(hh,{})}),t.jsx(Qt,{path:"/settings",element:t.jsx(xh,{})}),t.jsx(Qt,{path:"*",element:t.jsx(Mn,{to:"/dashboard",replace:!0})})]})})})})})})}au({connectionManager:Kt});zc(document.getElementById("root")).render(t.jsx(gh,{}));
|