@adhdev/daemon-standalone 0.8.78 → 0.8.79
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 nu(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0
|
|
|
29
29
|
|
|
30
30
|
`)))return}const O=(c==null?void 0:c[P.id])??d[P.id];try{const S=await w(P.invokeScript),D=br(S);if(D&&!D.ok||gr(S))throw new Error((D==null?void 0:D.error)||Vs(S)||`Could not run ${P.label}`);D&&x(P,O??!0,D)}catch(S){$(P,O);const D=S instanceof Error?S.message:`Could not run ${P.label}`;lt.showToast(D,"warning")}};return t.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1 flex-wrap text-[10px] border-t border-border-subtle bg-surface-primary font-[var(--font)]",children:[t.jsx("span",{className:"text-[9px] font-bold tracking-wide opacity-70",style:{color:p},children:a}),t.jsx("span",{className:"text-border-subtle text-[10px]",children:"│"}),N.map(P=>{const O=String(b[P.id]||""),S=fu(P,v,O),D=C===P.id,z=g===P.id,U=Rr(P,v);switch(P.type){case"select":return t.jsxs("div",{className:"relative",children:[t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all bg-[var(--surface-tertiary)] whitespace-nowrap max-w-40 overflow-hidden text-ellipsis",style:{borderColor:D?`${p}55`:"transparent",border:"1px solid",color:O?"var(--text-primary)":"var(--text-muted)"},onClick:()=>L(P),children:[P.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:P.icon}),z?"...":S||P.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),D&&U.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>_(null)}),t.jsxs("div",{className:"absolute bottom-full left-0 z-[60] bg-[var(--surface-primary)] border border-border-subtle rounded-lg mb-1 max-h-[220px] overflow-y-auto min-w-40 shadow-[0_-4px_16px_rgba(0,0,0,0.3)]",children:[t.jsx("div",{className:"px-3 py-1.5 text-[9px] font-bold text-text-muted tracking-wider border-b border-border-subtle",children:P.label.toUpperCase()}),U.map(ae=>t.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:ae.value===O?`${p}18`:"transparent",color:ae.value===O?p:"var(--text-secondary)",fontWeight:ae.value===O?600:400,borderLeft:ae.value===O?`2px solid ${p}`:"2px solid transparent"},title:ae.description||ae.label,onMouseEnter:q=>{q.currentTarget.style.background=`${p}12`},onMouseLeave:q=>{q.currentTarget.style.background=ae.value===O?`${p}18`:"transparent"},onClick:()=>T(P,ae.value),children:ae.label},ae.value))]})]})]},P.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:O?"var(--text-primary)":"var(--text-muted)"},onClick:()=>K(P),title:`Click to cycle: ${U.map(ae=>ae.label).join(" → ")}`,children:[P.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:P.icon}),S||P.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"⟳"})]},P.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:O?`${p}44`:"transparent",background:O?`${p}14`:"var(--surface-tertiary)",color:O?p:"var(--text-muted)"},onClick:()=>F(P),children:[P.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:P.icon}),P.label]},P.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:()=>M(P),children:[P.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:P.icon}),P.resultDisplay==="inline"&&O?`${P.label}: ${O}`:P.label]},P.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:O?"var(--text-primary)":"var(--text-muted)"},children:[P.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:P.icon}),O?`${P.label}: ${O}`:P.label]},P.id);default:return null}})]})}function bu({isActive:e=!0,isCliTerminal:s=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:u}){const{isVisible:p,toggleVisibility:m}=Ad(),h=Mi(l,{hostIdeType:a,providerType:i});return!e||s||h.length===0?null:t.jsxs("div",{className:"shrink-0 bg-[var(--surface-primary)]",children:[t.jsx("div",{className:`px-3 py-1.5 flex justify-end ${p?"":"border-t border-border-subtle"}`,children:t.jsxs("button",{type:"button",onClick:m,"aria-pressed":p,className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-medium transition-colors border border-border-subtle bg-[var(--surface-tertiary)] text-[var(--text-secondary)] hover:bg-[var(--surface-tertiary-hover)] hover:text-[var(--text-primary)]",title:p?"Hide controls bar":"Show controls bar",children:[p?t.jsx(ma,{size:13}):t.jsx(ua,{size:13}),t.jsx("span",{children:p?"Hide controls":"Show controls"})]})}),p&&t.jsx(xu,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:h,controlValues:u})]})}function Li({hasDraft:e,isBusy:s=!1}){return!e||s}const gu=o.memo(function({contextKey:s,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:i=null,onSend:c,isActive:l=!0}){const u=o.useRef(null),[p,m]=o.useState("");o.useEffect(()=>{m("")},[s]),o.useEffect(()=>{var y;l&&((y=u.current)==null||y.focus())},[s,l]);const h=async()=>{const y=p.trim();if(!y||a)return;await c(y)!==!1&&m("")};return t.jsxs("div",{className:"dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden transition-all duration-200 ease-out",style:{borderTop:l?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:l?72:0,opacity:l?1:0,transform:l?"translateY(0)":"translateY(10px)",padding:l?"10px 12px":"0 12px",pointerEvents:l?"auto":"none"},"aria-hidden":!l,children:[t.jsxs("div",{className:"flex gap-2.5 items-center",title:l?`Send message to ${r}`:void 0,children:[t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:u,type:"text",placeholder:i||`Send message to ${r}...`,value:p,onChange:y=>m(y.target.value),onPaste:y=>{const k=y.clipboardData.getData("text");k&&m(A=>A+k),y.preventDefault()},onKeyDown:y=>{if(y.key==="Enter"){if(y.nativeEvent.isComposing){y.preventDefault();return}y.preventDefault(),h()}},onBlur:y=>{if(window.innerWidth<768){const k=y.relatedTarget;if((k==null?void 0:k.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:()=>{h()},disabled:Li({hasDraft:!!p.trim(),isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${p.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:p.trim()&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:t.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:p.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),i&&t.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),et=e=>e.transport==="pty",Es=(e,s)=>et(e)?e.mode||"terminal":"chat",_i=(e,s)=>et(e)&&Es(e)==="terminal",Je=e=>e.transport==="acp";function Jt(e){return e.streamSource!=="agent-stream"}function ts(e){var s;return e.daemonId||((s=e.routeId)==null?void 0:s.split(":")[0])||e.routeId||""}function Ri(e){return e.machineName||""}function nn(e){return ts(e)}function Et(e){return e.agentType||""}function Ur(e){return e.hostIdeType||""}function va(e){return e.displayPrimary||e.agentName||"Agent"}function Pi(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function yu(e){return e.lastMessagePreview||e.displaySecondary||""}function Di(e){return[e.displaySecondary,Ri(e)].filter(Boolean)}function $s(e){return e.agentName||at(Et(e))}function vu(e){var s,r;if(!Jt(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return at(Ur(e)||Et(e))}function Ei(e){return Jt(e)?e.sessionId:e.nativeSessionId}function po(e){return Jt(e)?"native":e.tabKey}function wu(e){return e.sessionId}function ju(e,s){if(s)return Jt(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function ku(e,s){const r=Et(e),n=Jt(e),a=et(e)||Je(e),i=n?a?$s(e)||(s==null?void 0:s.cliName)||at(Ur(e)||r):s!=null&&s.type?at(s.type):at(Ur(e)||r):$s(e);return{isNativeConversation:n,isCli:et(e),isAcp:Je(e),isCliTerminal:_i(e),providerType:r,displayLabel:i,targetEntry:ju(e,s)}}function Su(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 cs(e){const s=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1];return e.lastMessageAt||Su(s==null?void 0:s.receivedAt)||0}function Yn(e,s=0){return cs(e)||e.lastUpdated||s||0}function $i(e){return cs(e)||e.lastUpdated||0}function Bi(e,s,r=$i){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 Xn(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 Nu(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!Xn(e)&&!e.title.trim()}function Cu(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(Xn(r))-Number(Xn(s));if(n!==0)return n;const a=r.messages.length-s.messages.length;return a!==0?a:Bi(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=Cu(a);return n?i&&Nu(n)?i:n:i||r[0]||null}function Zt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function wa(e){return en(e)||e.tabKey||e.routeId||null}function Ki(e){const s=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"";if(s)return s;const r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"";if(r)return r;const n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"";if(!n)return null;const a=Bt(e.conversations,n)||e.conversations.find(i=>i.routeId===n);return a?wa(a):null}function Wi({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=Os(),c=ts(e),l=Ri(e),u=e.transport==="cdp-page"||e.transport==="cdp-webview",p=e.streamSource==="agent-stream"&&!!e.agentName,m=!p&&(e.transport==="pty"||e.transport==="acp"),h=$s(e),y=vu(e),k=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),A=o.useCallback(()=>{if(r){r();return}const d=wa(e);d&&i(Zt(d))},[e,i,r]);return t.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[u&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:A,title:y,children:[t.jsx(Lt,{size:12}),t.jsx("span",{children:y})]}):t.jsxs("span",{className:"conversation-meta-chip",title:y,children:[t.jsx(Lt,{size:12}),t.jsx("span",{children:y})]})),p&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[t.jsx(or,{size:12}),t.jsx("span",{children:h})]}),m&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[t.jsx(or,{size:12}),t.jsx("span",{children:h})]}),l&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:k,title:l,children:[t.jsx(zt,{size:12}),t.jsx("span",{children:l})]}):t.jsxs("span",{className:"conversation-meta-chip",title:l,children:[t.jsx(zt,{size:12}),t.jsx("span",{children:l})]}))]})}function wn(e,s){return`${e}:${s}`}function Iu(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function yr(e,s){Iu()&&console.debug(`[subscription-manager] ${e}`,s)}class Au{constructor(){qe(this,"active",new Map)}subscribe(s,r,n,a){var p;const i=wn(n.topic,n.key),c=this.active.get(i);let l=!0;if(c)c.handlers.add(a),c.lastUpdate&&a(c.lastUpdate);else{const m={daemonId:r,request:n,handlers:new Set([a])};this.active.set(i,m),yr("subscribe",{daemonId:r,topic:n.topic,key:n.key}),l=((p=s.sendData)==null?void 0:p.call(s,r,n))??!1}const u=()=>{var y;const m=this.active.get(i);if(!m||(m.handlers.delete(a),m.handlers.size>0))return;this.active.delete(i);const h={type:"unsubscribe",topic:n.topic,key:n.key};yr("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(y=s.sendData)==null||y.call(s,r,h)};return u.initialSendAccepted=l,u}publish(s){const r=wn(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,_s.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),_s.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.handler_invoked",topic:s.topic,payload:{key:s.key}})}))}updateParams(s,r,n){const a=wn(s,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(s){var r;yr("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);yr("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 es=new Au;function Tu(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 Mu(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 Fr(e,s){const r=[],{daemonId:n,existingDaemon:a,existingEntries:i,timestamp:c}=s,l=c||e.timestamp||Date.now(),u=e.sessions||[],{topLevel:p,childrenByParent:m}=Mu(u),h=Tu(i,n),y=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,k=p.filter(b=>b.kind==="workspace"&&b.transport==="cdp-page"),A=p.filter(b=>b.kind==="agent"&&b.transport==="pty"),d=p.filter(b=>b.kind==="agent"&&b.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...y&&{machine:y,platform:y.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:k.some(b=>!!b.cdpConnected)});for(const b of k){const v=h.get(b.id),f=Js(b,v),C=(m.get(b.id)||[]).map(_=>Js(_,h.get(_.id)));r.push({id:`${n}:ide:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(v==null?void 0:v.providerSessionId),parentSessionId:f.parentId,sessionKind:f.kind,transport:f.transport,sessionCapabilities:f.capabilities,type:f.providerType,status:f.cdpConnected?"online":"detected",daemonId:n,instanceId:b.id,workspace:f.workspace,terminals:0,childSessions:C,agents:C.map(_=>({id:_.id,name:_.providerName||_.providerType,type:_.providerType,status:_.status})),activeChat:f.activeChat,chats:[],cdpConnected:f.cdpConnected,...f.lastMessagePreview!==void 0&&{lastMessagePreview:f.lastMessagePreview},...f.lastMessageRole!==void 0&&{lastMessageRole:f.lastMessageRole},...f.lastMessageAt!==void 0&&{lastMessageAt:f.lastMessageAt},...f.lastMessageHash!==void 0&&{lastMessageHash:f.lastMessageHash},lastUpdated:f.lastUpdated,unread:f.unread,lastSeenAt:f.lastSeenAt,inboxBucket:f.inboxBucket,surfaceHidden:f.surfaceHidden,...f.controlValues!==void 0&&{controlValues:f.controlValues},...f.providerControls!==void 0&&{providerControls:f.providerControls},...f.summaryMetadata!==void 0&&{summaryMetadata:f.summaryMetadata},timestamp:l})}for(const b of A){const v=h.get(b.id),f=Js(b,v);r.push({id:`${n}:cli:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(v==null?void 0:v.providerSessionId),parentSessionId:f.parentId,sessionKind:f.kind,transport:f.transport,sessionCapabilities:f.capabilities,type:f.providerType,agentType:f.providerType,status:f.status||"running",daemonId:n,instanceId:b.id,cliName:f.providerName||f.providerType,mode:f.mode||(v==null?void 0:v.mode)||"terminal",workspace:f.workspace||"",activeChat:f.activeChat,...f.resume!==void 0&&{resume:f.resume},...f.runtimeKey!==void 0&&{runtimeKey:f.runtimeKey},...f.runtimeDisplayName!==void 0&&{runtimeDisplayName:f.runtimeDisplayName},...f.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:f.runtimeWorkspaceLabel},...f.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:f.runtimeWriteOwner},...f.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:f.runtimeAttachedClients},...f.lastMessagePreview!==void 0&&{lastMessagePreview:f.lastMessagePreview},...f.lastMessageRole!==void 0&&{lastMessageRole:f.lastMessageRole},...f.lastMessageAt!==void 0&&{lastMessageAt:f.lastMessageAt},...f.lastMessageHash!==void 0&&{lastMessageHash:f.lastMessageHash},lastUpdated:f.lastUpdated,unread:f.unread,lastSeenAt:f.lastSeenAt,inboxBucket:f.inboxBucket,surfaceHidden:f.surfaceHidden,...f.controlValues!==void 0&&{controlValues:f.controlValues},...f.providerControls!==void 0&&{providerControls:f.providerControls},...f.summaryMetadata!==void 0&&{summaryMetadata:f.summaryMetadata},timestamp:l,_isCli:!0})}for(const b of d){const v=h.get(b.id),f=Js(b,v);r.push({id:`${n}:acp:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(v==null?void 0:v.providerSessionId),parentSessionId:f.parentId,sessionKind:f.kind,transport:f.transport,sessionCapabilities:f.capabilities,type:f.providerType,agentType:f.providerType,status:f.status||"running",daemonId:n,instanceId:b.id,cliName:f.providerName||f.providerType,mode:"chat",workspace:f.workspace||"",activeChat:f.activeChat,...f.runtimeKey!==void 0&&{runtimeKey:f.runtimeKey},...f.runtimeDisplayName!==void 0&&{runtimeDisplayName:f.runtimeDisplayName},...f.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:f.runtimeWorkspaceLabel},...f.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:f.runtimeWriteOwner},...f.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:f.runtimeAttachedClients},...f.lastMessagePreview!==void 0&&{lastMessagePreview:f.lastMessagePreview},...f.lastMessageRole!==void 0&&{lastMessageRole:f.lastMessageRole},...f.lastMessageAt!==void 0&&{lastMessageAt:f.lastMessageAt},...f.lastMessageHash!==void 0&&{lastMessageHash:f.lastMessageHash},lastUpdated:f.lastUpdated,unread:f.unread,lastSeenAt:f.lastSeenAt,inboxBucket:f.inboxBucket,surfaceHidden:f.surfaceHidden,...f.controlValues!==void 0&&{controlValues:f.controlValues},...f.providerControls!==void 0&&{providerControls:f.providerControls},...f.summaryMetadata!==void 0&&{summaryMetadata:f.summaryMetadata},timestamp:l,_isAcp:!0})}return r}const jn=new Map,kn=new Map,Sn=new Set,tr=new Map,Lu=1200;function _u(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 fo(e,s){const r=tr.get(e);!r||r.size===0||(tr.delete(e),r.forEach(n=>n(s)))}function Ru(e,s){return new Promise(r=>{const n=tr.get(e)||new Set;tr.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&tr.delete(e),r(c)},i=setTimeout(()=>a(!1),s);n.add(a)})}function ur(){const{sendCommand:e,sendData:s}=Dt(),{injectEntries:r,getIdes:n}=Wr();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??6e4,l=kn.get(a)||0;if(!(i!=null&&i.force)&&Sn.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const u=jn.get(a);if(u)return u;const p=(async()=>{if(s&&!Sn.has(a)&&(Sn.add(a),es.subscribe({sendData:s},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},d=>{const b=n(),v=b.find(C=>C.id===a),f=Fr(d.status,{daemonId:a,existingDaemon:v,existingEntries:b,timestamp:d.timestamp});f.length>0&&r(f),kn.set(a,Date.now()),fo(a,!0)}),!(i!=null&&i.force)&&await Ru(a,Lu)))return;const m=await e(a,"get_status_metadata"),h=_u(m);if(!h)return;const y=n(),k=y.find(d=>d.id===a),A=Fr(h,{daemonId:a,existingDaemon:k,existingEntries:y,timestamp:h.timestamp||Date.now()});A.length>0&&r(A,{authoritativeDaemonIds:[a]}),kn.set(a,Date.now()),fo(a,!0)})().finally(()=>{jn.delete(a)});return jn.set(a,p),p},[n,r,e,s])}function Gt(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}function ja(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=Ps(e.content),i=Ps(s.content);if(!a||!i||!(a===i||cr(a,i)||cr(i,a)))return!1;const l=Gt(e),u=Gt(s);return l&&u?Math.abs(l-u)<=15e3:!!e._localId!=!!s._localId}function ho(e){let s=0;return e!=null&&e._localId||(s+=4),e!=null&&e.id&&(s+=3),e!=null&&e._turnKey&&(s+=2),Gt(e)&&(s+=1),s}function Bs(e){return Ps(e==null?void 0:e.content)}function cr(e,s){if(!e||!s||e.length<=s.length)return!1;const r=Math.max(12,Math.min(80,Math.floor(e.length*.4)));return s.length<r?!1:e.startsWith(s)||e.includes(s)}function Pu(e,s){const r=Bs(e),n=Bs(s);return!r||!n||r===n?null:cr(r,n)?e:cr(n,r)?s:null}function Du(e,s){const r=Pu(e,s);if(r)return r;const n=ho(e),a=ho(s);return a!==n?a>n?s:e:Bs(s).length>=Bs(e).length?s:e}function ls(e){const s=[];for(const r of e){const n=s.findIndex(a=>ja(a,r));if(n>=0){s.splice(n,1,Du(s[n],r));continue}s.push(r)}return s}function Eu(e,s){const r=Array.isArray(e)?e:[],n=Array.isArray(s)?s:[];return r.length===0?n:n.length===0?r:ls([...r,...n])}function xo(e){return[...e].sort((s,r)=>{const n=Gt(s),a=Gt(r);return n&&a&&n!==a?n-a:0})}function bo(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=>ja(i,n));return a>=0?(r.splice(a,1),!1):!0})}function $u(e,s){return e.filter(r=>{const n=Bs(r),a=String((r==null?void 0:r.role)||"").toLowerCase(),i=Gt(r);return!s.some(c=>{if(ja(r,c))return!0;const l=String((c==null?void 0:c.role)||"").toLowerCase();if(!n||!a||a!==l)return!1;const u=Bs(c);if(!cr(u,n)&&u!==n)return!1;const p=Gt(c);return i&&p?Math.abs(i-p)<=15e3:!0})})}function Ms(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:et(e)||Je(e)?{agentType:Et(e)}:e.streamSource==="agent-stream"?{agentType:Et(e)}:s}function lr(e){return e?nn(e):""}function Gs(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function ka(e){if(!e)return null;if(Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return"Resolve the pending approval prompt before sending another message.";switch(e.status){case"waiting_approval":case"waiting_for_user_input":return"Resolve the pending approval prompt before sending another message.";default:return null}}function Bu(e){const s=e instanceof Error?e.message:String(e||""),r=s.toLowerCase();return r.includes("still processing the previous prompt")?"Wait for the current reply to finish before sending another message.":r.includes("awaiting confirmation")?"Resolve the pending approval prompt before sending another message.":r.includes("not ready")?"Wait for the runtime to finish starting up before sending a message.":r.includes("not running")?"Runtime is not available right now.":s||"Unable to send message right now."}const Ku=60,Wu=200;function Oi(e={}){return e.isCliLike?Wu:Ku}function Ou(e={}){return Oi(e)}const an=60,go=new Map;function Hu(e,s){return`${e}::${s}`}function Qn(e=an){return{liveMessages:[],cursor:Ui([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function Hi(e){return li(e)}function Ui(e,s=an){return{knownMessageCount:e.length,lastMessageSignature:Hi(e[e.length-1]),tailLimit:s}}function vr(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 Uu(e,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return e;case"append":return ls([...e,...r]);case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??e.length),e.length));return ls([...e.slice(0,n),...r])}case"full":{const n=Math.max(Number(s.totalMessages||0),r.length);if(n>r.length&&e.length>r.length){const a=Math.max(0,n-r.length);return ls([...e.slice(0,a),...r])}return r}default:return r}}class Fu{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||es,this.sendData=s.sendData,this.daemonId=s.daemonId,this.sessionId=s.sessionId,this.historySessionId=s.historySessionId,this.subscriptionKey=s.subscriptionKey,this.snapshot=Qn(Math.max(0,s.tailLimit??an))}updateOptions(s){if(s.manager&&(this.manager=s.manager),s.sendData&&(this.sendData=s.sendData),s.historySessionId&&(this.historySessionId=s.historySessionId),s.tailLimit!==void 0){const r=Math.max(0,s.tailLimit);if(r!==this.snapshot.cursor.tailLimit){const n=Math.min(this.snapshot.cursor.knownMessageCount,this.snapshot.liveMessages.length);this.snapshot={...this.snapshot,cursor:{...this.snapshot.cursor,knownMessageCount:n,tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect())}}}getSnapshot(){return this.snapshot}hydrateLiveMessages(s){const r=Array.isArray(s)?s:[];if(r.length===0)return;const n=ls([...r,...this.snapshot.liveMessages]);if(n.length<r.length)return;const a=Ui(n,this.snapshot.cursor.tailLimit);vr(this.snapshot.liveMessages)===vr(n)&&this.snapshot.cursor.knownMessageCount===a.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===a.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:n,cursor:a})}subscribe(s){return this.listeners.add(s),s(this.snapshot),()=>{this.listeners.delete(s)}}retain(){this.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=Uu(this.snapshot.liveMessages,s),n={knownMessageCount:r.length,lastMessageSignature:typeof s.lastMessageSignature=="string"?s.lastMessageSignature:Hi(r[r.length-1]),tailLimit:this.snapshot.cursor.tailLimit};vr(this.snapshot.liveMessages)===vr(r)&&this.snapshot.cursor.knownMessageCount===n.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===n.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:r,cursor:n},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:n.knownMessageCount,lastMessageSignature:n.lastMessageSignature}),this.emit())}}function zu(e){const s=Hu(e.daemonId,e.sessionId),r=go.get(s);if(r)return r.updateOptions(e),r;const n=new Fu(e);return go.set(s,n),n}function Vu(e,s){return{...e,loadHistoryPage:s}}function Gu(e,s){const{sendData:r,sendCommand:n}=Dt(),a=(s==null?void 0:s.enabled)!==!1,i=nn(e),c=e.sessionId||"",l=en(e)||c,u=`daemon:${i}:session:${c}`,p=Math.max(0,(s==null?void 0:s.tailLimit)??an),m=o.useMemo(()=>!a||!i||!c?null:zu({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:u,sendData:r,tailLimit:p}),[i,a,l,r,c,u,p]),[h,y]=o.useState(()=>(m==null?void 0:m.getSnapshot())||Qn(p));o.useEffect(()=>{if(!m){y(Qn(p));return}m.hydrateLiveMessages(e.messages),m.retain(),y(m.getSnapshot());const A=m.subscribe(d=>{y(d)});return()=>{A(),m.release()}},[e.messages,m,p]);const k=o.useCallback(async()=>{!m||!i||!c||await m.loadHistoryPage(async()=>{const A=e.agentType,d=await n(i,"chat_history",{agentType:A,offset:m.getSnapshot().historyOffset,limit:30,targetSessionId:c,historySessionId:l}),b=d&&typeof d=="object"&&"result"in d?d.result||{}:d||{};return{messages:Array.isArray(b.messages)?b.messages:[],hasMore:b.hasMore===!0}})},[e.agentType,m,i,l,n,c]);return o.useMemo(()=>Vu(h,k),[k,h])}function qu(e,s){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(s)}function Yu(e){return qu(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const Xu=60;function Jn({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:l,userName:u,showMetaChips:p=!1,scrollToBottomRequestNonce:m,isInputActive:h=!0}){var q,ue,Z,se;const y=o.useRef(new Map),k=ur();dr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const A=nt.useMemo(()=>Us(e),[e.status,e.connectionState]),d=o.useMemo(()=>ku(e,s),[e,s]),b=Oi({isCliLike:d.isCli||d.isAcp}),v=Ou({isCliLike:d.isCli||d.isAcp}),f=Gu(e,{enabled:!!e.sessionId,tailLimit:v}),[C,_]=o.useState(b),g=e.tabKey,I=f.historyMessages,j=f.hasMoreHistory,w=f.historyError,x=Eu(f.liveMessages,e.messages);o.useEffect(()=>{_(b)},[b,g]);const $=Math.max(0,x.length-C),N=va(e),L=nn(e),T=Yu(e),K=ka(e),F=a||K,M=!!K,[P,O]=o.useState(!1);o.useEffect(()=>{const oe=d.targetEntry;L&&(!oe||oe.providerControls===void 0||oe.controlValues===void 0)&&k(L,{minFreshMs:3e4}).catch(()=>{})},[L,d.isAcp,(q=d.targetEntry)==null?void 0:q.providerControls,(ue=d.targetEntry)==null?void 0:ue.controlValues,k]);const S=o.useCallback(async()=>{if(!P){if(x.length>C){_(oe=>Math.min(x.length,oe+Xu));return}O(!0);try{await f.loadHistoryPage()}finally{O(!1)}}},[f,P,x.length,C]),{allMessages:D,receivedAtMap:z}=o.useMemo(()=>{const oe=$>0?x.slice(-C):x;if(I.length===0){const ie=xo(ls(oe)),V={};return ie.forEach((ye,Q)=>{const ge=`${e.tabKey}:${Cs(ye,Q)}`;let te=Gt(ye)||y.current.get(ge)||0;te||(te=Date.now(),y.current.set(ge,te)),V[Cs(ye,Q)]=te}),{allMessages:ie,receivedAtMap:V}}const Ne=$u(I,oe),me=xo(ls([...Ne,...oe])),he={};return me.forEach((ie,V)=>{const ye=`${e.tabKey}:${Cs(ie,V)}`;let Q=Gt(ie)||y.current.get(ye)||0;Q||(Q=Date.now(),y.current.set(ye,Q)),he[Cs(ie,V)]=Q}),{allMessages:me,receivedAtMap:he}},[e.tabKey,$,I,x,C]),U=o.useMemo(()=>l.filter(oe=>oe.routeId===e.tabKey).sort((oe,Ne)=>oe.timestamp-Ne.timestamp),[l,e.tabKey]),ae=o.useMemo(()=>{if(x.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[t.jsx("div",{className:"connecting-logo-float",children:t.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),t.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[t.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",t.jsx("span",{className:"connecting-dots"})]}),t.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((A.isGenerating||e.status==="streaming")&&O(!1),e.status==="not_monitored"&&T)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(or,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),t.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Switching...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Rs,{size:14})," Open ",N," 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"&&T)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(ua,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),t.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Opening...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Rs,{size:14})," Open ",N," 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"&&!P)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,T,i,c,P,x.length,N,A.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[p&&t.jsx(Wi,{conversation:e,className:"chat-pane-meta-row"}),t.jsx(xd,{messages:D,actionLogs:U,agentName:$s(e)||N||"Agent",userName:u,isCliMode:d.isCli||d.isAcp,isWorking:A.isGenerating,contextKey:e.tabKey,receivedAtMap:z,onLoadMore:S,isLoadingMore:P,hasMoreHistory:j,hiddenLiveCount:$,loadError:w??void 0,emptyState:ae,scrollToBottomRequestNonce:m}),t.jsx(bu,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:d.providerType,displayLabel:d.displayLabel,controls:(Z=d.targetEntry)==null?void 0:Z.providerControls,controlValues:(se=d.targetEntry)==null?void 0:se.controlValues,isActive:h,isCliTerminal:d.isCliTerminal}),!d.isCliTerminal&&t.jsx(gu,{contextKey:e.tabKey,panelLabel:N,isSending:n,isBusy:M,statusMessage:F,onSend:r,isActive:h})]})}let Fi=xs;function zi(){return Fi()}class Qu{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 Vi=new Qu;class Ju{sendPtyInput(s,r,n){return!1}retryConnection(s){}getState(s){return"disconnected"}sendData(s,r){return!1}get(s){}onScreenshot(s,r){return()=>{}}onRuntimeEvent(s,r){return()=>{}}requestRuntimeSnapshot(s,r){return Promise.resolve()}}let ut=new Ju;function Zu(e){e.dashboardWS&&(Vi=e.dashboardWS),e.connectionManager&&(ut=e.connectionManager),e.useDaemonsHook&&(Fi=e.useDaemonsHook)}const Gi=.6,em=1.15;function tm(e,s={}){const r=typeof s.minScale=="number"?s.minScale:Gi;return!Number.isFinite(e)||e<=0?1:e<=480?r:1}function dt(e){return va(e)}function ys(e){return Di(e).join(" · ")}function qi(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=Ps(s==null?void 0:s.content);return r||(e.title?e.title:ys(e)||"No messages yet")}function Yi(e,s){const{isReconnecting:r,isConnecting:n}=Us(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function sm(e,s){const r=["Chat",...Di(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function ds(e){return Yi(e)||ys(e)}function rm(e){return`${dt(e)} · ${qi(e)}`}function nm(e){const s=Ur(e),r=s?at(s):$s(e);return`${dt(e)} — ${r||"Agent"}`}function am(e){return $s(e)||"CLI"}function Xi(e){return Pi(e)}function Qi(e){return e?`Remote · ${dt(e)||e.workspaceName||"Session"}`:"Remote"}function om({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0}){var ae;const{ides:l}=xs(),u=o.useRef(null),{sendCommand:p,sendData:m}=Dt(),[h,y]=o.useState(""),[k,A]=o.useState(!1),[d,b]=o.useState(1),v=o.useRef(!1),f=o.useRef(0),C=o.useRef(!1),_=o.useRef(""),g=o.useRef(null),I=o.useRef(!1),j=o.useRef(null),w=e.tabKey,x=e.sessionId||"",$=e.daemonId||((ae=e.routeId)==null?void 0:ae.split(":")[0])||e.routeId||"",N=l.find(q=>q.id===$&&q.type==="adhdev-daemon"),L=(N==null?void 0:N.terminalSizingMode)==="fit"?"fit":"measured",T=ka(e),K=i||T,F=Gi,M=em,P=()=>typeof window>"u"?1:tm(window.innerWidth||0,{minScale:F}),O=()=>{var q,ue;f.current=0,C.current=!1,_.current="",g.current=null,I.current=!1,j.current!==null&&(cancelAnimationFrame(j.current),j.current=null),A(!1),(ue=(q=r.current)==null?void 0:q.reset)==null||ue.call(q)},S=()=>{var q,ue;f.current=0,C.current=!1,_.current="",g.current=null,I.current=!1,j.current!==null&&(cancelAnimationFrame(j.current),j.current=null),A(!0),(ue=(q=r.current)==null?void 0:q.reset)==null||ue.call(q)},D=()=>{var ue;if(j.current=null,!c)return;const q=_.current;q&&(_.current="",(ue=r.current)==null||ue.write(q))},z=q=>{q&&(_.current+=q,c&&j.current===null&&(j.current=requestAnimationFrame(D)))},U=(q,ue=0,Z,se)=>{var oe,Ne,me,he,ie;ue>0&&f.current>=ue||ue===0&&C.current||(f.current=ue,A(!0),typeof Z=="number"&&typeof se=="number"&&Z>0&&se>0&&((Ne=(oe=r.current)==null?void 0:oe.resize)==null||Ne.call(oe,Z,se)),(he=(me=r.current)==null?void 0:me.reset)==null||he.call(me),q&&((ie=r.current)==null||ie.write(q)))};return o.useEffect(()=>{O()},[x]),o.useEffect(()=>{var ue;if(!x)return;const q=((ue=ut.onRuntimeEvent)==null?void 0:ue.call(ut,x,Z=>{if(!(!Z||Z.sessionId!==x)){if(Z.type==="runtime_snapshot"){if(!c){g.current={text:Z.text||"",seq:Z.seq||0,cols:Z.cols,rows:Z.rows};return}U(Z.text||"",Z.seq||0,Z.cols,Z.rows);return}if(Z.type==="session_output"){C.current=!0,typeof Z.seq=="number"&&(f.current=Math.max(f.current,Z.seq)),k||A(!0),typeof Z.data=="string"&&z(Z.data);return}if(Z.type==="session_cleared"){if(!c){I.current=!0,_.current="",g.current=null;return}S()}}}))||(()=>{});return()=>{q()}},[$,x,r,c,k]),o.useEffect(()=>{var ue,Z,se;if(!x)return;$&&((ue=ut.getState)==null?void 0:ue.call(ut,$))==="connected"&&(A(!0),(Z=ut.requestRuntimeSnapshot)==null||Z.call(ut,$,x).catch(()=>{}));const q=(se=ut.onStateChange)==null?void 0:se.call(ut,(oe,Ne)=>{var me;oe!==$||Ne!=="connected"||(A(!0),(me=ut.requestRuntimeSnapshot)==null||me.call(ut,$,x).catch(()=>{}))});return()=>{q==null||q()}},[$,x,r]),o.useEffect(()=>{s&&O()},[s,w,r]),o.useEffect(()=>{y("")},[e.tabKey]),o.useEffect(()=>{const q=()=>{v.current||b(P())};return q(),window.addEventListener("resize",q),()=>window.removeEventListener("resize",q)},[]),o.useEffect(()=>{var ue;if(!c){(ue=u.current)==null||ue.blur();return}I.current&&(I.current=!1,S());const q=g.current;q&&(g.current=null,U(q.text,q.seq,q.cols,q.rows)),_.current&&j.current===null&&(j.current=requestAnimationFrame(D)),requestAnimationFrame(()=>{var Z;(Z=r.current)==null||Z.bumpResize()})},[c]),o.useEffect(()=>()=>{j.current!==null&&(cancelAnimationFrame(j.current),j.current=null)},[]),o.useEffect(()=>{const q=ue=>{var se;const Z=ue.detail;Z!=null&&Z.sessionId&&Z.sessionId!==x||k&&((se=r.current)==null||se.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",q),()=>{window.removeEventListener("adhdev:fit-cli-terminal",q)}},[k,x,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:()=>{v.current=!0,b(q=>Math.max(F,Number((q-.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:()=>{v.current=!0,b(q=>Math.min(M,Number((q+.1).toFixed(2))))},title:"Increase terminal viewport",children:"+"})]}),t.jsx("div",{className:"w-full h-full overflow-x-auto overflow-y-hidden rounded-lg overscroll-contain",children:t.jsx("div",{style:{width:`${100/d}%`,height:`${100/d}%`,transform:`scale(${d})`,transformOrigin:"top left"},children:t.jsx(xi,{ref:r,readOnly:!k||!c,sizingMode:L,onInput:q=>{k&&(m!=null&&m($,{type:"pty_input",sessionId:x,targetSessionId:x,data:q})||p($,"pty_input",{targetSessionId:x,data:q}).catch(console.error))}})})}),!k&&t.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:"Runtime terminal unavailable"})]}),t.jsxs("div",{className:"px-3 py-2 bg-[var(--surface-primary)] border-t border-border-subtle shrink-0",children:[t.jsxs("div",{className:"flex gap-2.5 items-center",children:[t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:u,type:"text",placeholder:K||`Send message to ${dt(e)}...`,value:h,disabled:!k||!c,onChange:q=>y(q.target.value),onPaste:q=>{const ue=q.clipboardData.getData("text");ue&&y(Z=>Z+ue),q.preventDefault()},onKeyDown:q=>{if(q.key!=="Enter")return;if(q.nativeEvent.isComposing){q.preventDefault();return}q.preventDefault();const ue=h.trim();!k||!ue||T||n(ue).then(Z=>{Z!==!1&&y("")})},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 q=h.trim();!k||!q||T||n(q).then(ue=>{ue!==!1&&y("")})},disabled:!k||!c||Li({hasDraft:!!h.trim(),isBusy:!!T}),className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${h.trim()&&!T?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:h.trim()&&!T?{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:h.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),K&&t.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:K})]})]})}function im({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 cm({terminalBackend:e,isStandalone:s=!1,machineLabel:r,machineKey:n}){const a=o.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[i,c]=o.useState(!1);if(o.useEffect(()=>{if(!a){c(!1);return}try{c(localStorage.getItem(a)==="1")}catch{c(!1)}},[a]),!s||!e||e.backend!=="xterm"||i)return null;const l=(r==null?void 0:r.trim())||"This machine",u=()=>{if(a)try{localStorage.setItem(a,"1")}catch{}c(!0)};return t.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5",style:{background:"linear-gradient(90deg, rgba(245,158,11,0.12), rgba(245,158,11,0.04))",borderBottom:"1px solid rgba(245,158,11,0.2)",color:"#d97706"},children:[t.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[t.jsxs("span",{children:[l," is using `xterm` fallback."]}),t.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),t.jsx("button",{type:"button",onClick:u,className:"shrink-0 text-[12px] font-semibold px-2 py-1 rounded-md transition-colors",style:{color:"#b45309",background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.18)"},"aria-label":"Dismiss terminal backend warning",title:"Dismiss",children:"Dismiss"})]})}function Sa({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(Jr,{size:n}):t.jsx(Vt,{size:n})})}function yo({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function vo({notification:e,shortcutIndex:s,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=tn(e.updatedAt),l=!e.readAt;return t.jsxs("div",{className:`dashboard-header-inbox-item ${l?"is-attention":""}`.trim(),children:[t.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[s?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",s]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",c].filter(Boolean).join(" · ")]}),e.preview?t.jsx("span",{className:"dashboard-header-inbox-item-meta",children:e.preview}):null]}),t.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[l?t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),n()},children:"Mark read"}):t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),a()},children:"Mark unread"}),t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),i()},children:"Delete"})]})]})}function lm({activeConv:e,agentCount:s,wsStatus:r,isConnected:n,conversations:a,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:u,onSetCliViewMode:p,onHideConversation:m,hiddenConversations:h=[],onShowConversation:y,onShowAllHidden:k,onResetPanelsToMain:A,inboxOpen:d,onInboxOpenChange:b,hiddenOpen:v,onHiddenOpenChange:f,onOpenNewSession:C,actionShortcuts:_,notifications:g,notificationUnreadCount:I,onOpenNotification:j,onMarkNotificationRead:w,onMarkNotificationUnread:x,onDeleteNotification:$}){const{ides:N,p2pStates:L={}}=xs(),T=!!e&&et(e)&&!Je(e),K=!!e&&Je(e),F=u||(e?_i(e)?"terminal":"chat":null),[M,P]=o.useState(!1),O=o.useRef(null),S=o.useRef(null),D=n?"#22c55e":r==="connected"?"#eab308":"#ef4444",z=n?"0 0 4px #22c55e80":r==="connected"?"0 0 4px #eab30880":"0 0 4px #ef444480",U=N.filter(V=>V.type==="adhdev-daemon"),ae=Object.values(L),q=ae.filter(V=>V==="connected").length,ue=ae.filter(V=>V==="connecting"||V==="new"||V==="checking").length,se=r!=="connected"||U.length===0?null:ue>0&&q===0?"P2P connecting...":q>0&&s===0?"Waiting for IDE...":null,oe=o.useMemo(()=>g.filter(V=>!V.readAt),[g]),Ne=o.useMemo(()=>g.filter(V=>!!V.readAt),[g]),me=o.useMemo(()=>oe.slice(0,9),[oe]),he=I;o.useEffect(()=>{if(!d)return;const V=ye=>{var Q;(Q=O.current)!=null&&Q.contains(ye.target)||b(!1)};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[d,b]),o.useEffect(()=>{if(!v)return;const V=ye=>{var Q;(Q=S.current)!=null&&Q.contains(ye.target)||f(!1)};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[v,f]),o.useEffect(()=>{if(!v&&!d)return;const V=ye=>{if(!ye.altKey)return;const Q=ye.code.match(/^Digit([1-9])$/);if(!Q)return;const ge=Number(Q[1])-1,te=v?h[ge]:void 0,ce=d?me[ge]:void 0;if(!(!te&&!ce)){if(ye.preventDefault(),ye.stopPropagation(),te){y==null||y(te),f(!1);return}ce&&(j(ce),b(!1))}};return window.addEventListener("keydown",V,!0),()=>window.removeEventListener("keydown",V,!0)},[h,v,d,me,f,b,j,y]);const ie=V=>{if(!V)return;const ye=a.find(Q=>Q.tabKey===V);ye&&(m==null||m(ye))};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(Vt,{size:18}),t.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),t.jsx("span",{className:"header-title-mobile",children:e?dt(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:z}})})]}),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:z}}),se&&t.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",se]}),C&&t.jsx("button",{type:"button",onClick:C,className:"btn btn-secondary btn-sm ml-2",title:"Start or recover a session","aria-label":"Start or recover a session",children:t.jsx(Gl,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(T||K||!Je(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:ys(e)||dt(e),children:dt(e)}),(T||K)&&l&&t.jsxs(t.Fragment,{children:[T&&p&&F&&t.jsx(Sa,{mode:F,onChange:p,compact:!0}),t.jsx("button",{onClick:()=>l(e),className:"btn btn-secondary btn-sm",title:K?"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(Nt,{size:14})})]}),!Je(e)&&t.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:t.jsx(da,{size:14})}),!T&&!Je(e)&&t.jsx("button",{onClick:c,className:"btn btn-secondary btn-sm",title:"Remote Control",children:t.jsx(Lt,{size:14})})]}),t.jsxs("div",{className:"dashboard-header-inbox",ref:O,children:[t.jsxs("div",{className:`dashboard-header-hidden${M?" is-drop-target":""}`,ref:S,onDragEnter:V=>{V.dataTransfer.types.includes("text/tab-key")&&(V.preventDefault(),P(!0))},onDragOver:V=>{V.dataTransfer.types.includes("text/tab-key")&&(V.preventDefault(),V.dataTransfer.dropEffect="move",P(!0))},onDragLeave:V=>{V.currentTarget.contains(V.relatedTarget)||P(!1)},onDrop:V=>{const ye=V.dataTransfer.getData("text/tab-key");V.preventDefault(),P(!1),ie(ye)},children:[t.jsxs("button",{type:"button",onClick:()=>f(!v),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(ma,{size:16}),h.length>0&&t.jsx("span",{className:"dashboard-header-hidden-badge",children:h.length})]}),v&&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(yo,{value:_==null?void 0:_.toggleHiddenTabs})]}),t.jsxs("div",{className:"dashboard-header-hidden-actions",children:[A&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:A,children:"Reset panels"}),h.length>0&&k&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{k(),f(!1)},children:"Restore all"})]})]}),e&&m&&t.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>m(e),children:[t.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[t.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),t.jsx(yo,{value:_==null?void 0:_.hideCurrentTab})]}),t.jsx("span",{className:"dashboard-header-hidden-current-title",children:dt(e)})]}),h.length>0?t.jsx("div",{className:"dashboard-header-hidden-list",children:h.map(V=>t.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{y==null||y(V),f(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:dt(V)}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[h.indexOf(V)<9?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",h.indexOf(V)+1]}):null,ys(V)]})]},V.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(Zr,{size:16}),he>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:he})]}),d&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[oe.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),oe.map(V=>t.jsx(vo,{notification:V,shortcutIndex:me.indexOf(V)>=0?me.indexOf(V)+1:void 0,onOpen:()=>j(V),onMarkRead:()=>w(V.id),onMarkUnread:()=>x(V.id),onDelete:()=>$(V.id)},V.id))]}),Ne.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),Ne.map(V=>t.jsx(vo,{notification:V,onOpen:()=>j(V),onMarkRead:()=>w(V.id),onMarkUnread:()=>x(V.id),onDelete:()=>$(V.id)},V.id))]}),g.length===0&&t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function yt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function dm(e,s){return String(e||"")!==String(s||"")}function um(e,s={}){const r=String(s.textQuery||"").trim().toLowerCase(),n=String(s.workspaceQuery||"").trim().toLowerCase(),a=String(s.modelQuery||"").trim().toLowerCase(),i=!!s.resumableOnly;return!r&&!n&&!a&&!i?e:e.filter(c=>!(i&&!c.canResume||r&&![c.title,c.preview].map(u=>String(u||"").toLowerCase()).join(`
|
|
31
31
|
`).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!Ni(c.summaryMetadata).map(u=>u.toLowerCase()).join(`
|
|
32
|
-
`).includes(a)))}function mm(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 Ji(e,s={}){return mm(um(e,s),s.sortMode||"recent")}function zr(e){return e?"Resume saved history":"Start fresh"}function Na(e){return e?"Resuming saved history…":"Starting fresh…"}function pm(){return"Start fresh"}function Zi(e,s=!1){return e==="cli"?zr(s):e==="ide"?"Start IDE":"Start ACP session"}function ec(e,s=!1){return e==="cli"?Na(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function fm(){return"Recover hosted runtime"}function hm(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function xm(){return"Open saved history"}function bm(){return"Saved History"}function Ca(){return"Use saved history when you want continuity in the same provider conversation."}function gm(){return"No saved history found yet."}function ym(){return"Refresh saved history"}function vm(){return"Refreshing saved history…"}function us(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function ms(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 Ks(e){return e==="start-fresh"?"Start fresh":"Restart"}function Ws(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Ia(e){return`Resume saved history with ${e}?`}function Aa(){return"Review or change the target workspace before resuming saved history."}function wm(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 Ta({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:u,onClose:p,onNewChat:m,onSwitchSession:h,onRefreshHistory:y,onResumeSavedSession:k}){var w;const A=s.find(x=>x.id===e.routeId),d=(A==null?void 0:A.chats)||[],b=(w=A==null?void 0:A.activeChat)==null?void 0:w.id,v=et(e)&&!Je(e),[f,C]=o.useState(()=>yt()),_=l||f,g=x=>{if(u){u(x);return}C(x)},I=o.useMemo(()=>Ji(a,{textQuery:_.textQuery,workspaceQuery:_.workspaceQuery,modelQuery:_.modelQuery,resumableOnly:_.resumableOnly,sortMode:_.sortMode}),[_.modelQuery,_.resumableOnly,_.sortMode,_.textQuery,_.workspaceQuery,a]),j=t.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[t.jsx("div",{onClick:p,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),t.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[t.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[t.jsxs("div",{children:[t.jsx("h3",{className:"m-0 text-lg font-extrabold",children:v?bm():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:nm(e)}),v&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Ca()})]}),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(Nt,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!v&&t.jsx("button",{onClick:m,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),v?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=>g({..._,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=>g({..._,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=>g({..._,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=>g({..._,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=>g({..._,resumableOnly:x.target.checked})}),"Resume-ready only"]})]}),I.map(x=>{const $=e.providerSessionId===x.providerSessionId,N=$||!x.canResume||!!c;return t.jsxs("button",{type:"button",onClick:()=>{N||!k||k(x)},disabled:N,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"} ${N?"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:wm(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",gs(x.summaryMetadata)?` · ${gs(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:()=>{h(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)),(v&&!i&&I.length===0||!v&&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(Ql,{size:32})}),t.jsx("div",{className:"text-[13px]",children:v?a.length>0?"No saved history matches these filters.":gm():"No recent chat sessions found."})]}),v&&i&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:vm()})})]}),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:y,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(Hs,{size:13})," ",v?ym():"Refresh History"]})})})]})]});return typeof document>"u"?j:ar.createPortal(j,document.body)}const wo={success:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Done"},warning:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Attention"},info:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Update"}};function tc({toasts:e,onDismiss: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=wo[n.type]||wo.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(Nt,{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 jm=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function km(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function Sm(e){return e.sessionId||e.instanceId||e.agentType}function Nn(e,s){return e||s}function jo(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 sc(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=Mt(r,{fallbackId:r.id}));return s}function rc(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 Ma(e,s,r={}){return Nm(e,s,rc(e,r))}function Nm(e,s,r={}){var h,y,k,A,d,b;const n=[],a=r.machineName,i=r.connectionState,c=km(e),l=Ed(e.type,{agentName:e.cliName}),u=et(e)||Je(e)?l:at(e.type),p=Array.isArray(e.childSessions)?e.childSessions.map(v=>{var f,C;return{sessionId:v.id,instanceId:v.id,providerSessionId:v.providerSessionId,transport:v.transport,sessionCapabilities:v.capabilities,agentType:v.providerType,agentName:v.providerName||at(v.providerType),status:v.status,title:v.title,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,messages:((f=v.activeChat)==null?void 0:f.messages)||[],activeModal:((C=v.activeChat)==null?void 0:C.activeModal)||void 0,unread:v.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,inboxBucket:v.inboxBucket,surfaceHidden:v.surfaceHidden}}):[],m=jm(e);if(m){const v=e.sessionId||e.instanceId,f=l,C=(h=e.activeChat)==null?void 0:h.activeModal,_=C&&Array.isArray(C.buttons)&&C.buttons.length>0,g=jt((y=e.activeChat)==null?void 0:y.status,{activeModal:(k=e.activeChat)==null?void 0:k.activeModal})||jt((d=(A=e.agents)==null?void 0:A[0])==null?void 0:d.status)||"idle",I=e.activeChat||{title:"",messages:[]};let j=I.title&&String(I.title).trim()?String(I.title).trim():"";const w=(b=e.activeChat)==null?void 0:b.id,x=e.chats;if(w&&Array.isArray(x)&&x.length>0){const F=x.find(M=>M.id===w||M.id&&String(M.id)===String(w));F!=null&&F.title&&String(F.title).trim()&&(j=String(F.title).trim())}const $=(et(e)||Je(e),e.type),N=(et(e)||Je(e))&&lo(j,f,$)?"":j,L=I.messages||[],T=jo(s,[e.id,v]),K=bo(L,T);n.push({routeId:e.id,sessionId:v,providerSessionId:e.providerSessionId,nativeSessionId:v,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:et(e)?e.mode||"terminal":"chat",agentName:f,agentType:$,status:g,title:N,messages:[...L,...K],resume:e.resume,hostIdeType:!et(e)&&!Je(e)?e.type:void 0,workspaceName:c,displayPrimary:N||c||(et(e)?e.mode==="chat"?f:"Terminal":f),displaySecondary:u,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:_?C.buttons:void 0,modalMessage:_?C.message:void 0,streamSource:"native",tabKey:Nn(v,e.id),machineName:a,connectionState:i})}if(m&&(et(e)||Je(e)))return n;for(const v of p){const f=v.activeModal&&Array.isArray(v.activeModal.buttons)&&v.activeModal.buttons.length>0,C=$d(v),_=Sm(v),g=`${e.id}:${_}`,I=v.title&&String(v.title).trim()||"",j=lo(I,v.agentName,v.agentType)?"":I,w=v.messages||[],x=jo(s,[g,v.sessionId,v.instanceId]),$=bo(w,x);(v.transport==="cdp-webview"||v.sessionId||v.providerSessionId||w.length>0||$.length>0||f||j||!["idle","panel_hidden","disconnected","not_monitored"].includes(C))&&n.push({routeId:e.id,sessionId:v.sessionId||v.instanceId,providerSessionId:v.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:v.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:v.sessionCapabilities,mode:"chat",agentName:v.agentName,agentType:v.agentType,status:C,title:j,messages:[...w,...$],hostIdeType:e.type,workspaceName:c,displayPrimary:j||c||v.agentName||u,displaySecondary:`${u} · ${v.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,lastUpdated:v.lastUpdated||e.lastUpdated,modalButtons:f?v.activeModal.buttons:void 0,modalMessage:f?v.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Nn(v.sessionId||v.instanceId,g),machineName:a,connectionState:i})}return n.length===0&&n.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:l,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:c,displayPrimary:c||u,displaySecondary:u,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Nn(e.sessionId||e.instanceId,e.id),connectionState:i}),n}function Cm(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 Im(e,s){const r=Cm(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const nc=[{id:"antigravity",name:"Antigravity",icon:"🌀"},{id:"cursor",name:"Cursor",icon:"⚡"},{id:"kiro",name:"Kiro",icon:"🎯"},{id:"pearai",name:"PearAI",icon:"🍐"},{id:"trae",name:"Trae",icon:"🔮"},{id:"vscode",name:"VS Code",icon:"💙"},{id:"vscodium",name:"VSCodium",icon:"💚"},{id:"windsurf",name:"Windsurf",icon:"🏄"}],ac=[{id:"aider-cli",name:"Aider",icon:"🛠️"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"gemini-cli",name:"Gemini CLI",icon:"✨"},{id:"github-copilot-cli",name:"GitHub Copilot CLI",icon:"🤖"},{id:"goose-cli",name:"Goose",icon:"🪿"},{id:"opencode-cli",name:"OpenCode CLI",icon:"🧩"}],oc=[{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:"🟠"}],Am=nc,Tm=ac,Mm=oc;function vs(...e){return gl(yl(e))}function Lm({icon:e,title:s,subtitle:r,badge:n,actions:a,className:i}){return t.jsxs("div",{className:vs("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 ic({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(Lm,{icon:e,title:s,subtitle:r,badge:n,actions:a}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:vs("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}function Tt({title:e,icon:s,description:r,accentColor:n,className:a,children:i}){return t.jsxs("div",{className:vs("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 cc({icon:e,title:s,description:r,action:n,className:a}){return t.jsxs("div",{className:vs("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 _m={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"},Rm={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function wr({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:vs("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",_m[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:Rm[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 Pm={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"},Dm={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Em({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:vs("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Pm[e],r),children:[t.jsx("span",{className:vs("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Dm[e])}),n]})}const Zn="adhdev:themechange";function $m(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Ss(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Ns(e){return e==="system"?$m():e}function lc(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Pr(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(Zn,{detail:{preference:e,theme:s}}))}function Bm(){const e=Ss(),s=Ns(e);lc(s),Pr(e,s)}function La(){const[e,s]=o.useState(Ss),[r,n]=o.useState(()=>Ns(Ss()));o.useEffect(()=>{lc(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=u=>{if(e==="system"){const p=u.matches?"light":"dark";n(p),Pr("system",p)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=u=>{const p=u.detail||{},m=p.preference,h=p.theme;s(m==="dark"||m==="light"||m==="system"?m:Ss()),n(h==="dark"||h==="light"?h:Ns(Ss()))},l=u=>{if(u.key!=="theme")return;const p=Ss(),m=Ns(p);s(p),n(m)};return window.addEventListener(Zn,c),window.addEventListener("storage",l),()=>{window.removeEventListener(Zn,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=Ns(c);s(c),n(l);try{localStorage.setItem("theme",c)}catch{}Pr(c,l)},[]),i=o.useCallback(()=>{s(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=Ns(l);n(u);try{localStorage.setItem("theme",l)}catch{}return Pr(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const ko={dark:"Dark",light:"Light",system:"System"};function Km({collapsed:e}){const{preference:s,cycleTheme:r}=La(),n=s==="dark"?t.jsx(Zl,{size:16}):s==="light"?t.jsx(Jl,{size:16}):t.jsx(ed,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${ko[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:ko[s]})]})}function os({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 Wm({onPrefChange:e}){const[s,r]=Gd(),[n,a]=o.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);o.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,l)=>{r({[c]:l}),e==null||e(c,l)};return t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(os,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Zr,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:c=>i("globalEnabled",c)}),s.globalEnabled&&t.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&t.jsx(os,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Lt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:c=>i("browserNotifications",c)}),s.globalEnabled&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.jsx("div",{className:"text-[11px] text-text-muted",children:"Browser alerts only fire while this dashboard tab stays open in the background. If you close it, standalone cannot deliver hosted push notifications for you."}),n==="default"&&t.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[t.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),t.jsx("button",{onClick:()=>{Ai().then(a)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:"Allow notifications"})]}),n==="denied"&&t.jsx("div",{className:"text-[11px] text-amber-300",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),n==="unsupported"&&t.jsx("div",{className:"text-[11px] text-amber-300",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),s.globalEnabled&&s.browserNotifications&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.jsx(os,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(td,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:c=>i("completionAlert",c)}),t.jsx(os,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(sd,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:c=>i("approvalAlert",c)}),t.jsx(os,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(or,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!s.globalEnabled&&t.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function Vr(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function Om(e,s){const r=Vr(e),n=Vr(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 dc(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function sr(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||Om(r,s)>=0)return!1;const n=Vr(r),a=Vr(s);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Hm(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Cn(e,s){return e instanceof Error?e.message:s}function Um({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(cc,{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(zm,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function So({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 ar.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 Fm(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Am,...Tm,...Mm].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 zm({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var K,F;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[p,m]=o.useState(null),[h,y]=o.useState("idle"),[k,A]=o.useState(""),d=e.version||null,b=((K=e.machine)==null?void 0:K.platform)||((F=e.system)==null?void 0:F.platform)||"",v=Mt(e,{fallbackId:e.id}),f=b==="win32"?"🪟":b==="darwin"?"🍎":"🐧",C=s.filter(M=>M.daemonId===e.id&&M.transport==="cdp-page"),_=s.filter(M=>M.daemonId===e.id&&M.transport==="pty"),g=s.filter(M=>M.daemonId===e.id&&M.transport==="acp"),I=e.p2p,j=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const M=Hm(await r(e.id,"daemon_upgrade",{}));M.alreadyLatest?(c("done"),u(`Already on v${M.version||"latest"}.`)):M.upgraded||M.success?(c("done"),u(`Upgrade to v${M.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(M.error||"Upgrade failed"))}catch(M){c("error"),u(Cn(M,"Connection lost during upgrade"))}}},w=async()=>{if(m(null),!!n){y("loading");try{await n(e.id),y("done"),A("Machine disconnected.")}catch(M){y("error"),A(Cn(M,"Failed to disconnect"))}}},x=async()=>{if(m(null),!!a){y("loading");try{await a(e.id),y("done"),A("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(M){y("error"),A(Cn(M,"Failed to revoke token"))}}},$="0.8.78",N=dc(e,$),L=sr(e,$),T=C.length+_.length+g.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:f}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-sm",children:v}),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] ${N?"":"bg-bg-secondary"}`,style:N?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",d,!N&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&N&&t.jsx("button",{onClick:j,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${$}`,children:i==="upgrading"?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${L?"↑ Update now":`↑ Update${` to v${$}`}`}`}),n&&t.jsx("button",{onClick:()=>m("disconnect"),disabled:h==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&t.jsx("button",{onClick:()=>m("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),t.jsx(Em,{status:e.status==="online"?"online":"error"})]})]}),t.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[I&&t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${I.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${I.state==="connecting"||I.state==="new"?"animate-pulse":""}`,style:I.state==="connecting"||I.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",I.state==="connected"?"connected":I.state==="connecting"||I.state==="new"?"connecting...":I.state||"off"]}),I.peers!==void 0&&I.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",I.peers," peer",I.peers!==1?"s":"",")"]})]}),I&&T>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),T>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[C.map(M=>{const P=Fm(M.type),O=M.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:P.icon}),t.jsx("span",{children:P.name}),O!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${O?"bg-green-400":"animate-pulse"}`,style:O?void 0:{background:"var(--status-warning)"},title:O?"CDP connected":"CDP connecting..."})]},M.id)}),_.map(M=>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:M.cliName||"CLI"})]},M.id)),g.map(M=>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:M.cliName||"ACP"})]},M.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||k)&&t.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||h==="error"?"text-red-400":i==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:k||l})]}),p==="disconnect"&&t.jsx(So,{title:"🔌 Disconnect Machine",message:`Disconnect "${v}" from ADHDev?
|
|
32
|
+
`).includes(a)))}function mm(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 Ji(e,s={}){return mm(um(e,s),s.sortMode||"recent")}function zr(e){return e?"Resume saved history":"Start fresh"}function Na(e){return e?"Resuming saved history…":"Starting fresh…"}function pm(){return"Start fresh"}function Zi(e,s=!1){return e==="cli"?zr(s):e==="ide"?"Start IDE":"Start ACP session"}function ec(e,s=!1){return e==="cli"?Na(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function fm(){return"Recover hosted runtime"}function hm(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function xm(){return"Open saved history"}function bm(){return"Saved History"}function Ca(){return"Use saved history when you want continuity in the same provider conversation."}function gm(){return"No saved history found yet."}function ym(){return"Refresh saved history"}function vm(){return"Refreshing saved history…"}function us(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function ms(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 Ks(e){return e==="start-fresh"?"Start fresh":"Restart"}function Ws(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Ia(e){return`Resume saved history with ${e}?`}function Aa(){return"Review or change the target workspace before resuming saved history."}function wm(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 Ta({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:u,onClose:p,onNewChat:m,onSwitchSession:h,onRefreshHistory:y,onResumeSavedSession:k}){var w;const A=s.find(x=>x.id===e.routeId),d=(A==null?void 0:A.chats)||[],b=(w=A==null?void 0:A.activeChat)==null?void 0:w.id,v=et(e)&&!Je(e),[f,C]=o.useState(()=>yt()),_=l||f,g=x=>{if(u){u(x);return}C(x)},I=o.useMemo(()=>Ji(a,{textQuery:_.textQuery,workspaceQuery:_.workspaceQuery,modelQuery:_.modelQuery,resumableOnly:_.resumableOnly,sortMode:_.sortMode}),[_.modelQuery,_.resumableOnly,_.sortMode,_.textQuery,_.workspaceQuery,a]),j=t.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[t.jsx("div",{onClick:p,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),t.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[t.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[t.jsxs("div",{children:[t.jsx("h3",{className:"m-0 text-lg font-extrabold",children:v?bm():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:nm(e)}),v&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Ca()})]}),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(Nt,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!v&&t.jsx("button",{onClick:m,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),v?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=>g({..._,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=>g({..._,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=>g({..._,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=>g({..._,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=>g({..._,resumableOnly:x.target.checked})}),"Resume-ready only"]})]}),I.map(x=>{const $=e.providerSessionId===x.providerSessionId,N=$||!x.canResume||!!c;return t.jsxs("button",{type:"button",onClick:()=>{N||!k||k(x)},disabled:N,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"} ${N?"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:wm(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",gs(x.summaryMetadata)?` · ${gs(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:()=>{h(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)),(v&&!i&&I.length===0||!v&&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(Ql,{size:32})}),t.jsx("div",{className:"text-[13px]",children:v?a.length>0?"No saved history matches these filters.":gm():"No recent chat sessions found."})]}),v&&i&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:vm()})})]}),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:y,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(Hs,{size:13})," ",v?ym():"Refresh History"]})})})]})]});return typeof document>"u"?j:ar.createPortal(j,document.body)}const wo={success:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Done"},warning:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Attention"},info:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Update"}};function tc({toasts:e,onDismiss: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=wo[n.type]||wo.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(Nt,{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 jm=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function km(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function Sm(e){return e.sessionId||e.instanceId||e.agentType}function Nn(e,s){return e||s}function jo(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 sc(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=Mt(r,{fallbackId:r.id}));return s}function rc(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 Ma(e,s,r={}){return Nm(e,s,rc(e,r))}function Nm(e,s,r={}){var h,y,k,A,d,b;const n=[],a=r.machineName,i=r.connectionState,c=km(e),l=Ed(e.type,{agentName:e.cliName}),u=et(e)||Je(e)?l:at(e.type),p=Array.isArray(e.childSessions)?e.childSessions.map(v=>{var f,C;return{sessionId:v.id,instanceId:v.id,providerSessionId:v.providerSessionId,transport:v.transport,sessionCapabilities:v.capabilities,agentType:v.providerType,agentName:v.providerName||at(v.providerType),status:v.status,title:v.title,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,messages:((f=v.activeChat)==null?void 0:f.messages)||[],activeModal:((C=v.activeChat)==null?void 0:C.activeModal)||void 0,unread:v.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,inboxBucket:v.inboxBucket,surfaceHidden:v.surfaceHidden}}):[],m=jm(e);if(m){const v=e.sessionId||e.instanceId,f=l,C=(h=e.activeChat)==null?void 0:h.activeModal,_=C&&Array.isArray(C.buttons)&&C.buttons.length>0,g=jt((y=e.activeChat)==null?void 0:y.status,{activeModal:(k=e.activeChat)==null?void 0:k.activeModal})||jt((d=(A=e.agents)==null?void 0:A[0])==null?void 0:d.status)||"idle",I=e.activeChat||{title:"",messages:[]};let j=I.title&&String(I.title).trim()?String(I.title).trim():"";const w=(b=e.activeChat)==null?void 0:b.id,x=e.chats;if(w&&Array.isArray(x)&&x.length>0){const F=x.find(M=>M.id===w||M.id&&String(M.id)===String(w));F!=null&&F.title&&String(F.title).trim()&&(j=String(F.title).trim())}const $=(et(e)||Je(e),e.type),N=(et(e)||Je(e))&&lo(j,f,$)?"":j,L=I.messages||[],T=jo(s,[e.id,v]),K=bo(L,T);n.push({routeId:e.id,sessionId:v,providerSessionId:e.providerSessionId,nativeSessionId:v,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:et(e)?e.mode||"terminal":"chat",agentName:f,agentType:$,status:g,title:N,messages:[...L,...K],resume:e.resume,hostIdeType:!et(e)&&!Je(e)?e.type:void 0,workspaceName:c,displayPrimary:N||c||(et(e)?e.mode==="chat"?f:"Terminal":f),displaySecondary:u,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:_?C.buttons:void 0,modalMessage:_?C.message:void 0,streamSource:"native",tabKey:Nn(v,e.id),machineName:a,connectionState:i})}if(m&&(et(e)||Je(e)))return n;for(const v of p){const f=v.activeModal&&Array.isArray(v.activeModal.buttons)&&v.activeModal.buttons.length>0,C=$d(v),_=Sm(v),g=`${e.id}:${_}`,I=v.title&&String(v.title).trim()||"",j=lo(I,v.agentName,v.agentType)?"":I,w=v.messages||[],x=jo(s,[g,v.sessionId,v.instanceId]),$=bo(w,x);(v.transport==="cdp-webview"||v.sessionId||v.providerSessionId||w.length>0||$.length>0||f||j||!["idle","panel_hidden","disconnected","not_monitored"].includes(C))&&n.push({routeId:e.id,sessionId:v.sessionId||v.instanceId,providerSessionId:v.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:v.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:v.sessionCapabilities,mode:"chat",agentName:v.agentName,agentType:v.agentType,status:C,title:j,messages:[...w,...$],hostIdeType:e.type,workspaceName:c,displayPrimary:j||c||v.agentName||u,displaySecondary:`${u} · ${v.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,lastUpdated:v.lastUpdated||e.lastUpdated,modalButtons:f?v.activeModal.buttons:void 0,modalMessage:f?v.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Nn(v.sessionId||v.instanceId,g),machineName:a,connectionState:i})}return n.length===0&&n.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:l,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:c,displayPrimary:c||u,displaySecondary:u,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Nn(e.sessionId||e.instanceId,e.id),connectionState:i}),n}function Cm(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 Im(e,s){const r=Cm(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const nc=[{id:"antigravity",name:"Antigravity",icon:"🌀"},{id:"cursor",name:"Cursor",icon:"⚡"},{id:"kiro",name:"Kiro",icon:"🎯"},{id:"pearai",name:"PearAI",icon:"🍐"},{id:"trae",name:"Trae",icon:"🔮"},{id:"vscode",name:"VS Code",icon:"💙"},{id:"vscodium",name:"VSCodium",icon:"💚"},{id:"windsurf",name:"Windsurf",icon:"🏄"}],ac=[{id:"aider-cli",name:"Aider",icon:"🛠️"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"gemini-cli",name:"Gemini CLI",icon:"✨"},{id:"github-copilot-cli",name:"GitHub Copilot CLI",icon:"🤖"},{id:"goose-cli",name:"Goose",icon:"🪿"},{id:"opencode-cli",name:"OpenCode CLI",icon:"🧩"}],oc=[{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:"🟠"}],Am=nc,Tm=ac,Mm=oc;function vs(...e){return gl(yl(e))}function Lm({icon:e,title:s,subtitle:r,badge:n,actions:a,className:i}){return t.jsxs("div",{className:vs("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 ic({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(Lm,{icon:e,title:s,subtitle:r,badge:n,actions:a}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:vs("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}function Tt({title:e,icon:s,description:r,accentColor:n,className:a,children:i}){return t.jsxs("div",{className:vs("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 cc({icon:e,title:s,description:r,action:n,className:a}){return t.jsxs("div",{className:vs("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 _m={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"},Rm={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function wr({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:vs("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",_m[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:Rm[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 Pm={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"},Dm={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Em({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:vs("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Pm[e],r),children:[t.jsx("span",{className:vs("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Dm[e])}),n]})}const Zn="adhdev:themechange";function $m(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Ss(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Ns(e){return e==="system"?$m():e}function lc(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Pr(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(Zn,{detail:{preference:e,theme:s}}))}function Bm(){const e=Ss(),s=Ns(e);lc(s),Pr(e,s)}function La(){const[e,s]=o.useState(Ss),[r,n]=o.useState(()=>Ns(Ss()));o.useEffect(()=>{lc(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=u=>{if(e==="system"){const p=u.matches?"light":"dark";n(p),Pr("system",p)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=u=>{const p=u.detail||{},m=p.preference,h=p.theme;s(m==="dark"||m==="light"||m==="system"?m:Ss()),n(h==="dark"||h==="light"?h:Ns(Ss()))},l=u=>{if(u.key!=="theme")return;const p=Ss(),m=Ns(p);s(p),n(m)};return window.addEventListener(Zn,c),window.addEventListener("storage",l),()=>{window.removeEventListener(Zn,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=Ns(c);s(c),n(l);try{localStorage.setItem("theme",c)}catch{}Pr(c,l)},[]),i=o.useCallback(()=>{s(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=Ns(l);n(u);try{localStorage.setItem("theme",l)}catch{}return Pr(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const ko={dark:"Dark",light:"Light",system:"System"};function Km({collapsed:e}){const{preference:s,cycleTheme:r}=La(),n=s==="dark"?t.jsx(Zl,{size:16}):s==="light"?t.jsx(Jl,{size:16}):t.jsx(ed,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${ko[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:ko[s]})]})}function os({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 Wm({onPrefChange:e}){const[s,r]=Gd(),[n,a]=o.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);o.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,l)=>{r({[c]:l}),e==null||e(c,l)};return t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(os,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Zr,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:c=>i("globalEnabled",c)}),s.globalEnabled&&t.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&t.jsx(os,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Lt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:c=>i("browserNotifications",c)}),s.globalEnabled&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.jsx("div",{className:"text-[11px] text-text-muted",children:"Browser alerts only fire while this dashboard tab stays open in the background. If you close it, standalone cannot deliver hosted push notifications for you."}),n==="default"&&t.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[t.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),t.jsx("button",{onClick:()=>{Ai().then(a)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:"Allow notifications"})]}),n==="denied"&&t.jsx("div",{className:"text-[11px] text-amber-300",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),n==="unsupported"&&t.jsx("div",{className:"text-[11px] text-amber-300",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),s.globalEnabled&&s.browserNotifications&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.jsx(os,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(td,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:c=>i("completionAlert",c)}),t.jsx(os,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(sd,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:c=>i("approvalAlert",c)}),t.jsx(os,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(or,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!s.globalEnabled&&t.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function Vr(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function Om(e,s){const r=Vr(e),n=Vr(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 dc(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function sr(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||Om(r,s)>=0)return!1;const n=Vr(r),a=Vr(s);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Hm(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Cn(e,s){return e instanceof Error?e.message:s}function Um({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(cc,{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(zm,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function So({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 ar.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 Fm(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Am,...Tm,...Mm].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 zm({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var K,F;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[p,m]=o.useState(null),[h,y]=o.useState("idle"),[k,A]=o.useState(""),d=e.version||null,b=((K=e.machine)==null?void 0:K.platform)||((F=e.system)==null?void 0:F.platform)||"",v=Mt(e,{fallbackId:e.id}),f=b==="win32"?"🪟":b==="darwin"?"🍎":"🐧",C=s.filter(M=>M.daemonId===e.id&&M.transport==="cdp-page"),_=s.filter(M=>M.daemonId===e.id&&M.transport==="pty"),g=s.filter(M=>M.daemonId===e.id&&M.transport==="acp"),I=e.p2p,j=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const M=Hm(await r(e.id,"daemon_upgrade",{}));M.alreadyLatest?(c("done"),u(`Already on v${M.version||"latest"}.`)):M.upgraded||M.success?(c("done"),u(`Upgrade to v${M.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(M.error||"Upgrade failed"))}catch(M){c("error"),u(Cn(M,"Connection lost during upgrade"))}}},w=async()=>{if(m(null),!!n){y("loading");try{await n(e.id),y("done"),A("Machine disconnected.")}catch(M){y("error"),A(Cn(M,"Failed to disconnect"))}}},x=async()=>{if(m(null),!!a){y("loading");try{await a(e.id),y("done"),A("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(M){y("error"),A(Cn(M,"Failed to revoke token"))}}},$="0.8.79",N=dc(e,$),L=sr(e,$),T=C.length+_.length+g.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:f}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-sm",children:v}),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] ${N?"":"bg-bg-secondary"}`,style:N?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",d,!N&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&N&&t.jsx("button",{onClick:j,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${$}`,children:i==="upgrading"?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${L?"↑ Update now":`↑ Update${` to v${$}`}`}`}),n&&t.jsx("button",{onClick:()=>m("disconnect"),disabled:h==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&t.jsx("button",{onClick:()=>m("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),t.jsx(Em,{status:e.status==="online"?"online":"error"})]})]}),t.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[I&&t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${I.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${I.state==="connecting"||I.state==="new"?"animate-pulse":""}`,style:I.state==="connecting"||I.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",I.state==="connected"?"connected":I.state==="connecting"||I.state==="new"?"connecting...":I.state||"off"]}),I.peers!==void 0&&I.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",I.peers," peer",I.peers!==1?"s":"",")"]})]}),I&&T>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),T>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[C.map(M=>{const P=Fm(M.type),O=M.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:P.icon}),t.jsx("span",{children:P.name}),O!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${O?"bg-green-400":"animate-pulse"}`,style:O?void 0:{background:"var(--status-warning)"},title:O?"CDP connected":"CDP connecting..."})]},M.id)}),_.map(M=>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:M.cliName||"CLI"})]},M.id)),g.map(M=>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:M.cliName||"ACP"})]},M.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||k)&&t.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||h==="error"?"text-red-400":i==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:k||l})]}),p==="disconnect"&&t.jsx(So,{title:"🔌 Disconnect Machine",message:`Disconnect "${v}" from ADHDev?
|
|
33
33
|
|
|
34
34
|
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
35
35
|
|
|
@@ -40,7 +40,7 @@ This will:
|
|
|
40
40
|
• Delete the machine registration
|
|
41
41
|
• Require restarting ADHDev on that machine
|
|
42
42
|
|
|
43
|
-
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:x,onCancel:()=>m(null)})]})}const Vm=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Gm(){const{preference:e,setPreference:s}=La();return t.jsx("div",{className:"flex gap-2",children:Vm.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 qm(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 Ym(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function In(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function No(e){const{r:s,g:r,b:n}=Ym(e);return .2126*In(s)+.7152*In(r)+.0722*In(n)}function Co(e,s){const r=No(e),n=No(s),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function uc(e){const s=qm(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return Co(s,r)>=Co(s,n)?r:n}const ea={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},ta={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},Xm=[{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"}}}],mc="adhdev-chat-theme",pc="adhdev-chat-theme-custom";function Dr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(mc)||"ember"}catch{return"ember"}}function $t(e){try{const s=localStorage.getItem(pc);if(s){const r=JSON.parse(s);return{...e==="dark"?ea:ta,...r[e]}}}catch{}return e==="dark"?ea:ta}function jr(e,s){try{localStorage.setItem(pc,JSON.stringify({dark:e,light:s}))}catch{}}function Rt(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 Gr(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 Qm={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function rr(e,s){var a;const r=(a=Qm[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",Gr(r,24)),n.style.setProperty("--accent-on-primary",uc(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Gr(r,18)})`),n.style.setProperty("--border-accent",Rt(r,.35)),n.style.setProperty("--nav-active-bg",Rt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Rt(r,.06)}`)}function ps(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",Rt(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",Rt(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",Rt(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",Rt(e.borderSubtle,.5)),s.style.setProperty("--border-default",Rt(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",Gr(e.accentColor,30)),s.style.setProperty("--accent-on-primary",uc(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Gr(e.accentColor,40)})`),s.style.setProperty("--border-accent",Rt(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",Rt(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Rt(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 ${Rt(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 _a(){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 Jm(e){try{localStorage.setItem(mc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=fs()?"dark":"light";ps($t(s))}else _a(),rr(e,fs()?"dark":"light")}function Zm(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Dr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=fs()?"dark":"light";ps($t(s))}else _a(),rr(e,fs()?"dark":"light")}function fs(){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 qs({title:e,children:s}){return t.jsxs("div",{style:{marginBottom:14},children:[t.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s})]})}function ep({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,a]=o.useState(()=>$t(r));o.useEffect(()=>{a($t(r))},[r]);const i=o.useCallback((c,l)=>{a(u=>{const p={...u,[c]:l},h=$t(r==="dark"?"light":"dark");return r==="dark"?jr(p,h):jr(h,p),ps(p),s(p),p})},[r,s]);return t.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[t.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",t.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsxs(qs,{title:"App Background",children:[t.jsx(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(qs,{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(qs,{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(qs,{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(qs,{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?ea:ta,u=$t(e?"light":"dark");e?jr(c,u):jr(u,c),a(c),ps(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 tp(){const[e,s]=o.useState(Dr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>$t("dark"));o.useEffect(()=>{n(fs());const u=new MutationObserver(()=>{const h=fs();n(h);const y=Dr();y==="custom"?ps($t(h?"dark":"light")):rr(y,h?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const p=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const h=fs();n(h);const y=Dr();y==="custom"?ps($t(h?"dark":"light")):rr(y,h?"dark":"light")};return p.addEventListener("change",m),()=>{u.disconnect(),p.removeEventListener("change",m)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?ps($t(r?"dark":"light")):(_a(),rr(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i($t(r?"dark":"light"))},[r]);const c=u=>{s(u),Jm(u)},l=[...Xm,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return t.jsxs("div",{children:[t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:l.map(u=>{const p=e===u.id,m=r?u.preview.dark:u.preview.light,h=u.id==="honey"||u.id==="ember"?"#1a1a1a":u.id==="custom"?a.userText:"#fff";return t.jsxs("button",{onClick:()=>c(u.id),className:"text-left rounded-xl p-3 transition-all",style:{background:p?"var(--bg-glass-hover)":"var(--bg-glass)",border:p?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:p?1:.75},children:[t.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:"Hello! How can I help?"}),t.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.userBubble,color:h},children:"Fix the bug please"}),t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:"On it! ✨"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[p&&t.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:u.id==="custom"?"🎨 Custom":u.name}),t.jsx("div",{className:"text-[10px] text-text-muted",children:u.description})]})]})]},u.id)})}),e==="custom"&&t.jsx(ep,{dark:r,onColorsChange:u=>i(u)})]})}const fc="adhdev_mobileDashboardMode_v1";function hc(){try{return localStorage.getItem(fc)==="workspace"?"workspace":"chat"}catch{return"chat"}}function sp(e){try{localStorage.setItem(fc,e)}catch{}}function rp(){const[e,s]=o.useState(!0);return o.useEffect(()=>{s(hc()==="chat")},[]),t.jsx(os,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Vt,{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),sp(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}function np(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 ap(e,s){const{sendData:r}=Dt(),{injectEntries:n,getIdes:a}=Wr(),i=Array.from(new Set(e.filter(Boolean))).join("|");o.useEffect(()=>{if(!(s!=null&&s.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const l=c.map(u=>es.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:s==null?void 0:s.intervalMs}},p=>{const m=a().find(y=>y.id===u),h=np(m,u,p);n([h])}));return()=>{l.forEach(u=>u())}},[i,a,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}const op=4e3;function xc(e,s){const{sendData:r}=Dt(),[n,a]=o.useState(null),[i,c]=o.useState(!1);return o.useEffect(()=>{if(!e){a(null),c(!1);return}if(!(s!=null&&s.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const u=es.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(s==null?void 0:s.includeSessions)!==!1,...typeof(s==null?void 0:s.limit)=="number"?{limit:s.limit}:{},...typeof(s==null?void 0:s.intervalMs)=="number"?{intervalMs:s.intervalMs}:{}}},p=>{l&&(clearTimeout(l),l=null),a(p.diagnostics),c(!1)});return u.initialSendAccepted?l=setTimeout(()=>{c(!1)},op):c(!1),()=>{l&&clearTimeout(l),u()}},[e,s==null?void 0:s.enabled,s==null?void 0:s.includeSessions,s==null?void 0:s.intervalMs,s==null?void 0:s.limit,r]),{diagnostics:n,loading:i,applyDiagnostics:a}}function ip(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function bc(e){const{sendData:s}=Dt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=ip(e);if(!a||!e.sessionId||!s){n({});return}const i=es.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}),_s.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 gc="adhdev_hiddenTabs";function cp(){try{const e=localStorage.getItem(gc);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function js(e){try{localStorage.setItem(gc,JSON.stringify([...e]))}catch{}}function lp(){const[e,s]=o.useState(cp),r=o.useCallback(p=>{s(m=>{const h=new Set(m);return h.has(p)?h.delete(p):h.add(p),js(h),h})},[]),n=o.useCallback(p=>{s(m=>{if(m.has(p))return m;const h=new Set(m);return h.add(p),js(h),h})},[]),a=o.useCallback(p=>{s(m=>{if(!m.has(p))return m;const h=new Set(m);return h.delete(p),js(h),h})},[]),i=o.useCallback(()=>{s(p=>{if(p.size===0)return p;const m=new Set;return js(m),m})},[]),c=o.useCallback((p,m)=>{s(h=>{const y=new Set(h);for(const k of m)y.add(k);return js(y),y})},[]),l=o.useCallback((p,m)=>{s(h=>{const y=new Set(h);for(const k of m)y.delete(k);return js(y),y})},[]),u=o.useCallback(p=>e.has(p),[e]);return{hiddenTabs:e,toggleTab:r,hideTab:n,showTab:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function Io(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 dp(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=Io(a,s),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>Io(u,s)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function yc(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 up(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))yc(s,a)===i&&(delete n[a],r=!0);return r?n:e}function mp({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{Ai()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:Xi(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Xd(a),o.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(l=>{const u=Date.now(),p={};for(const[m,h]of Object.entries(l))u-h<5e3&&(p[m]=h);return Object.keys(p).length===Object.keys(l).length?l:p})},5500);return()=>clearTimeout(c)},[s,r]),o.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const u=l.filter(p=>p.timestamp>c).slice(-100);return u.length===l.length?l:u})},6e4);return()=>clearInterval(i)},[n]),null}function pp(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 An(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 fp(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?fp(Ps(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 hp(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 xp(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 bp(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 gp(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 yp(e,s){const r=new Map;for(const n of e){const a=s.get(n.routeId)||n;for(const i of is({routeId:n.routeId}))r.set(i,a);for(const i of is({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of is({tabKey:n.tabKey}))r.set(i,n)}return r}function vp(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function wp(e){const s=vp(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=Ps(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function jp({ides:e,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:a}){const i=o.useMemo(()=>pp(e),[e]),c=o.useMemo(()=>sc(e),[e]),l=o.useRef([]),u=o.useRef([]),p=o.useRef([]),m=o.useRef(new Map),h=o.useRef(new Map),y=o.useMemo(()=>{const g=new Map,I=[];for(const $ of i){const{connectionState:N="new",machineName:L}=rc($,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),T=bp($,r),K=hp($),F=m.current.get($.id);if(F&&F.ide===$&&F.sourceSignature===K&&F.connectionState===N&&F.machineName===L&&gp(F.localRefs,T)){g.set($.id,F),I.push(...F.conversations);continue}const M=Ma($,r,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),P={ide:$,sourceSignature:K,connectionState:N,machineName:L,localRefs:T,conversations:M};g.set($.id,P),I.push(...M)}m.current=g;const j=new Map,w=$=>{const N=wp($),L=h.current.get($.tabKey);if(L&&L.signature===N)return j.set($.tabKey,L),L.timestamp;const T={signature:N,timestamp:$i($)||(L==null?void 0:L.timestamp)||0};return j.set($.tabKey,T),T.timestamp},x=[...I].sort(($,N)=>Bi($,N,w));return h.current=j,x},[i,r,s,c]),k=o.useMemo(()=>{const g=xp(y,n);return An(l.current,g)?l.current:(l.current=g,g)},[y,n]),A=o.useMemo(()=>{const g=new Map,I=Array.from(new Set(k.map(j=>j.routeId)));for(const j of I){const w=Bt(k,j);w&&g.set(j,w)}return g},[k]),d=o.useMemo(()=>{const g=new Map;for(const I of k){const j=A.get(I.routeId),w=I.streamSource==="native"&&j?j:I;for(const x of is({providerSessionId:I.providerSessionId,sessionId:I.sessionId}))g.set(x,w)}return g},[k,A]),b=o.useMemo(()=>yp(k,A),[k,A]),v=o.useCallback(g=>{if(g)return d.get(g)},[d]),f=o.useCallback(g=>{if(g)return b.get(g)},[b]),C=o.useMemo(()=>{const g=k.filter(I=>!a.has(I.tabKey));return An(u.current,g)?u.current:(u.current=g,g)},[k,a]),_=o.useMemo(()=>{const g=C.map(I=>I.tabKey);return An(p.current,g)?p.current:(p.current=g,g)},[C]);return{chatIdes:i,conversations:k,visibleConversations:C,visibleTabKeys:_,resolveConversationBySessionId:v,resolveConversationByTarget:f}}function kp({isMobile:e,urlActiveTab:s,resolveConversationBySessionId:r,setSearchParams:n}){const a=o.useMemo(()=>{var l;return e||!s?null:((l=r(s))==null?void 0:l.tabKey)??null},[e,r,s]),i=o.useMemo(()=>{var l;return!e||!s?null:((l=r(s))==null?void 0:l.tabKey)??null},[e,r,s]),c=o.useCallback(()=>{s&&n(l=>{const u=new URLSearchParams(l);return u.delete("activeTab"),u},{replace:!0})},[n,s]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function Sp({ides:e,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:a}){o.useEffect(()=>{lt.setIdes(e)},[e]),o.useEffect(()=>{lt.setResolveAction((i,c,l)=>{s(i,c,l).catch(()=>{})})},[s]),o.useEffect(()=>{const i=lt.onToast(u=>{r(m=>m.some(y=>y.message===u.message&&u.timestamp-y.timestamp<3e3)?m:[...m.slice(-4),{id:u.id,message:u.message,type:u.type,timestamp:u.timestamp,targetKey:u.targetKey,actions:u.actions}]);const p=u.duration||5e3;setTimeout(()=>r(m=>m.filter(h=>h.id!==u.id)),p)}),c=lt.onSystemMessage((u,p)=>{var k,A;const m=a(u),h=(k=p._localId)==null?void 0:k.startsWith("sys_approval_"),y=!!(m&&(m.status==="waiting_approval"||(A=m.modalButtons)!=null&&A.length||m.modalMessage));h&&y||n(d=>({...d,[u]:[...d[u]||[],p]}))}),l=lt.onClearSystemMessage((u,p)=>{n(m=>{var h;return(h=m[u])!=null&&h.length?{...m,[u]:m[u].filter(y=>{var k;return!(y.role==="system"&&((k=y._localId)!=null&&k.startsWith(p)))})}:m})});return()=>{i(),c(),l()}},[r,n]),o.useEffect(()=>{const i=Vi.on("status_event",c=>{lt.handleRawEvent(c,"ws")});return()=>{i()}},[]),o.useEffect(()=>{var c;const i=l=>{var b;const u=l.data;if((u==null?void 0:u.type)!=="notification_action"||typeof u.action!="string"||!u.action.startsWith("approval_")||!(u.daemonId||u.targetSessionId||u.targetKey))return;const p=u.targetSessionId||u.targetKey||u.daemonId,m=a(p),h=(m==null?void 0:m.routeId)||u.daemonId;if(!h)return;const y=Number(u.buttonIndex),k=u.button||((b=m==null?void 0:m.modalButtons)==null?void 0:b[y])||"Approve",A=String(k).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),d=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(A);s(h,"resolve_action",{action:d?"approve":"reject",button:k,...Number.isFinite(y)&&{buttonIndex:y},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...u.targetSessionId&&{targetSessionId:u.targetSessionId}}).catch(v=>console.error("[SW Action] approval failed:",v))};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 Np="adhdev_dashboardLayout_v1",Cp="adhdev_dashboardDockview_v1",Ip="adhdev_dashboardDockviewHiddenRestore_v1",Ys={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Ra(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function vc(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function wc(e){return`${Np}:${e}`}function Ap(e){const s=wc(e);return Ra(s,null)}function Tp(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=wc(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function jc(e){return`${Cp}:${e}`}function Mp(e){const s=jc(e);return Ra(s,null)}function Lp(e,s){try{const r=jc(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function kc(e){return`${Ip}:${e}`}function _p(e){const s=kc(e);return Ra(s,{})}function Rp(e,s){try{const r=kc(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Pp(){return{groupAssignments:[...Ys.groupAssignments],focusedGroup:Ys.focusedGroup,groupActiveTabIds:{...Ys.groupActiveTabIds},groupTabOrders:{...Ys.groupTabOrders},groupSizes:[...Ys.groupSizes]}}function Dp(){const[e]=o.useState(()=>vc(typeof window<"u"?window.innerWidth:1280)),[s,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,u]=o.useState({}),[p,m]=o.useState([]),[h,y]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[k,A]=o.useState(!1),d=o.useCallback(()=>{if(k)return;const b=Ap(e)??Pp();r(new Map(b.groupAssignments)),a(b.focusedGroup),c(b.groupActiveTabIds),u(b.groupTabOrders),m(b.groupSizes),A(!0)},[k,e]);return o.useEffect(()=>{k&&Tp(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:p})},[k,e,s,n,i,l,p]),o.useEffect(()=>{const b=window.matchMedia("(max-width: 767px)"),v=f=>y(f.matches);return b.addEventListener("change",v),()=>b.removeEventListener("change",v)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:a,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:l,setGroupTabOrders:u,groupSizes:p,setGroupSizes:m,isMobile:h,hasHydratedStoredLayout:k,hydrateStoredLayout:d}}function Ep(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=ha(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function $p({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:l,setSearchParams:u,historyModalOpen:p,activeConv:m,isRefreshingHistory:h,ides:y,handleRefreshHistory:k}){const A=o.useRef(!1),d=o.useRef(!1),b=o.useRef(null),v=o.useRef(!1);o.useEffect(()=>{if(!e||A.current||s.length===0)return;if(!a){i();return}const f=r(e);if(!f)return;const C=n.get(f.tabKey)??0;c(_=>({..._,[C]:f.tabKey})),l(C),A.current=!0,d.current=!0,b.current!=null&&(window.clearTimeout(b.current),b.current=null),u(_=>{const g=new URLSearchParams(_);return g.delete("activeTab"),g},{replace:!0})},[e,s,r,n,a,i,c,l,u]),o.useEffect(()=>{if(!(d.current||a)&&s.length!==0){if(!e){i(),d.current=!0;return}if(A.current){d.current=!0;return}if(b.current==null)return b.current=window.setTimeout(()=>{b.current=null,!(d.current||a)&&(i(),d.current=!0)},1500),()=>{b.current!=null&&(window.clearTimeout(b.current),b.current=null)}}},[e,s.length,a,i]),o.useEffect(()=>{if(!p){v.current=!1;return}if(!m||v.current||h)return;const f=y.find(C=>C.id===m.routeId);f&&(!f.chats||f.chats.length===0||Ep(f.chats,m))&&(v.current=!0,k())},[p,m,h,y,k]),o.useEffect(()=>{if(!m)return;let f=null,C=0,_=-1,g=0;const I=()=>{f=null;const j=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(x=>x.offsetParent!==null);if(j.length===0){C<18&&(C+=1,f=requestAnimationFrame(I));return}let w=0;for(const x of j)x.scrollTop=x.scrollHeight,w+=x.scrollHeight;w===_?g+=1:(g=0,_=w),C+=1,!(g>=2||C>=18)&&(f=requestAnimationFrame(I))};return f=requestAnimationFrame(I),()=>{f!=null&&cancelAnimationFrame(f)}},[m==null?void 0:m.tabKey])}function Bp({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[u,p]=o.useState(null),[m,h]=o.useState(null),y=o.useMemo(()=>{if(e||!n)return null;const v=l(n);return v&&!et(v)&&!Je(v)?v:null},[e,n,l]),k=o.useMemo(()=>{const v=u==null?void 0:u.routeId;if(!v)return null;const f=u!=null&&u.tabKey?i.find(C=>C.tabKey===u.tabKey):a?i.find(C=>C.tabKey===a):null;return(f==null?void 0:f.routeId)===v?f:Bt(i,v)},[i,u,a]),A=o.useMemo(()=>{if(k)return c.find(v=>v.id===k.routeId)},[c,k]);o.useEffect(()=>{y&&(p({routeId:y.routeId,tabKey:po(y)}),h(y),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,y]);const d=o.useCallback(v=>{v&&(p({routeId:v.routeId,tabKey:po(v)}),h(v))},[]),b=o.useCallback(()=>{p(null),h(null)},[]);return{remoteDialogConv:k,remoteDialogIdeEntry:A,remoteDialogActiveConv:m,setRemoteDialogActiveConv:h,openRemoteDialog:d,closeRemoteDialog:b}}function Tn(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=ha(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function To({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:a,setLocalUserMessages:i,setClearedTabs:c}){const[l,u]=o.useState(!1),[p,m]=o.useState(!1),h=o.useCallback(async d=>{try{await e("standalone","launch_ide",{ideType:d,enableCdp:!0})}catch(b){console.error("Launch failed",b)}},[e]),y=o.useCallback(async(d,b)=>{try{const v=d||(s==null?void 0:s.daemonId)||"",f=await e(v,"switch_chat",{id:b,sessionId:b,...Ms(s)}),C=f==null?void 0:f.result;if((f==null?void 0:f.success)===!0||C==="switched"||C==="switched-by-title")return;C===!1||C==="not_found"?Gs(a,"⚠️ Session tab not found — try refreshing history"):typeof C=="string"&&C.startsWith("error:")?Gs(a,`⚠️ Switch error: ${C}`):Gs(a,"⚠️ Session switch failed")}catch(v){console.error("Switch failed",v),Gs(a,`❌ Switch failed: ${v.message||"connection error"}`)}},[s,e,a]),k=o.useCallback(async()=>{if(!(!s||l)){u(!0);try{const d=lr(s);await e(d,"new_chat",{...Ms(s)}),c(b=>({...b,[s.tabKey]:Date.now()})),i(b=>({...b,[s.tabKey]:[]}))}catch(d){console.error("New chat failed",d)}finally{u(!1)}}},[s,l,e,c,i]),A=o.useCallback(async()=>{var d,b;if(!(!s||p)){m(!0);try{const v=lr(s),f=async()=>e(v,"list_chats",{forceExpand:!0,...Ms(s)});let C=await f(),_=(C==null?void 0:C.chats)||((d=C==null?void 0:C.result)==null?void 0:d.chats);Tn(_,s)&&(await new Promise(g=>setTimeout(g,450)),C=await f(),_=(C==null?void 0:C.chats)||((b=C==null?void 0:C.result)==null?void 0:b.chats)),C!=null&&C.success&&Array.isArray(_)&&(n(s.routeId,_),Tn(_,s)&&!Tn(r,s)&&Gs(a,"⚠️ History dialog did not fully open — try once more"))}catch(v){console.error("Refresh history failed",v)}finally{m(!1)}}},[s,r,p,e,n,a]);return{isCreatingChat:l,isRefreshingHistory:p,handleLaunchIde:h,handleSwitchSession:y,handleNewChat:k,handleRefreshHistory:A}}function Kp(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 Wp(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function Mo(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 kr(e,s){const r=new Set(s),n=s.length>0?[0]:[];for(const[c,l]of e)!r.has(c)||l<=0||n.includes(l)||n.push(l);n.sort((c,l)=>c-l);const a={};n.forEach((c,l)=>{a[c]=l}),n.length===0&&(a[0]=0);const i=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const u=a[l];typeof u=="number"&&u>0&&i.set(c,u)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function Lo(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 Op(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 Hp(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 _o(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 Ro(e){return Array(e).fill(100/e)}function Up({groupAssignments:e,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:a,groupSizes:i,setGroupSizes:c,isMobile:l,visibleConversations:u,visibleTabKeys:p}){const m=o.useRef(null),h=o.useMemo(()=>kr(e,p),[e,p]),y=h.assignments,k=o.useMemo(()=>l?1:h.groupCount,[h.groupCount,l]),A=k>1,d=o.useCallback((g,I)=>{s(j=>{const w=new Map(kr(j,p).assignments);return I===0?w.delete(g):w.set(g,I),w}),n(j=>({...j,[I]:g})),r(I)},[s,p,n,r]),b=o.useCallback(g=>{s(I=>{const j=kr(I,p).assignments,w=new Map;for(const[x,$]of j)$!==g&&($>g?w.set(x,$-1):w.set(x,$));return w}),c(I=>{if(I.length<=1)return[];const j=[...I];j.splice(g,1);const w=j.reduce((x,$)=>x+$,0);return w>0?j.map(x=>x/w*100):[]}),r(0)},[s,p,c,r]),v=o.useCallback((g,I)=>{I.preventDefault();const j=m.current;if(!j)return;const w=I.clientX,x=j.offsetWidth,$=i.length===k?[...i]:Ro(k),N=T=>{const F=(T.clientX-w)/x*100,M=[...$];M[g]=Math.max(15,$[g]+F),M[g+1]=Math.max(15,$[g+1]-F),c(M)},L=()=>{document.removeEventListener("mousemove",N),document.removeEventListener("mouseup",L),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",N),document.addEventListener("mouseup",L)},[i,k,c]),f=o.useCallback((g,I,j)=>{if(k>=4)return;const w=j==="left"?I:I+1;s(x=>{const $=kr(x,p).assignments,N=new Map;for(const L of u){const T=$.get(L.tabKey)??0,K=T>=w?T+1:T;K>0&&N.set(L.tabKey,K)}return w>0&&N.set(g,w),N}),c(x=>{const $=x.length===k?[...x]:Ro(k),N=$[I]??100/k,L=Math.max(15,N/2),T=Math.max(15,N/2),K=[...$];K[I]=L,K.splice(w,0,T);const F=K.reduce((M,P)=>M+P,0);return K.map(M=>M/F*100)}),n(x=>{const $=_o(x,w);return $[w]=g,$}),a(x=>{const $=_o(x,w);return $[w]=[g],$}),r(w)},[k,s,p,u,c,n,a,r]);o.useEffect(()=>{Kp(e,y)||s(y)},[e,y,s]),o.useEffect(()=>{const{mapping:g,usedGroups:I}=h;n(j=>{const w=Lo(j,g);return Mo(j,w)?j:w}),a(j=>{const w=Lo(j,g);return Mo(j,w)?j:w}),r(j=>{const w=l?0:Op(j,I,g);return j===w?j:w}),c(j=>{const w=l?[]:Hp(j,I,h.groupCount);return Wp(j,w)?j:w})},[h,l,n,a,r,c]);const C=o.useMemo(()=>{const g=Array.from({length:k},()=>[]);for(const I of u){const j=y.get(I.tabKey)??0,w=Math.min(j,k-1);g[w].push(I)}return g},[u,y,k]),_=o.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:m,normalizedGroupAssignments:y,numGroups:k,isSplitMode:A,groupedConvs:C,moveTabToGroup:d,closeGroup:b,handleResizeStart:v,splitTabRelative:f,clearAllSplits:_}}function Fp({ides:e,sendDaemonCommand:s}){const r="0.8.78",n=o.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:dc(m,r)).sort((m,h)=>Number(sr(h,r))-Number(sr(m,r))),[r,e]),a=o.useMemo(()=>n.some(m=>sr(m,r)),[r,n]),[i,c]=o.useState(!1),[l,u]=o.useState({}),p=o.useCallback(async m=>{var h,y;u(k=>({...k,[m]:"upgrading"}));try{const k=await s(m,"daemon_upgrade",{});(h=k==null?void 0:k.result)!=null&&h.upgraded||(y=k==null?void 0:k.result)!=null&&y.success?u(A=>({...A,[m]:"done"})):u(A=>({...A,[m]:"error"}))}catch{u(k=>({...k,[m]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:p}}const sa="adhdev_dashboard_notifications_v1",Pa=80;function Er(e,s=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:s}function qr(e){return{...e,createdAt:Er(e.createdAt),updatedAt:Er(e.updatedAt,e.createdAt),lastEventAt:Er(e.lastEventAt,e.updatedAt||e.createdAt)}}function zp(e){const s=yi(e);return s==="unknown:"?e.id:s}function Vp(e){return[e.type,gi(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Gp(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 u=Er(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),p=Vp({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(qr({id:p,dedupKey:p,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Pi(a),preview:yu(a),createdAt:u,updatedAt:u,lastEventAt:u}))}return n.sort((a,i)=>i.updatedAt-a.updatedAt)}function qp(e,s,r=Pa){const n=new Map;for(const i of e)i.deletedAt||n.set(i.id,qr(i));for(const i of s){const c=qr(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=zp(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 Yp(e,s,r=Date.now()){return e.map(n=>n.id===s?{...n,readAt:r,updatedAt:Math.max(n.updatedAt,r)}:n)}function Xp(e,s){return e.map(r=>{if(r.id!==s)return r;const n={...r};return delete n.readAt,n})}function Qp(e,s,r=Date.now()){return e.map(n=>Or(n,s)?{...n,readAt:r,updatedAt:Math.max(n.updatedAt,r)}:n)}function Jp(e,s){return e.filter(r=>r.id!==s)}function Zp(e){return e.filter(s=>!s.readAt&&!s.deletedAt).length}function ef(e){const s=new Map;for(const r of e){if(r.deletedAt)continue;const n=is(r);if(n.length===0)continue;const a=r.readAt?0:1;for(const i of n){const c=s.get(i);if(!c){s.set(i,{unreadCount:a,latestNotificationAt:r.updatedAt,latestRecordId:r.id});continue}s.set(i,{unreadCount:c.unreadCount+a,latestNotificationAt:Math.max(c.latestNotificationAt,r.updatedAt),latestRecordId:c.latestNotificationAt>=r.updatedAt?c.latestRecordId:r.id})}}return s}function tf(){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(sa),s=e?JSON.parse(e):[];return Array.isArray(s)?s.map(r=>qr(r)).filter(r=>!r.deletedAt):[]}catch{return[]}}function sf(e){if(!(typeof window>"u"))try{const s=e.filter(r=>!r.deletedAt).slice(0,Pa);if(s.length===0){window.localStorage.removeItem(sa);return}window.localStorage.setItem(sa,JSON.stringify(s))}catch{}}function rf(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 nf(e){const{conversations:s,liveSessionInboxState:r,maxItems:n=Pa}=e,a=o.useMemo(()=>Gp(s,r),[s,r]),[i,c]=o.useState(()=>tf());o.useEffect(()=>{c(k=>{const A=qp(k,a,n);return rf(k,A)?k:A})},[a,n]),o.useEffect(()=>{sf(i)},[i]);const l=o.useMemo(()=>Zp(i),[i]),u=o.useMemo(()=>ef(i),[i]),p=o.useCallback((k,A)=>{c(d=>Yp(d,k,A))},[]),m=o.useCallback(k=>{c(A=>Xp(A,k))},[]),h=o.useCallback((k,A)=>{c(d=>Qp(d,k,A))},[]),y=o.useCallback(k=>{c(A=>Jp(A,k))},[]);return{notifications:i,unreadCount:l,notificationStateBySessionId:u,markRead:p,markUnread:m,markTargetRead:h,deleteNotification:y}}function Sc(){return"select_session"}function af(){return"open_panel"}function of({hasMessage:e,blockedMessage:s}){return e?!!s:!0}function cf(e,s,r=2e3){return e?e.tabKey===s.tabKey&&e.message===s.message&&s.timestamp-e.timestamp<r:!1}function Po(e,s){return e?e.tabKey===s.tabKey&&e.message===s.message&&e.timestamp===s.timestamp?null:e:null}function Do(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Da(e){return e instanceof Error?e.message:String(e||"")}function Eo(e){const s=Da(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function $o(e,s){const r=Da(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function on({sendDaemonCommand:e,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:a}){const[i,c]=o.useState(!1),[l,u]=o.useState(!1),[p,m]=o.useState(null),h=o.useRef(!1),y=o.useRef(null);o.useEffect(()=>{m(null)},[s==null?void 0:s.tabKey]);const k=o.useCallback(async v=>{if(!s)return!1;const f=v.trim(),C=ka(s);if(of({hasMessage:!!f,blockedMessage:C,sendInFlight:h.current}))return C&&m(C),!1;const _=Date.now(),g={tabKey:s.tabKey,message:f,timestamp:_};if(cf(y.current,g))return m(null),!0;h.current=!0,u(!0),m(null),y.current=g;const I=`${_}-${Math.random().toString(36).slice(2,8)}`,j={role:"user",content:f,timestamp:_,_localId:I},w=!0;r(x=>({...x,[g.tabKey]:[...x[g.tabKey]||[],j]}));try{const x=lr(s);if(!x)return y.current=Po(y.current,g),w&&r(L=>({...L,[g.tabKey]:(L[g.tabKey]||[]).filter(T=>T._localId!==I)})),m("Unable to send message right now."),!1;const $=await e(x,"send_chat",{message:f,...Ms(s)}),N=Do($);if(w&&(N!=null&&N.deduplicated))return r(L=>({...L,[g.tabKey]:(L[g.tabKey]||[]).filter(T=>T._localId!==I)})),m(null),!0;if((N==null?void 0:N.sent)===!1)throw new Error((N==null?void 0:N.error)||"Send failed");if((N==null?void 0:N.success)===!1)throw new Error((N==null?void 0:N.error)||"Send failed");return setTimeout(()=>{const L=Date.now()-6e4;r(T=>{const K=T[g.tabKey];if(!K)return T;const F=K.filter(M=>M.timestamp>L);return F.length===K.length?T:{...T,[g.tabKey]:F}})},6e4),m(null),!0}catch(x){const $=Da(x);return $.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",$):console.warn("Send blocked/failed",x),y.current=Po(y.current,g),r(N=>({...N,[g.tabKey]:(N[g.tabKey]||[]).filter(L=>L._localId!==I)})),m(Bu(x)),!1}finally{h.current=!1,u(!1)}},[s,e,n,r]),A=o.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await e(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(v){console.error("Relaunch failed",v)}},[s,e]),d=o.useCallback(async v=>{if(s)try{const C=(s.modalButtons||[]).indexOf(v),_=v.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),g=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(_),I=lr(s);if(!I)return;const j=await e(I,"resolve_action",{button:v,action:g?"approve":"reject",...C>=0&&{buttonIndex:C},...Ms(s)}),w=Do(j);w.success||n(x=>[...x,{routeId:s.tabKey,text:$o(v,w==null?void 0:w.error),timestamp:Date.now()}])}catch(f){Eo(f)||console.error("[ModalButton] Error:",f),n(C=>[...C,{routeId:s.tabKey,text:Eo(f)?$o(v,f):`❌ **${v}** error`,timestamp:Date.now()}])}},[s,e,n]),b=o.useCallback(async()=>{if(!(!s||i)){c(!0);try{await e(s.routeId,af(),{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(v){console.error("Focus agent failed",v)}finally{c(!1)}}},[s,i,e]);return{isSendingChat:l,sendFeedbackMessage:p,isFocusingAgent:i,handleSendChat:k,handleRelaunch:A,handleModalButton:d,handleFocusAgent:b}}const Ea=o.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m=null,handleFocusAgent:h,isFocusingAgent:y,actionLogs:k,userName:A,scrollToBottomRequestNonce:d,isInputActive:b=!0}){const v=bc(s),f=v.status||v.modalMessage||v.modalButtons?{...s,...v.status?{status:v.status}:{},...v.modalMessage!==void 0?{modalMessage:v.modalMessage}:{},...v.modalButtons!==void 0?{modalButtons:v.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(ji,{activeConv:f,onModalButton:c}),f.transport!=="pty"&&f.transport!=="acp"&&f.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(bs,{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,f.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(om,{activeConv:f,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m,isVisible:n})}),!n&&t.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(Jn,{activeConv:f,ideEntry:a,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m,handleFocusAgent:h,isFocusingAgent:y,actionLogs:k,userName:A,scrollToBottomRequestNonce:d,isInputActive:b})})]}):t.jsx(Jn,{activeConv:f,ideEntry:a,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m,handleFocusAgent:h,isFocusingAgent:y,actionLogs:k,userName:A,scrollToBottomRequestNonce:d,isInputActive:b})]})},(e,s)=>e.activeConv===s.activeConv&&e.isCliTerminal===s.isCliTerminal&&e.ideEntry===s.ideEntry&&e.terminalRef===s.terminalRef&&e.handleModalButton===s.handleModalButton&&e.handleRelaunch===s.handleRelaunch&&e.handleSendChat===s.handleSendChat&&e.isSendingChat===s.isSendingChat&&e.sendFeedbackMessage===s.sendFeedbackMessage&&e.handleFocusAgent===s.handleFocusAgent&&e.isFocusingAgent===s.isFocusingAgent&&e.actionLogs===s.actionLogs&&e.userName===s.userName&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&e.isInputActive===s.isInputActive);function lf({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:u,onBack:p,onOpenNativeConversation:m,onOpenMachine:h,onOpenHistory:y,onOpenRemote:k,onHideConversation:A,onStopCli:d,cliViewMode:b,onSetCliViewMode:v,handleSendChat:f,handleFocusAgent:C,handleModalButton:_,handleRelaunch:g}){const I=o.useRef(null),j=et(e)&&!s,w=j&&b==="terminal",x=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:`flex items-center justify-between gap-3 ${x} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:t.jsx(ca,{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:dt(e)}),t.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:t.jsx(Wi,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>m(e),onOpenMachine:()=>h(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[j&&b&&t.jsx(Sa,{mode:b,onChange:v,compact:!0}),j&&d&&t.jsx("button",{onClick:()=>{d(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:t.jsx(Nt,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>y(e),type:"button",children:t.jsx(da,{size:14})}),!s&&!j&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>k(e),type:"button",children:t.jsx(Lt,{size:14})}),A&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>A(e),type:"button",title:"Close chat",children:t.jsx(Nt,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(Ea,{activeConv:e,clearToken:0,isCliTerminal:w,ideEntry:n,terminalRef:I,handleModalButton:_,handleRelaunch:g,handleSendChat:f,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:C,isFocusingAgent:u,actionLogs:a,userName:i})})]})}const Mn={unix:{cmd:"curl -fsSL https://adhf.dev/install | sh",shell:"Terminal",prompt:"$ "},powershell:{cmd:"irm https://adhf.dev/install.ps1 | iex",shell:"PowerShell",prompt:"PS> "},cmd:{cmd:"curl -fsSL https://adhf.dev/install.cmd -o %TEMP%\\adhdev.cmd && %TEMP%\\adhdev.cmd",shell:"CMD",prompt:"> "}};function df(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Nc(){const[e,s]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{s(df())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(Mn[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:Mn[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:Mn[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 Cc({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:Lt},{key:"chats",label:"Chats",icon:Vt}];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 Sr({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 ks({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 Xs({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 Nr({item:e,type:s,getAvatarText:r,onOpenConversation:n}){const a=s==="needs_attention"||s==="task_complete",i=s==="working",c=s==="earlier",l=s==="task_complete",{isReconnecting:u,isConnecting:p}=Us(e.conversation),m=dt(e.conversation),h=ys(e.conversation),y=Yi(e.conversation,{requiresAction:s==="needs_attention"}),k=a?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":i?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",A=a?"bg-accent-primary shadow-glow":i?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":c?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",d=c?"text-text-secondary":"text-text-primary",b=c?"text-text-muted":"text-text-secondary",v=c?"text-text-secondary opacity-80":"text-text-muted",f=c?"text-text-muted opacity-80":"text-text-muted",C="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] ${k}`,onClick:()=>n(e.conversation),type:"button",children:[a||i?t.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,t.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${A}`,style:a?{color:"var(--accent-on-primary)"}:void 0,children:r(m)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${d}`,children:m}),!i&&t.jsx("span",{className:`text-[11px] font-medium shrink-0 ${f}`,children:wi(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${b}`,children:[h,u?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${C} 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…"})]}):y==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:C,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${v}`,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 Bo({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 uf({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:u,onShowConversation:p,onShowAllHidden:m,onOpenNewSession:h,onOpenMachine:y,onOpenSettings:k,onSectionChange:A,wsStatus:d="connected",isStandalone:b=!1}){const v=d==="disconnected"||d==="reconnecting"||d==="offline"||d==="auth_failed",f=c.length>0,C=s.length>0||r.length>0||n.length>0||a.length>0,_=e==="machines"?"Machines":"Chats",g=b?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",I=b?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]";return t.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[t.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${g}`,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(Zr,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:k,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(Qr,{size:18})})]})]})}),t.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${I}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:v?t.jsx(Xs,{icon:t.jsx(Bo,{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(Xs,{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(Nc,{})})}):t.jsx(ks,{children:c.map((j,w)=>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] ${w>0?"border-t border-border-subtle/70":""}`,onClick:()=>y(j.id),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:l(j.label)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:j.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:j.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[j.unread," new"]}):j.total>0?`${j.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:j.subtitle}),j.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[j.total," chat",j.total!==1?"s":"",j.unread>0?` · ${j.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},j.id))})}),e==="chats"&&s.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Sr,{title:"Needs attention",className:"mb-0"}),t.jsx(ks,{children:s.map((j,w)=>t.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:t.jsx(Nr,{item:j,type:"needs_attention",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&r.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Sr,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(ks,{children:r.map((j,w)=>t.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:t.jsx(Nr,{item:j,type:"task_complete",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&n.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Sr,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(ks,{children:n.map((j,w)=>t.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:t.jsx(Nr,{item:j,type:"working",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&t.jsx(Sr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?t.jsx(ks,{children:a.map((j,w)=>t.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:t.jsx(Nr,{item:j,type:"earlier",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))}):C?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):v?t.jsx(Xs,{icon:t.jsx(Bo,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):f?t.jsx(Xs,{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(Vt,{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(Xs,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),e==="chats"&&i.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsxs("div",{className:"mx-1 mt-4 mb-1 flex items-center justify-between gap-2 px-1 py-1 text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:[t.jsx("span",{children:"Hidden"}),t.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:m,children:"Restore all"})]}),t.jsx(ks,{className:"bg-bg-secondary/25",children:i.map((j,w)=>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 ${w>0?"border-t border-border-subtle/70":""}`,onClick:()=>p(j),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-bg-primary border border-border-subtle text-text-secondary",children:l(dt(j))}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:dt(j)}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:ys(j)}),t.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},j.tabKey))})]})]}),e==="chats"&&h&&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:h,"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(Cc,{section:e,onSectionChange:A})]})}function mf(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 Ic(e){const s=[e.workspace||"Workspace unknown"],r=gs(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=mf(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function cn(...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 pf(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 ln(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=pf(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 ff(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 hf(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function dn(e,s,r){const n=await e(s,"file_list_browse",{path:r}),a=hf(n);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(n==null?void 0:n.error)||"Could not browse folder");const i=typeof(a==null?void 0:a.path)=="string"?a.path:r,c=i.includes("\\")?"\\":"/",l=(p,m)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${m}`:p==="/"||p==="\\"?`${c}${m}`:`${p.replace(/[\\/]+$/,"")}${c}${m}`,u=Array.isArray(a==null?void 0:a.files)?a.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:typeof(p==null?void 0:p.path)=="string"&&p.path.trim()?p.path:l(i,p.name)})).sort((p,m)=>p.name.localeCompare(m.name)):[];return{path:i,directories:u}}function un({title:e,description:s,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:u,onConfirm:p}){const[m,h]=o.useState(r);o.useEffect(()=>{h(r)},[r]);const y=ff(r),k=m.trim();return t.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:t.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:l,"aria-label":"Close folder browser",children:t.jsx(Nt,{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:()=>{!y||a||u(y)},disabled:!y||a,children:[t.jsx(ca,{size:15}),"Parent"]}),t.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"text",value:m,onChange:A=>h(A.target.value),onKeyDown:A=>{A.key!=="Enter"||!k||a||(A.preventDefault(),u(k))},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:()=>{!k||a||u(k)},disabled:!k||a,children:"Go"})]})]})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):i?t.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):n.length===0?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):t.jsx("div",{className:"p-3",children:n.map(A=>t.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>u(A.path),children:[t.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(Rs,{size:17})}),t.jsxs("span",{className:"min-w-0 flex-1",children:[t.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:A.name}),t.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:A.path})]})]},A.path))})}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(k||r),disabled:!k&&!r||a,children:c})]})]})})}function $a({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:u=!1,showArgsInput:p,argsValue:m,onArgsChange:h,showModelInput:y,modelValue:k,onModelChange:A,historyProviderNode:d,onConfirm:b,onCancel:v}){const f=n==null?void 0:n.find(C=>C.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:v,"aria-label":"Close launch confirmation",children:t.jsx(Nt,{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:C=>i(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:u,children:n.map(C=>t.jsx("option",{value:C.key,children:C.label},C.key))}),(f==null?void 0:f.description)&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:f.description})]}),d,r.map(C=>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:C.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:C.value})]},`${C.label}:${C.value}`)),y&&A&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),t.jsx("input",{type:"text",value:k||"",onChange:C=>A(C.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]}),p&&h&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),t.jsx("input",{type:"text",value:m||"",onChange:C=>h(C.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:v,disabled:u,children:"Cancel"}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:b,disabled:u,children:[t.jsx(pa,{size:14}),u?l:c]})]})]})})}function Ko(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function hs(e){const{machine:s,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,i=[];a&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const u of s.workspaces||[])i.push({key:`saved:${u.id}`,label:`${u.id===s.defaultWorkspaceId?"⭐ ":""}${Ko(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const c=(r==null?void 0:r.trim())||"",l=c?(s.workspaces||[]).find(u=>u.path===c):null;if(c&&!l&&i.push({key:`custom:${c}`,label:Ko(c),description:c,workspaceId:null,workspacePath:c}),n){const u=`saved:${n}`;if(i.some(p=>p.key===u))return{options:i,selectedKey:u}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function xf(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function bf(e){return[xf(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function gf(e){return e.lastLaunchedAt?tn(e.lastLaunchedAt):""}function Ac(e){return{metaText:bf(e),updatedLabel:gf(e)}}function Ln(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function yf({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var Ve,it,ht,pt;const c=ur(),[l,u]=o.useState(!1),p=(((Ve=e.detectedIdes)==null?void 0:Ve.length)||0)>0,m=o.useMemo(()=>(e.workspaces||[]).map(je=>({id:je.id,path:je.path,label:je.label})),[e]),h=e.defaultWorkspaceId||null,[y,k]=o.useState(h||((it=m[0])==null?void 0:it.id)||""),[A,d]=o.useState(""),[b,v]=o.useState(""),[f,C]=o.useState([]),[_,g]=o.useState(!1),[I,j]=o.useState(""),[w,x]=o.useState(!1),[$,N]=o.useState(Ln(p,s.length,r.length)),L=o.useRef(null),[T,K]=o.useState(null),F=o.useRef("__home__"),[M,P]=o.useState("__home__"),[O,S]=o.useState(""),[D,z]=o.useState(""),[U,ae]=o.useState(""),[q,ue]=o.useState([]),[Z,se]=o.useState(()=>yt().textQuery),[oe,Ne]=o.useState(()=>yt().workspaceQuery),[me,he]=o.useState(()=>yt().modelQuery),[ie,V]=o.useState(()=>yt().resumableOnly),[ye,Q]=o.useState(()=>yt().sortMode),[ge,te]=o.useState(!1),[ce,ne]=o.useState(!1),we=o.useRef(null),xe=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const B=y==="__custom__"?A.trim():((ht=m.find(je=>je.id===y))==null?void 0:ht.path)||"",ke=y==="__custom__"&&!!B&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),ve=y!=="__custom__"&&((pt=m.find(je=>je.id===y))==null?void 0:pt.path)||"",Ce=o.useMemo(()=>(e.recentLaunches||[]).map(je=>je.workspace),[e]),J=o.useCallback(async je=>{g(!0),j("");try{const Ue=await a(je);v(Ue.path),d(Ue.path),C(Ue.directories)}catch(Ue){j(Ue instanceof Error?Ue.message:"Could not load folder")}finally{g(!1)}},[a]),Te=o.useCallback(()=>{var Ue;k("__custom__"),x(!0);const je=ln(e.platform,cn(A.trim(),ve,Ce,e.defaultWorkspacePath,(Ue=m.find(ze=>ze.id===h))==null?void 0:Ue.path,m.map(ze=>ze.path)));J(je)},[A,h,J,Ce,ve,e.platform,m]),He=o.useCallback(je=>{if(je!=null&&je.workspaceId){k(je.workspaceId),d("");return}if(je!=null&&je.workspacePath){k("__custom__"),d(je.workspacePath);return}k(""),d("")},[]),De=o.useCallback(je=>{if(k(je),je==="__custom__"){Te();return}d("")},[Te]),Ze=o.useCallback(je=>{k("__custom__"),d(je)},[]),Ge=o.useCallback((je,Ue)=>{L.current=Ue,F.current=je.selectedWorkspaceKey||"__home__",P(je.selectedWorkspaceKey||"__home__"),S(je.initialArgs||""),z(je.initialModel||""),ae(""),ue([]);const ze=je.providerType?`${e.id}:${je.providerType}`:null;if(dm(xe.current,ze)){const Xe=yt();se(Xe.textQuery),Ne(Xe.workspaceQuery),he(Xe.modelQuery),V(Xe.resumableOnly),Q(Xe.sortMode)}xe.current=ze,K(je),je.providerType&&i&&(te(!0),i(je.providerType).then(Xe=>ue(Xe||[])).catch(Xe=>console.warn("Failed to load saved sessions",Xe)).finally(()=>te(!1)))},[i,e.id]),Ye=o.useMemo(()=>Ji(q,{textQuery:Z,workspaceQuery:oe,modelQuery:me,resumableOnly:ie,sortMode:ye}),[me,ie,q,ye,Z,oe]);o.useEffect(()=>{U&&(Ye.some(je=>je.providerSessionId===U)||ae(""))},[Ye,U]);const ot=o.useCallback(()=>{L.current&&(ne(!0),L.current().finally(()=>{L.current=null,ne(!1),K(null)}))},[]),tt=o.useCallback(()=>{L.current=null,K(null)},[]),mt=o.useCallback(je=>{F.current=je,P(je)},[]);return o.useEffect(()=>{var je;we.current!==e.id&&(we.current=e.id,k(h||((je=m[0])==null?void 0:je.id)||"__custom__"),d(""),v(""),C([]),j(""),x(!1),se(yt().textQuery),Ne(yt().workspaceQuery),he(yt().modelQuery),V(yt().resumableOnly),Q(yt().sortMode),xe.current=null,N(Ln(p,s.length,r.length)))},[r.length,s.length,h,p,e.id,m]),o.useEffect(()=>{var je;y!=="__custom__"&&(y&&m.some(Ue=>Ue.id===y)||k(h||((je=m[0])==null?void 0:je.id)||"__custom__"))},[h,y,m]),o.useEffect(()=>{$==="ide"&&p||$==="cli"&&s.length>0||$==="acp"&&r.length>0||N(Ln(p,s.length,r.length))},[$,r.length,s.length,p]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:p,workspaceRows:m,defaultWorkspaceId:h,workspaceChoice:y,customWorkspacePath:A,browseCurrentPath:b,browseDirectories:f,browseBusy:_,browseError:I,browseDialogOpen:w,activeLauncherKind:$,launchConfirm:T,launchConfirmWorkspaceKeyRef:F,launchConfirmWorkspaceKey:M,launchConfirmArgs:O,launchConfirmModel:D,launchConfirmResumeId:U,launchConfirmSavedSessions:q,launchConfirmTextFilter:Z,launchConfirmWorkspaceFilter:oe,launchConfirmModelFilter:me,launchConfirmResumableOnly:ie,launchConfirmSortMode:ye,filteredLaunchConfirmSavedSessions:Ye,launchConfirmSessionsLoading:ge,launchConfirmBusy:ce,resolvedWorkspacePath:B,canCreateMissingWorkspace:ke,openBrowseDialog:Te,loadBrowsePath:J,handleWorkspaceChoiceChange:De,chooseCustomWorkspacePath:Ze,setCustomWorkspacePath:d,setBrowseDialogOpen:x,setActiveLauncherKind:N,openLaunchConfirm:Ge,handleConfirmLaunch:ot,closeLaunchConfirm:tt,setWorkspaceSelectionFromOption:He,setLaunchConfirmWorkspaceKeyAndSync:mt,setLaunchConfirmArgs:S,setLaunchConfirmModel:z,setLaunchConfirmResumeId:ae,setLaunchConfirmTextFilter:se,setLaunchConfirmWorkspaceFilter:Ne,setLaunchConfirmModelFilter:he,setLaunchConfirmResumableOnly:V,setLaunchConfirmSortMode:Q}}function vf({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:u,section:p,showBottomNav:m,onBack:h,onSectionChange:y,onOpenConversation:k,onOpenRecent:A,onOpenMachineDetails:d,onMachineUpgrade:b,onLaunchDetectedIde:v,onAddWorkspace:f,onBrowseDirectory:C,onLaunchWorkspaceProvider:_,onListSavedSessions:g}){const I=M=>M==="ide"?"IDE":M==="cli"?"CLI":"ACP",j=r.slice(0,4),w=s.slice(0,3),x=yf({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:C,onListSavedSessions:g}),$=o.useMemo(()=>j.map(M=>{const{metaText:P,updatedLabel:O}=Ac(M);return{key:`recent-launch:${M.id}`,primary:M.label,secondary:P,updatedLabel:O,onClick:()=>{const{options:S,selectedKey:D}=hs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspacePath:M.workspace});x.openLaunchConfirm({title:M.kind==="ide"?us("restart-ide",M.label):M.providerSessionId?Ia(M.label):us("start-fresh",M.label),description:M.kind==="ide"?ms("restart-ide"):M.providerSessionId?Aa():ms("start-fresh"),confirmLabel:M.kind==="ide"?Ks("restart-ide"):M.providerSessionId?zr(!0):Ks("start-fresh"),busyLabel:M.kind==="ide"?Ws("restart-ide"):M.providerSessionId?Na(!0):Ws("start-fresh"),workspaceOptions:S,selectedWorkspaceKey:D,details:[{label:"Mode",value:I(M.kind)},...M.providerType?[{label:"Provider",value:M.providerType}]:[]]},async()=>{const z=S.find(U=>U.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(z),await A({...M,workspace:(z==null?void 0:z.workspacePath)??null})})}}}),[x,A,j]),N=o.useMemo(()=>w.map(M=>({key:`recent-chat:${M.conversation.tabKey}`,primary:dt(M.conversation),secondary:sm(M.conversation,{timestampLabel:M.timestamp?wi(M.timestamp):null}),unread:M.unread,onClick:()=>k(M.conversation)})),[k,w]),L=x.showAllRecent?$:$.slice(0,4),T=$.length>0,K=N.length>0,F=u?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:`flex items-center justify-between gap-3 ${F} 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:h,type:"button","aria-label":"Back",children:t.jsx(ca,{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:Mt(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:[K&&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:N.map(M=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${M.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:M.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:M.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:M.secondary})]},M.key))})]}),T&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:L.map(M=>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:M.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:M.primary}),M.updatedLabel&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:M.updatedLabel})]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:M.secondary})]},M.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(M=>!M),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:M=>x.handleWorkspaceChoiceChange(M.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(M=>t.jsxs("option",{value:M.id,children:[M.id===x.defaultWorkspaceId?"⭐ ":"",rn(M.path,M.label)||M.path]},M.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(Rs,{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&&f(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(M=>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:P,selectedKey:O}=hs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspaceId:x.workspaceChoice!=="__custom__"?x.workspaceChoice:null,currentWorkspacePath:x.resolvedWorkspacePath});x.openLaunchConfirm({title:`Launch ${M.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:P,selectedWorkspaceKey:O,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:M.name}]},async()=>{const S=P.find(D=>D.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(S),v(M.type,{workspacePath:(S==null?void 0:S.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:M.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath||"Use selected workspace"})]},M.type)):(x.activeLauncherKind==="cli"?n:a).map(M=>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 P=x.activeLauncherKind==="cli"?"cli":"acp",{options:O,selectedKey:S}=hs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspaceId:x.workspaceChoice!=="__custom__"?x.workspaceChoice:null,currentWorkspacePath:x.resolvedWorkspacePath});x.openLaunchConfirm({title:`Launch ${M.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${P.toUpperCase()}`,workspaceOptions:O,selectedWorkspaceKey:S,details:[{label:"Mode",value:P.toUpperCase()},{label:"Provider",value:M.displayName}],showArgsInput:!0,showModelInput:P==="acp",initialArgs:"",initialModel:"",providerType:M.type},async()=>{const D=O.find(z=>z.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(D),_(P,M.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:[M.icon?`${M.icon} `:"",M.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath||"Use selected workspace"})]},M.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:()=>f(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(un,{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:M=>{x.loadBrowsePath(M)},onConfirm:M=>{x.chooseCustomWorkspacePath(M),x.setBrowseDialogOpen(!1)}}),x.launchConfirm&&t.jsx($a,{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?zr(!!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:Ca()}),t.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[t.jsx("input",{type:"text",value:x.launchConfirmTextFilter,onChange:M=>x.setLaunchConfirmTextFilter(M.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:M=>x.setLaunchConfirmWorkspaceFilter(M.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:M=>x.setLaunchConfirmModelFilter(M.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:M=>x.setLaunchConfirmSortMode(M.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:M=>x.setLaunchConfirmResumableOnly(M.target.checked),disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),"Resume-ready only"]}),t.jsxs("select",{value:x.launchConfirmResumeId,onChange:M=>x.setLaunchConfirmResumeId(M.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:pm()}),x.filteredLaunchConfirmSavedSessions.map(M=>t.jsxs("option",{value:M.providerSessionId,disabled:!M.canResume,children:[M.title||M.providerSessionId," ",M.canResume?"":"(workspace missing)"]},M.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 M=x.filteredLaunchConfirmSavedSessions.find(O=>O.providerSessionId===x.launchConfirmResumeId);if(!M)return null;const P=Ic(M);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:P.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:P.providerSessionId}),t.jsx("div",{className:"mt-1",children:P.metaLine}),P.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:P.updatedLabel}),P.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:P.preview})]})})()]}),onConfirm:x.handleConfirmLaunch,onCancel:x.closeLaunchConfirm}),m&&t.jsx(Cc,{section:p,onSectionChange:y})]})}function Tc(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 wf(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:gs(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):s.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var c,l,u,p,m;const a=ir(n)?"cli":As(n)?"acp":"ide",i=gs(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(ir(n)?n.cliName||n.type:As(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:As(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((m=(p=(u=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:u.at)==null?void 0:p.call(u,-1))==null?void 0:m.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function jf(e,s){const r=new Map;for(const n of s){const a=ts(n.conversation),i=r.get(a);i?i.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],i=[...a].sort((h,y)=>y.timestamp-h.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=Gn(n),u=a.filter(h=>h.unread||h.requiresAction).length,p=Tc(n),m=[n.platform||"machine",p].filter(Boolean);return{id:n.id,label:Mt(n,{fallbackId:n.id}),subtitle:m.join(" · "),unread:u,total:a.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?rm(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 Cr(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 kf({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:m,onRequestedMachineConsumed:h,requestedMobileSection:y,onRequestedMobileSectionConsumed:k,setSelectedTabKey:A,setScreen:d,setSelectedMachineId:b,setSection:v,setMachineBackTarget:f,resetMachineAction:C,markNotificationTargetRead:_}){const g=o.useRef(null),I=o.useCallback(j=>{if(!(j!=null&&j.sessionId))return;const w=Hr(j,c),x=Math.max(Date.now(),cs(j),w.lastUpdated||0);Cr("mark_read:start",{tabKey:j.tabKey,sessionId:j.sessionId,displayPrimary:dt(j),inboxBucket:w.inboxBucket,unread:w.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,activityAt:cs(j),readAt:x}),_({sessionId:j.sessionId,providerSessionId:j.providerSessionId,tabKey:j.tabKey,routeId:j.routeId}),l(ts(j)||j.routeId,"mark_session_seen",{sessionId:j.sessionId,seenAt:x}).then($=>{Cr("mark_read:result",{tabKey:j.tabKey,sessionId:j.sessionId,result:$})}).catch($=>{Cr("mark_read:error",{tabKey:j.tabKey,sessionId:j.sessionId,error:$ instanceof Error?$.message:String($)})})},[c,l]);return o.useEffect(()=>{var w;if(!n){d("inbox"),A(((w=e[0])==null?void 0:w.tabKey)||null),g.current=null;return}if(i!=="chat"){g.current=null;return}const j=`${n.tabKey}:${n.sessionId||""}`;g.current!==j&&(g.current=j,I(n))},[e,I,i,n,d,A]),o.useEffect(()=>{if(!u)return;const j=e.find(w=>w.tabKey===u);j&&(A(j.tabKey),d("chat"),p==null||p())},[e,p,u,d,A]),o.useEffect(()=>{if(!m)return;const j=s.find(w=>w.id===m);j&&(b(j.id),C(),v("machines"),f("inbox"),d("machine"),h==null||h())},[s,h,m,C,f,d,v,b]),o.useEffect(()=>{y&&(v(y),d("inbox"),k==null||k())},[k,y,d,v]),o.useEffect(()=>{const j=r.filter(w=>w.inboxBucket==="task_complete"||w.unread);j.length!==0&&Cr("inbox_state",{screen:i,selectedTabKey:a,items:j.map(w=>{const x=Hr(w.conversation,c);return{liveState:x,tabKey:w.conversation.tabKey,sessionId:w.conversation.sessionId,displayPrimary:dt(w.conversation),serverBucket:x.inboxBucket,computedBucket:w.inboxBucket,serverUnread:x.unread,computedUnread:w.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,activityAt:cs(w.conversation)}})})},[r,c,i,a]),{markConversationRead:I}}function Sf(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Wo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Nf(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Cf({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[u,p]=o.useState(null),m=o.useCallback(()=>{i("idle"),l(""),p(null)},[]),h=o.useCallback(async(f,C,_)=>{var g;try{i("loading"),l(`Launching ${C}…`);const I={ideType:C,enableCdp:!0};(g=_==null?void 0:_.workspacePath)!=null&&g.trim()&&(I.workspace=_.workspacePath.trim()),await e(f,"launch_ide",I),i("done"),l(`${C} launch requested`)}catch(I){i("error"),l(I instanceof Error?I.message:"Launch IDE failed"),console.error("Launch IDE failed",I)}},[e]),y=o.useCallback(async(f,C,_)=>{if(C.trim())try{i("loading"),l(_!=null&&_.createIfMissing?"Creating folder…":"Saving workspace…");const g=await e(f,"workspace_add",{path:C.trim(),createIfMissing:(_==null?void 0:_.createIfMissing)===!0});if(g!=null&&g.success){i("done"),l(_!=null&&_.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((g==null?void 0:g.error)||"Could not save workspace")}catch(g){i("error"),l(g instanceof Error?g.message:"Could not save workspace")}},[e]),k=o.useCallback(async f=>{var C,_,g,I,j,w;try{i("loading"),l("Starting daemon upgrade…");const x=await e(f,"daemon_upgrade",{});if((C=x==null?void 0:x.result)!=null&&C.alreadyLatest){i("done"),l(`Already on v${((_=x==null?void 0:x.result)==null?void 0:_.version)||"latest"}.`);return}if((g=x==null?void 0:x.result)!=null&&g.upgraded||(I=x==null?void 0:x.result)!=null&&I.success){i("done"),l(`Upgrade to v${((j=x==null?void 0:x.result)==null?void 0:j.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((w=x==null?void 0:x.result)==null?void 0:w.error)||"Upgrade failed")}catch(x){i("error"),l(x instanceof Error?x.message:"Upgrade failed")}},[e]),A=o.useCallback(async(f,C,_,g)=>{var w,x,$;const I=Date.now(),j={machineId:f,kind:C,providerType:_,workspaceId:(g==null?void 0:g.workspaceId)||null,workspacePath:(g==null?void 0:g.workspacePath)||null,resumeSessionId:(g==null?void 0:g.resumeSessionId)||null,startedAt:I};try{i("loading"),l(`Launching ${_}…`),p(j);const N={cliType:_};(w=g==null?void 0:g.workspacePath)!=null&&w.trim()?N.dir=g.workspacePath.trim():g!=null&&g.workspaceId&&(N.workspaceId=g.workspaceId),g!=null&&g.resumeSessionId&&(N.resumeSessionId=g.resumeSessionId),(x=g==null?void 0:g.args)!=null&&x.trim()&&(N.cliArgs=g.args.trim().split(/\s+/).filter(Boolean)),($=g==null?void 0:g.model)!=null&&$.trim()&&(N.initialModel=g.model.trim());const L=await e(f,"launch_cli",N),T=(L==null?void 0:L.result)||L,K=(T==null?void 0:T.sessionId)||(T==null?void 0:T.id);if(L!=null&&L.success&&K){p(null),i("done"),l(`${_} launched`),s(Zt(K));return}if(L!=null&&L.success){i("loading"),l(`${_} launch requested — waiting for session…`);return}p(null),i("error"),l((L==null?void 0:L.error)||(T==null?void 0:T.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(N){if(Nf(N)){i("loading"),l(`${_} launch requested — waiting for session…`);return}p(null),i("error"),l(N instanceof Error?N.message:`Could not launch ${C.toUpperCase()} workspace`)}},[s,e]),d=o.useCallback(async(f,C)=>{try{const _=await e(f,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),g=(_==null?void 0:_.result)??_;return Array.isArray(g==null?void 0:g.sessions)?g.sessions:[]}catch(_){return console.error("Failed to list saved sessions on mobile:",_),[]}},[e]),b=o.useCallback(async(f,C)=>dn(e,f,C),[e]);o.useEffect(()=>{if(!u)return;const f=Wo(u.workspacePath),C=r.find(g=>{var N,L,T,K;if(!g||g.type==="adhdev-daemon"||Sf(g.daemonId||g.id)!==u.machineId||(g.transport==="acp"?"acp":g.transport==="pty"?"cli":null)!==u.kind||String(g.agentType||g.type||"")!==u.providerType)return!1;const x=String(g.providerSessionId||"");if(u.resumeSessionId&&x)return x===u.resumeSessionId;if(f){const F=Wo(g.workspace||g.runtimeWorkspaceLabel);return F?F===f:!1}return Number(g.lastUpdated||g._lastUpdate||g.timestamp||((K=(T=(L=(N=g.activeChat)==null?void 0:N.messages)==null?void 0:L.at)==null?void 0:T.call(L,-1))==null?void 0:K.timestamp)||0)>=u.startedAt-5e3});if(!C)return;const _=Ki({entrySessionId:C.sessionId,entryInstanceId:C.instanceId,entryRouteId:C.id,conversations:n});_&&(p(null),i("done"),l(`${u.providerType} launched`),s(Zt(_)))},[n,r,s,u]),o.useEffect(()=>{if(!u)return;const f=window.setTimeout(()=>{p(C=>!C||C.startedAt!==u.startedAt?C:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(f)},[u]);const v=o.useCallback(async(f,C)=>{if(C.kind==="ide"&&C.providerType){await h(f,C.providerType,{workspacePath:C.workspace||null});return}(C.kind==="cli"||C.kind==="acp")&&C.providerType&&await A(f,C.kind,C.providerType,{workspacePath:C.workspace||null,resumeSessionId:C.providerSessionId||null})},[h,A]);return{machineAction:{state:a,message:c},resetMachineAction:m,handleLaunchDetectedIde:h,handleAddWorkspace:y,handleMachineUpgrade:k,handleLaunchWorkspaceProvider:A,handleListSavedSessions:d,handleBrowseDirectory:b,handleOpenRecent:v}}function If({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:p}){const m=o.useCallback(v=>{i(v.tabKey),c("chat"),n(v)},[n,c,i]),h=o.useCallback(v=>{const f=e.find(C=>C.routeId===v.routeId&&C.streamSource==="native");f&&(i(f.tabKey),c("chat"),n(f))},[e,n,c,i]),y=o.useCallback(()=>{n(s),c("inbox")},[n,s,c]),k=o.useCallback((v,f="inbox")=>{l(v),a(),u("machines"),p(f),c("machine")},[a,p,c,u,l]),A=o.useCallback(v=>{const f=ts(v);f&&k(f,"chat")},[k]),d=o.useCallback(()=>{a(),c(r)},[r,a,c]),b=o.useCallback(v=>{u(v),c("inbox")},[c,u]);return{openConversation:m,openNativeConversation:h,backFromConversation:y,openMachine:k,openConversationMachine:A,backFromMachine:d,changeMachineSection:b}}function Af(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function Tf(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 Ir(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Mf({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,userName:u,requestedActiveTabKey:p,onRequestedActiveTabConsumed:m,requestedMachineId:h,onRequestedMachineConsumed:y,requestedMobileSection:k,onRequestedMobileSectionConsumed:A,onOpenHistory:d,onOpenRemote:b,onStopCli:v,wsStatus:f,isConnected:C,onShowHiddenConversation:_,onShowAllHiddenConversations:g,onHideConversation:I,onOpenNewSession:j,notificationStateBySessionId:w,onMarkNotificationTargetRead:x}){const[$,N]=o.useState(()=>{var J;return((J=e[0])==null?void 0:J.tabKey)||null}),[L,T]=o.useState(()=>e[0]?"chat":"inbox"),[K,F]=o.useState("chats"),[M,P]=o.useState(null),[O,S]=o.useState("inbox"),D=Os(),z="0.8.78",U=o.useMemo(()=>e.find(J=>J.tabKey===$)||e[0]||null,[e,$]),ae=o.useMemo(()=>U?r.find(J=>J.id===U.routeId):void 0,[r,U]),q=o.useMemo(()=>!U||Je(U)||!et(U)?null:Es(U),[U]),ue=o.useMemo(()=>r.filter(J=>J.type==="adhdev-daemon").sort(ga),[r]),Z=o.useMemo(()=>ue.find(J=>J.id===M)||null,[ue,M]),se=o.useMemo(()=>sn(r),[r]),oe=on({sendDaemonCommand:a,activeConv:U||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),Ne=Cf({sendDaemonCommand:a,navigate:D,ides:r,conversations:e}),me=o.useMemo(()=>e.map(J=>{const Te=L==="chat"&&(U==null?void 0:U.tabKey)===J.tabKey,He=xa(J,se,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Te,notificationStateBySessionId:w}),De=cs(J),Ze=qi(J);return{conversation:J,timestamp:De,preview:Ze,unread:He.unread,requiresAction:He.requiresAction,isWorking:He.isWorking,inboxBucket:He.inboxBucket}}),[e,se,w,L,U]),{markConversationRead:he}=kf({conversations:e,machineEntries:ue,items:me,selectedConversation:U,selectedTabKey:$,screen:L,liveSessionInboxState:se,sendDaemonCommand:a,requestedActiveTabKey:p,onRequestedActiveTabConsumed:m,requestedMachineId:h,onRequestedMachineConsumed:y,requestedMobileSection:k,onRequestedMobileSectionConsumed:A,setSelectedTabKey:N,setScreen:T,setSelectedMachineId:P,setSection:F,setMachineBackTarget:S,resetMachineAction:Ne.resetMachineAction,markNotificationTargetRead:x}),ie=If({conversations:e,selectedConversation:U,machineBackTarget:O,markConversationRead:he,resetMachineAction:Ne.resetMachineAction,setSelectedTabKey:N,setScreen:T,setSelectedMachineId:P,setSection:F,setMachineBackTarget:S}),V=o.useMemo(()=>Ir(me.filter(J=>J.requiresAction)),[me]),ye=o.useMemo(()=>Ir(me.filter(J=>J.unread&&!J.requiresAction)),[me]),Q=o.useMemo(()=>Ir(me.filter(J=>!J.unread&&!J.requiresAction&&J.isWorking)),[me]),ge=o.useMemo(()=>Ir(me.filter(J=>!J.unread&&!J.requiresAction&&!J.isWorking)),[me]),te=o.useMemo(()=>Z?me.filter(J=>ts(J.conversation)===Z.id):[],[me,Z]),ce=o.useMemo(()=>wf(Z,r),[r,Z]),ne=(Z==null?void 0:Z.version)||null,we=!!Z&&!!ne&&!0&&ne!==z,xe=o.useMemo(()=>(Z==null?void 0:Z.availableProviders)||[],[Z]),B=o.useMemo(()=>xe.filter(J=>J.category==="cli"&&J.installed!==!1).map(J=>({type:J.type,displayName:J.displayName||J.type,icon:J.icon})),[xe]),ke=o.useMemo(()=>xe.filter(J=>J.category==="acp"&&J.installed!==!1).map(J=>({type:J.type,displayName:J.displayName||J.type,icon:J.icon})),[xe]),ve=o.useMemo(()=>jf(ue,me),[me,ue]),Ce=o.useCallback(async J=>{Z&&await Ne.handleOpenRecent(Z.id,J)},[Ne,Z]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:L==="chat"&&U?t.jsx(lf,{selectedConversation:U,isAcp:Je(U),isStandalone:l,selectedIdeEntry:ae,actionLogs:n,userName:u,isSendingChat:oe.isSendingChat,sendFeedbackMessage:oe.sendFeedbackMessage,isFocusingAgent:oe.isFocusingAgent,handleModalButton:oe.handleModalButton,handleRelaunch:oe.handleRelaunch,onBack:ie.backFromConversation,onOpenNativeConversation:ie.openNativeConversation,onOpenMachine:ie.openConversationMachine,onHideConversation:I,onOpenHistory:d,onOpenRemote:b,onStopCli:v,cliViewMode:q,onSetCliViewMode:async J=>{if(U&&q!==J)try{await a(ts(U)||U.routeId,"set_cli_view_mode",{targetSessionId:U.sessionId,cliType:Et(U),mode:J})}catch(Te){Tf(Te)?console.warn("Skipped CLI view mode switch:",Te instanceof Error?Te.message:String(Te)):console.error("Failed to switch CLI view mode:",Te)}},handleSendChat:oe.handleSendChat,handleFocusAgent:oe.handleFocusAgent}):L==="machine"&&Z?t.jsx(vf,{selectedMachineEntry:Z,selectedMachineConversations:te,selectedMachineRecentLaunches:ce,cliProviders:B,acpProviders:ke,selectedMachineNeedsUpgrade:we,appVersion:z,machineAction:Ne.machineAction,isStandalone:l,section:K,showBottomNav:O==="inbox",onBack:ie.backFromMachine,onSectionChange:ie.changeMachineSection,onOpenConversation:ie.openConversation,onOpenRecent:Ce,onOpenMachineDetails:()=>D(`/machines/${Z.id}`),onMachineUpgrade:()=>Ne.handleMachineUpgrade(Z.id),onLaunchDetectedIde:(J,Te)=>Ne.handleLaunchDetectedIde(Z.id,J,Te),onAddWorkspace:(J,Te)=>Ne.handleAddWorkspace(Z.id,J,Te),onBrowseDirectory:J=>Ne.handleBrowseDirectory(Z.id,J),onLaunchWorkspaceProvider:(J,Te,He)=>Ne.handleLaunchWorkspaceProvider(Z.id,J,Te,He),onListSavedSessions:J=>Ne.handleListSavedSessions(Z.id,J)}):t.jsx(uf,{section:K,attentionItems:V,unreadItems:ye,workingItems:Q,completedItems:ge,hiddenConversations:s,machineCards:ve,getAvatarText:Af,onOpenConversation:ie.openConversation,onShowConversation:_,onShowAllHidden:g,onOpenNewSession:j,onOpenMachine:ie.openMachine,onOpenSettings:()=>D("/settings"),onSectionChange:F,wsStatus:f,isConnected:C,isStandalone:l})})}function _n(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function Lf({conversations:e,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,u]=o.useState(!1),[p,m]=o.useState(null),h=o.useCallback(()=>{c.current=0,u(!1),m(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const y=o.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),k=o.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!_n(s,r)){m("merge");return}const v=b.currentTarget.getBoundingClientRect(),f=b.clientX-v.left,C=v.width/3;f<C?m("split-left"):f>C*2?m("split-right"):m("merge")},[s,r]),A=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,u(!1),m(null))},[]),d=o.useCallback(b=>{c.current=0,u(!1);const v=b.dataTransfer.getData("text/tab-key"),f=v?e.some(_=>_.tabKey===v):!1,C=p;if(m(null),i(),!!v){if(b.preventDefault(),C==="split-left"&&_n(s,r)){r==null||r(v,"split-left");return}if(C==="split-right"&&_n(s,r)){r==null||r(v,"split-right");return}if(f){a(v);return}n==null||n(v)}},[e,p,s,r,n,a,i]);return{dragOver:l,dropAction:p,resetDragState:h,handleDragEnter:y,handleDragOver:k,handleDragLeave:A,handleDrop:d}}function _f(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 Rf({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(s??null),[l,u]=o.useState(r??[]),[p,m]=o.useState(null),h=o.useRef(null),y=o.useRef(null),k=o.useRef(n),A=o.useRef(a);o.useEffect(()=>{k.current=n},[n]),o.useEffect(()=>{A.current=a},[a]),o.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),o.useEffect(()=>{u(j=>{const w=_f(j,e);return w.length===j.length&&w.every((x,$)=>x===j[$])?j:w})},[e]);const d=o.useMemo(()=>{const j=p??l;if(j.length===0)return e;const w=new Map(j.map((x,$)=>[x,$]));return[...e].sort((x,$)=>{const N=w.get(x.tabKey)??999,L=w.get($.tabKey)??999;return N-L})},[e,p,l]);o.useEffect(()=>{var w,x;if(d.length===0){i!==null&&(c(null),(w=k.current)==null||w.call(k,null));return}if(i&&d.some($=>$.tabKey===i))return;const j=d[0].tabKey;j!==i&&(c(j),(x=k.current)==null||x.call(k,j))},[d,i]);const b=o.useMemo(()=>d.find(j=>j.tabKey===i),[d,i]),v=o.useCallback(j=>{var w;c(j),(w=k.current)==null||w.call(k,j)},[]),f=o.useCallback((j,w,x)=>{u($=>{var K;const N=$.filter(F=>F!==j),L=N.indexOf(w);if(L<0)return $;const T=x==="left"?L:L+1;return N.splice(T,0,j),(K=A.current)==null||K.call(A,N),N}),m(null)},[]),C=o.useCallback((j,w,x)=>{const N=(l.length>0?l:e.map(K=>K.tabKey)).filter(K=>K!==j),L=N.indexOf(w);if(L<0)return;const T=x==="left"?L:L+1;N.splice(T,0,j),h.current=N,m(N)},[l,e]),_=o.useCallback(()=>{var w;const j=h.current;j&&(u(j),(w=A.current)==null||w.call(A,j))},[]),g=o.useCallback(()=>{h.current=null,m(null)},[]),I=o.useCallback(j=>{u(w=>{var $;const x=w.filter(N=>N!==j);return x.push(j),($=A.current)==null||$.call(A,x),x})},[]);return{activeTabId:i,activeConv:b,sortedConversations:d,previewOrderRef:h,draggingTabRef:y,selectTab:v,handleTabReorder:f,updatePreviewOrder:C,commitPreviewOrder:_,clearPreviewOrder:g,moveTabToEnd:I,setDraggingTabKey:j=>{y.current=j}}}function Pf({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 Ba({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(Nc,{}),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 Mc="adhdev-tab-shortcuts";function Lc(){try{return JSON.parse(localStorage.getItem(Mc)||"{}")}catch{return{}}}function _c({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>Lc()),[l,u]=o.useState(null),p=o.useCallback(h=>{const y=[];return h.metaKey&&y.push(a?"⌘":"Meta"),h.ctrlKey&&y.push("Ctrl"),h.altKey&&y.push(a?"⌥":"Alt"),h.shiftKey&&y.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(y.push(h.key.length===1?h.key.toUpperCase():h.key),y.join("+"))},[a]),m=o.useCallback(h=>{c(h);try{localStorage.setItem(Mc,JSON.stringify(h))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const h=y=>{if(y.preventDefault(),y.stopPropagation(),y.key==="Escape"){u(null);return}const k=p(y);if(!k)return;const A={...i};for(const[d,b]of Object.entries(A))b===k&&delete A[d];A[l]=k,m(A),u(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,l,i,m,p]),o.useEffect(()=>{if(!e)return;const h=y=>{if(!(!y.ctrlKey&&!y.metaKey&&!y.altKey)){for(const[k,A]of Object.entries(i))if(s.includes(k)&&p(y)===A){y.preventDefault(),r(),n(k);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,i,s,r,n,p]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:u,saveShortcuts:m}}const Df=o.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:u,onSelectTab:p,onConversationActivated:m,onPreviewReorder:h,onReorderTab:y,onCommitPreviewOrder:k,onClearPreviewOrder:A,onDragStateReset:d,onDragTabKeyChange:b,onReceiveTab:v,onOpenContextMenu:f,longPressTimer:C,isGroupActive:_}){const g=Us(s),I=g.isGenerating?"agent-tab-generating":g.isWaiting?"agent-tab-waiting":"",j=g.isReconnecting,w=o.useCallback(P=>{l.current=s.tabKey,b(s.tabKey),P.dataTransfer.setData("text/tab-key",s.tabKey),P.dataTransfer.effectAllowed="move"},[s.tabKey,l,b]),x=o.useCallback(()=>{l.current=null,b(null),k(),A(),d()},[l,b,k,A,d]),$=o.useCallback(P=>{const O=l.current;if(!(!O||O===s.tabKey)&&P.dataTransfer.types.includes("text/tab-key")){P.preventDefault(),P.stopPropagation();const S=P.currentTarget.getBoundingClientRect(),D=P.clientX<S.left+S.width/2?"left":"right";h(O,s.tabKey,D)}},[s.tabKey,l,h]),N=o.useCallback(P=>{P.preventDefault(),P.stopPropagation();const O=P.dataTransfer.getData("text/tab-key");if(O&&O!==s.tabKey){const S=P.currentTarget.getBoundingClientRect(),D=P.clientX<S.left+S.width/2?"left":"right";c.includes(O)?y(O,s.tabKey,D):v&&v(O)}A()},[s.tabKey,c,y,v,A]),L=o.useCallback(P=>{P.stopPropagation(),u(),p(s.tabKey),m(s)},[s,m,u,p]),T=o.useCallback(P=>{P.preventDefault(),f(P.clientX,P.clientY,s.tabKey)},[s.tabKey,f]),K=o.useCallback(P=>{const O=P.touches[0];C.current=setTimeout(()=>{f(O.clientX,O.clientY,s.tabKey)},600)},[s.tabKey,C,f]),F=o.useCallback(()=>{C.current&&clearTimeout(C.current)},[C]),M=["adhdev-dockview-tab",I,r&&"is-active",_&&"is-group-active",j&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:M,draggable:!0,onDragStart:w,onDragEnd:x,onDragOver:$,onDrop:N,onClick:L,onContextMenu:T,onTouchStart:K,onTouchEnd:F,onTouchMove:F,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:g.isGenerating?t.jsx("div",{className:"tab-spinner"}):g.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):g.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:dt(s),children:dt(s)}),t.jsx("span",{className:"adhdev-dockview-tab-meta",children:j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ds(s)}):g.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[ds(s),t.jsx("span",{className:"connecting-dots"})]}):ds(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 Ef({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:m,onClearPreviewOrder:h,onDragStateReset:y,onDragTabKeyChange:k,onReceiveTab:A,onHideTab:d,isGroupActive:b,allowTabShortcuts:v=!0}){const[f,C]=o.useState(null),_=o.useRef(null),g=o.useRef(null),I=o.useMemo(()=>e.map(T=>T.tabKey),[e]);dr("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(f==null?void 0:f.tabKey)||null});const{isMac:j,tabShortcuts:w,shortcutListening:x,setShortcutListening:$,saveShortcuts:N}=_c({enabled:v,sortedTabKeys:e.map(T=>T.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!f)return;const T=K=>{const F=document.querySelector("[data-pane-context-menu]");F&&F.contains(K.target)||C(null)};return window.addEventListener("mousedown",T,!0),()=>window.removeEventListener("mousedown",T,!0)},[f]),o.useEffect(()=>{const T=g.current;if(!T)return;const K=F=>{Math.abs(F.deltaY)<=Math.abs(F.deltaX)||(F.preventDefault(),T.scrollLeft+=F.deltaY)};return T.addEventListener("wheel",K,{passive:!1}),()=>T.removeEventListener("wheel",K)},[]);const L=o.useCallback((T,K,F)=>{C({x:T,y:K,tabKey:F})},[]);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:g,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(T=>t.jsx(Df,{conv:T,isActive:s===T.tabKey,isDraggedTab:a.current===T.tabKey,isTaskCompleteUnread:n.has(T.tabKey),shortcut:v?w[T.tabKey]:void 0,conversationKeys:I,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:m,onClearPreviewOrder:h,onDragStateReset:y,onDragTabKeyChange:k,onReceiveTab:A,onOpenContextMenu:L,longPressTimer:_,isGroupActive:b},T.tabKey)),e.length===0&&t.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),f&&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:f.x,top:f.y},children:[v&&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:T=>{T.stopPropagation(),$(f.tabKey),C(null)},children:["⌨ ",w[f.tabKey]?`Change shortcut (${w[f.tabKey]})`:"Set shortcut"]}),w[f.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 T={...w};delete T[f.tabKey],N(T),C(null)},children:"✕ Remove shortcut"})]}),d&&t.jsxs(t.Fragment,{children:[v&&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(f.tabKey),C(null)},children:"🚫 Hide from Dashboard"})]})]}),v&&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:T=>T.stopPropagation(),children:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",j?"⌘+1":"Ctrl+1",", ",j?"⌥+A":"Alt+A",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function $f({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:u,userName:p,groupIndex:m,onFocus:h,isSplitMode:y,numGroups:k,onMoveTab:A,onReceiveTab:d,style:b,onActiveTabChange:v,initialActiveTabId:f,initialTabOrder:C,onTabOrderChange:_,onHideTab:g,isFocused:I,allowTabShortcuts:j=!0}){const{sendCommand:w}=Dt(),x=o.useRef(null),{activeTabId:$,activeConv:N,sortedConversations:L,draggingTabRef:T,selectTab:K,handleTabReorder:F,updatePreviewOrder:M,commitPreviewOrder:P,clearPreviewOrder:O,moveTabToEnd:S,setDraggingTabKey:D}=Rf({conversations:e,initialActiveTabId:f,initialTabOrder:C,onActiveTabChange:v,onTabOrderChange:_}),z=on({sendDaemonCommand:a,activeConv:N,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),{dragOver:U,dropAction:ae,resetDragState:q,handleDragEnter:ue,handleDragOver:Z,handleDragLeave:se,handleDrop:oe}=Lf({conversations:e,numGroups:k,onMoveTab:A,onReceiveTab:d,onOwnTabDrop:S,onClearPreviewOrder:O}),Ne=N&&!Je(N)&&Es(N)==="terminal",me=o.useMemo(()=>N?s.find(Q=>Q.id===N.routeId):void 0,[s,N]),he=o.useMemo(()=>N?n.filter(Q=>Q.routeId===N.tabKey):[],[n,N]),ie=o.useMemo(()=>sn(s),[s]),V=o.useMemo(()=>new Set(L.filter(Q=>Id(Q,ie,{isOpenConversation:Q.tabKey===$})).map(Q=>Q.tabKey)),[$,ie,L]);dr("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:$,dragOver:U});const ye=o.useCallback(Q=>{Q.streamSource==="agent-stream"&&Q.agentType&&w(Q.routeId,Sc(),{agentType:Q.agentType,...Q.sessionId&&{targetSessionId:Q.sessionId}}).catch(()=>{})},[w]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:h,style:{...b,outline:U?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(Ef,{conversations:L,activeTabId:$,groupIndex:m,numGroups:k,unreadTabKeys:V,draggingTabRef:T,onFocus:h,onSelectTab:K,onConversationActivated:ye,onPreviewReorder:M,onReorderTab:F,onCommitPreviewOrder:P,onClearPreviewOrder:O,onDragStateReset:q,onDragTabKeyChange:D,onMoveTab:A,onReceiveTab:d,onHideTab:g,isGroupActive:I??!1,allowTabShortcuts:j}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ue,onDragOver:Z,onDragLeave:se,onDrop:oe,children:[U&&t.jsx(Pf,{dropAction:ae,canSplit:!!(k<4&&A)}),N?t.jsx(Ea,{activeConv:N,clearToken:r[N.tabKey]||0,isCliTerminal:!!Ne,ideEntry:me,terminalRef:x,handleModalButton:z.handleModalButton,handleRelaunch:z.handleRelaunch,handleSendChat:z.handleSendChat,isSendingChat:z.isSendingChat,sendFeedbackMessage:z.sendFeedbackMessage,handleFocusAgent:z.handleFocusAgent,isFocusingAgent:z.isFocusingAgent,actionLogs:he,userName:p,isInputActive:!y||!!I}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(Ba,{conversationsCount:e.length,isSplitMode:y,isStandalone:l,hasRegisteredMachines:u})})]})]})}function Bf({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:p,setActionLogs:m,isStandalone:h,hasRegisteredMachines:y,userName:k,focusedGroup:A,setFocusedGroup:d,moveTabToGroup:b,splitTabRelative:v,closeGroup:f,handleResizeStart:C,groupActiveTabIds:_,setGroupActiveTabIds:g,groupTabOrders:I,setGroupTabOrders:j,toggleHiddenTab:w,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(($,N)=>{const L=s&&n.length===r?`${n[N]}%`:void 0;return t.jsxs(nt.Fragment,{children:[s&&N>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:T=>C(N-1,T),onDoubleClick:()=>f(N),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($f,{style:s?{flexBasis:L??`${100/r}%`,flexGrow:L?0:1,flexShrink:L?0:1}:void 0,conversations:$,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:p,setActionLogs:m,isStandalone:h,hasRegisteredMachines:y,userName:k,groupIndex:N,isFocused:s&&A===N,onFocus:()=>d(N),isSplitMode:s,numGroups:r,onMoveTab:(T,K)=>{K==="left"&&N>0?b(T,N-1):K==="right"&&N<r-1?b(T,N+1):K==="split-left"&&r<4?v(T,N,"left"):K==="split-right"&&r<4&&v(T,N,"right")},onReceiveTab:T=>b(T,N),onActiveTabChange:T=>g(K=>(K[N]??null)===(T??null)?K:{...K,[N]:T}),initialActiveTabId:_[N],initialTabOrder:I[N],onTabOrderChange:T=>j(K=>{const F=K[N]||[];return F.length===T.length&&F.every((M,P)=>M===T[P])?K:{...K,[N]:T}}),onHideTab:w,allowTabShortcuts:x})]},N)})})}function Rc({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?ut.onScreenshot("ide-page",(m,h)=>{if(m!==e)return;const y=new FileReader;y.onload=()=>i(y.result),y.readAsDataURL(h)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var m;return e?((m=ut.onStatus)==null?void 0:m.call(ut,(h,y)=>{h===e&&y!=null&&y.screenshotUsage&&l(y.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,s]),o.useEffect(()=>{const p=e?ut.get(e):null;if(!(!p||r!=="connected"))return n!=="chat"&&s?p.startScreenshots(s):p.stopScreenshots(s),()=>{p.stopScreenshots(s)}},[n,r,s,e]);const u=o.useCallback(async(p,m)=>{const h=e?ut.get(e):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(p,m,s)},[e,r,s]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:u}}const Pc="adhdev-dashboard-action-shortcuts",Kf=1200,Wf={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Of(){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 Dc(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 ra(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function Yr(e){const s=Object.fromEntries(Dc(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Pc)||"{}"),n={...s,...r};for(const[a,i]of Object.entries(Wf))n[a]===i&&(n[a]=s[a]);return n}catch{return s}}function Ec(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Hf({enabled:e=!0,onTrigger:s}){const r=Of(),[n,a]=o.useState(()=>Yr(r)),[i,c]=o.useState(null),[l,u]=o.useState([]),p=o.useRef({parts:[],timer:null}),m=o.useCallback(d=>{const b=[];return d.metaKey&&b.push(r?"⌘":"Meta"),d.ctrlKey&&b.push("Ctrl"),d.altKey&&b.push(r?"⌥":"Alt"),d.shiftKey&&d.key.length!==1&&b.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(d.key)?null:(b.push(Ec(d.key)),b.join("+"))},[r]),h=o.useCallback(d=>{a(d);try{localStorage.setItem(Pc,JSON.stringify(d))}catch{}},[]);o.useEffect(()=>{const d=Yr(r),b=Object.entries(n),v=Object.entries(d);b.length===v.length&&b.every(([f,C])=>d[f]===C)||h(d)},[n,r,h]);const y=o.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),k=o.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},Kf))},[]);o.useEffect(()=>{if(!i)return;const d=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){c(null),u([]);return}const v=m(b);if(!v)return;const C=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(v);if(l.length===0&&C){u([v]);return}const g=[...l,v].slice(0,2).join(" "),I={...n};for(const[j,w]of Object.entries(I))w===g&&delete I[j];I[i]=g,h(I),c(null),u([])};return window.addEventListener("keydown",d,!0),()=>window.removeEventListener("keydown",d,!0)},[n,m,h,i,l]),o.useEffect(()=>{if(!e||i)return;const d=b=>{if(b.defaultPrevented)return;const v=m(b);if(!v)return;const f=b.metaKey||b.ctrlKey||b.altKey;if(ra(b.target)&&!f)return;const C=p.current.parts,_=f?[v]:[...C.slice(-1),v].slice(-2),g=_.join(" "),I=_[_.length-1],j=Object.entries(n).filter(([,L])=>!!L),w=j.find(([,L])=>L===g);if(w){b.preventDefault(),y(),s(w[0]);return}if(j.some(([,L])=>L.startsWith(`${g} `))){b.preventDefault(),p.current.parts=_,k();return}const $=j.find(([,L])=>L===I);if($){b.preventDefault(),y(),s($[0]);return}if(j.some(([,L])=>L.startsWith(`${I} `))){b.preventDefault(),p.current.parts=[I],k();return}y()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n,k,e,m,s,y,i]),o.useEffect(()=>()=>y(),[y]);const A=o.useMemo(()=>Dc(r),[r]);return{isMac:r,actionDefinitions:A,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:h}}function Uf({isTabInPopout:e,isTabFloating:s,tabShortcut:r,actionShortcuts:n}){const a=[];return e?(s&&a.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:n.dockActiveTab}),a.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:n.dockActiveTab})):s?a.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:n.dockActiveTab}):a.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:n.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:n.popoutActiveTab}),a.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:r?`Change shortcut (${r})`:"Set shortcut",shortcut:n.setActiveTabShortcut}),r&&a.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),a.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:n.hideCurrentTab,tone:"muted"}),a}function Ff(e){return e.some(s=>s.type!=="adhdev-daemon")||e.some(s=>s.type==="adhdev-daemon"&&!!s.machine)}function Oo({hasStoredLayout:e,initialDataLoaded:s,visibleConversationCount:r,ides:n}){return!e||r>0?!1:s?!Ff(n):!0}const $c=o.createContext(null);function mn(){const e=o.useContext($c);if(!e)throw new Error("DashboardDockviewContext missing");return e}function $r(e){return dt(e)||e.tabKey}function zf(e){return`remote:${e}`}function Yt(e){return e.startsWith("remote:")}function Ho(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Rn(e){var r,n,a,i,c;const s=e==null?void 0:e.defaultView;if(s)try{s.focus(),(n=(r=e==null?void 0:e.body)==null?void 0:r.focus)==null||n.call(r),(i=(a=e==null?void 0:e.documentElement)==null?void 0:a.focus)==null||i.call(a),(c=s.requestAnimationFrame)==null||c.call(s,()=>{var l,u;try{s.focus(),(u=(l=e==null?void 0:e.body)==null?void 0:l.focus)==null||u.call(l)}catch{}})}catch{}}function Ar(e,s){e.classList.remove(Un.className,Fn.className),e.classList.add(s==="light"?Un.className:Fn.className)}function Uo(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 Vf(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 Gf(e,s,r){var c;const n=[s];let a;for(const l of n){let u;for(const p of l){const m=e.addPanel({id:p.tabKey,component:"conversation",title:$r(p),params:{kind:"conversation",tabKey:p.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});u||(u=m.id)}a=u??a}return r??((c=s[0])==null?void 0:c.tabKey)??null}function Fo(e,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...e.panels])Yt(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!==$r(n)&&a.api.setTitle($r(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:$r(n),params:{kind:"conversation",tabKey:n.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function zo(e,s,r){var u,p;const n=r?zf(r):null;for(const m of[...e.panels])Yt(m.id)&&(!n||m.id!==n)&&e.removePanel(m);if(!r||!n)return;const a=Bt(s,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=Qi(a);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((p=e.panels.find(m=>!Yt(m.id)))==null?void 0:p.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function qf({params:e,api:s}){var h;const r=mn(),n=o.useRef(null),[a,i]=o.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=on({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(s.isActive);const y=[s.onDidActiveChange(k=>i(k.isActive)),s.onDidActiveGroupChange(k=>{if(!s.isActive&&!k.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const k of y)k.dispose()}},[s]);const u=o.useMemo(()=>c?r.ides.find(y=>y.id===c.routeId):void 0,[r.ides,c]),p=o.useMemo(()=>c?r.actionLogs.filter(y=>y.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(Ba,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,suppressGuide:r.hasDetachedConversationPanels})});const m=!Je(c)&&Es(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(Ea,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:m,ideEntry:u,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:p,userName:r.userName,scrollToBottomRequestNonce:((h=r.scrollToBottomRequest)==null?void 0:h.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a})})}function Yf({params:e}){var u;const s=mn(),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)||((u=r==null?void 0:r.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:l}=Rc({doId:a,targetSessionId:r?Ei(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(bi,{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 Xf(){const e=mn();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(Ba,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,suppressGuide:e.hasDetachedConversationPanels})})}function Qf(e){var k,A;Vf(e);const s=mn(),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=((k=e.api.group.activePanel)==null?void 0:k.id)===e.api.id,v=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${b?" is-active":""}${v?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(d==null?void 0:d.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:d!=null&&d.machineName?t.jsxs(t.Fragment,{children:[t.jsx("span",{children:"Live remote view"}),t.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),t.jsx("span",{className:"adhdev-dockview-tab-machine",children:d.machineName})]}):t.jsx("span",{children:"Live remote view"})})]})]})}const n=s.conversationsByTabKey.get(e.params.tabKey);if(!n)return t.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:t.jsx("div",{className:"adhdev-dockview-tab-copy",children:t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const a=((A=e.api.group.activePanel)==null?void 0:A.id)===e.api.id,i=e.api.isGroupActive,c=xa(n,s.liveSessionInboxState,{isOpenConversation:a,notificationStateBySessionId:s.notificationStateBySessionId}),l=c.isReconnecting,u=c.isConnecting,p=c.isGenerating,m=c.isWaiting,h=c.unread,y=s.tabShortcuts[n.tabKey];return t.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:dt(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:[h&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:p?t.jsx("div",{className:"tab-spinner"}):m?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):u?t.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:dt(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ds(n)}):u?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ds(n)}):t.jsx("span",{children:ds(n)})})]}),y&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:y,children:y})]})}function Jf({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:u,initialDataLoaded:p,userName:m,toggleHiddenTab:h,actionShortcuts:y,registerActionHandlers:k,onActiveTabChange:A,requestedActiveTabKey:d,requestedRemoteIdeId:b,onRequestedActiveTabConsumed:v,scrollToBottomRequest:f,notificationStateBySessionId:C}){var It,Y,$e;const{theme:_}=La(),{sendCommand:g}=Dt(),I=o.useRef(null),j=o.useRef(null),w=o.useRef(!1),x=o.useRef(!1),$=o.useRef(!1),N=o.useRef(null),L=o.useRef([]),[T,K]=o.useState(null),[F,M]=o.useState(!1),[P,O]=o.useState(!1),[S,D]=o.useState(0),z=o.useRef(null),U=o.useMemo(()=>vc(typeof window<"u"?window.innerWidth:1280),[]),ae=o.useRef(typeof window>"u"?{}:_p(U)),q=o.useMemo(()=>new Map(e.map(R=>[R.tabKey,R])),[e]),ue=o.useMemo(()=>sn(r),[r]),Z=o.useMemo(()=>{const R=I.current;return R?R.groups.some(W=>{try{const H=W.model.location.type;return H!=="floating"&&H!=="popout"?!1:W.panels.some(G=>q.has(G.id))}catch{return!1}}):!1},[q,S,e]),se=o.useCallback(()=>{var R;(R=I.current)==null||R.focus()},[]),oe=o.useCallback(R=>{const W=document,H=R.document;for(const Ie of W.querySelectorAll('link[rel="stylesheet"]')){const We=H.createElement("link");We.rel="stylesheet",We.href=Ie.href,Ie.crossOrigin&&(We.crossOrigin=Ie.crossOrigin),H.head.appendChild(We)}for(const Ie of W.querySelectorAll("style")){const We=H.createElement("style");We.textContent=Ie.textContent,H.head.appendChild(We)}const G=[];for(const Ie of W.styleSheets)try{for(const We of Ie.cssRules)We instanceof CSSStyleRule&&(We.selectorText===":root"||We.selectorText==="html")&&G.push(We.cssText)}catch{}if(G.length>0){const Ie=H.createElement("style");Ie.textContent=G.join(`
|
|
43
|
+
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:x,onCancel:()=>m(null)})]})}const Vm=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Gm(){const{preference:e,setPreference:s}=La();return t.jsx("div",{className:"flex gap-2",children:Vm.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 qm(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 Ym(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function In(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function No(e){const{r:s,g:r,b:n}=Ym(e);return .2126*In(s)+.7152*In(r)+.0722*In(n)}function Co(e,s){const r=No(e),n=No(s),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function uc(e){const s=qm(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return Co(s,r)>=Co(s,n)?r:n}const ea={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},ta={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},Xm=[{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"}}}],mc="adhdev-chat-theme",pc="adhdev-chat-theme-custom";function Dr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(mc)||"ember"}catch{return"ember"}}function $t(e){try{const s=localStorage.getItem(pc);if(s){const r=JSON.parse(s);return{...e==="dark"?ea:ta,...r[e]}}}catch{}return e==="dark"?ea:ta}function jr(e,s){try{localStorage.setItem(pc,JSON.stringify({dark:e,light:s}))}catch{}}function Rt(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 Gr(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 Qm={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function rr(e,s){var a;const r=(a=Qm[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",Gr(r,24)),n.style.setProperty("--accent-on-primary",uc(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Gr(r,18)})`),n.style.setProperty("--border-accent",Rt(r,.35)),n.style.setProperty("--nav-active-bg",Rt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Rt(r,.06)}`)}function ps(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",Rt(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",Rt(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",Rt(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",Rt(e.borderSubtle,.5)),s.style.setProperty("--border-default",Rt(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",Gr(e.accentColor,30)),s.style.setProperty("--accent-on-primary",uc(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Gr(e.accentColor,40)})`),s.style.setProperty("--border-accent",Rt(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",Rt(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Rt(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 ${Rt(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 _a(){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 Jm(e){try{localStorage.setItem(mc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=fs()?"dark":"light";ps($t(s))}else _a(),rr(e,fs()?"dark":"light")}function Zm(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Dr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=fs()?"dark":"light";ps($t(s))}else _a(),rr(e,fs()?"dark":"light")}function fs(){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 qs({title:e,children:s}){return t.jsxs("div",{style:{marginBottom:14},children:[t.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s})]})}function ep({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,a]=o.useState(()=>$t(r));o.useEffect(()=>{a($t(r))},[r]);const i=o.useCallback((c,l)=>{a(u=>{const p={...u,[c]:l},h=$t(r==="dark"?"light":"dark");return r==="dark"?jr(p,h):jr(h,p),ps(p),s(p),p})},[r,s]);return t.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[t.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",t.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsxs(qs,{title:"App Background",children:[t.jsx(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(qs,{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(qs,{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(qs,{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(qs,{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?ea:ta,u=$t(e?"light":"dark");e?jr(c,u):jr(u,c),a(c),ps(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 tp(){const[e,s]=o.useState(Dr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>$t("dark"));o.useEffect(()=>{n(fs());const u=new MutationObserver(()=>{const h=fs();n(h);const y=Dr();y==="custom"?ps($t(h?"dark":"light")):rr(y,h?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const p=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const h=fs();n(h);const y=Dr();y==="custom"?ps($t(h?"dark":"light")):rr(y,h?"dark":"light")};return p.addEventListener("change",m),()=>{u.disconnect(),p.removeEventListener("change",m)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?ps($t(r?"dark":"light")):(_a(),rr(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i($t(r?"dark":"light"))},[r]);const c=u=>{s(u),Jm(u)},l=[...Xm,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return t.jsxs("div",{children:[t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:l.map(u=>{const p=e===u.id,m=r?u.preview.dark:u.preview.light,h=u.id==="honey"||u.id==="ember"?"#1a1a1a":u.id==="custom"?a.userText:"#fff";return t.jsxs("button",{onClick:()=>c(u.id),className:"text-left rounded-xl p-3 transition-all",style:{background:p?"var(--bg-glass-hover)":"var(--bg-glass)",border:p?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:p?1:.75},children:[t.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:"Hello! How can I help?"}),t.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.userBubble,color:h},children:"Fix the bug please"}),t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:"On it! ✨"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[p&&t.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:u.id==="custom"?"🎨 Custom":u.name}),t.jsx("div",{className:"text-[10px] text-text-muted",children:u.description})]})]})]},u.id)})}),e==="custom"&&t.jsx(ep,{dark:r,onColorsChange:u=>i(u)})]})}const fc="adhdev_mobileDashboardMode_v1";function hc(){try{return localStorage.getItem(fc)==="workspace"?"workspace":"chat"}catch{return"chat"}}function sp(e){try{localStorage.setItem(fc,e)}catch{}}function rp(){const[e,s]=o.useState(!0);return o.useEffect(()=>{s(hc()==="chat")},[]),t.jsx(os,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Vt,{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),sp(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}function np(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 ap(e,s){const{sendData:r}=Dt(),{injectEntries:n,getIdes:a}=Wr(),i=Array.from(new Set(e.filter(Boolean))).join("|");o.useEffect(()=>{if(!(s!=null&&s.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const l=c.map(u=>es.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:s==null?void 0:s.intervalMs}},p=>{const m=a().find(y=>y.id===u),h=np(m,u,p);n([h])}));return()=>{l.forEach(u=>u())}},[i,a,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}const op=4e3;function xc(e,s){const{sendData:r}=Dt(),[n,a]=o.useState(null),[i,c]=o.useState(!1);return o.useEffect(()=>{if(!e){a(null),c(!1);return}if(!(s!=null&&s.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const u=es.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(s==null?void 0:s.includeSessions)!==!1,...typeof(s==null?void 0:s.limit)=="number"?{limit:s.limit}:{},...typeof(s==null?void 0:s.intervalMs)=="number"?{intervalMs:s.intervalMs}:{}}},p=>{l&&(clearTimeout(l),l=null),a(p.diagnostics),c(!1)});return u.initialSendAccepted?l=setTimeout(()=>{c(!1)},op):c(!1),()=>{l&&clearTimeout(l),u()}},[e,s==null?void 0:s.enabled,s==null?void 0:s.includeSessions,s==null?void 0:s.intervalMs,s==null?void 0:s.limit,r]),{diagnostics:n,loading:i,applyDiagnostics:a}}function ip(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function bc(e){const{sendData:s}=Dt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=ip(e);if(!a||!e.sessionId||!s){n({});return}const i=es.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}),_s.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 gc="adhdev_hiddenTabs";function cp(){try{const e=localStorage.getItem(gc);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function js(e){try{localStorage.setItem(gc,JSON.stringify([...e]))}catch{}}function lp(){const[e,s]=o.useState(cp),r=o.useCallback(p=>{s(m=>{const h=new Set(m);return h.has(p)?h.delete(p):h.add(p),js(h),h})},[]),n=o.useCallback(p=>{s(m=>{if(m.has(p))return m;const h=new Set(m);return h.add(p),js(h),h})},[]),a=o.useCallback(p=>{s(m=>{if(!m.has(p))return m;const h=new Set(m);return h.delete(p),js(h),h})},[]),i=o.useCallback(()=>{s(p=>{if(p.size===0)return p;const m=new Set;return js(m),m})},[]),c=o.useCallback((p,m)=>{s(h=>{const y=new Set(h);for(const k of m)y.add(k);return js(y),y})},[]),l=o.useCallback((p,m)=>{s(h=>{const y=new Set(h);for(const k of m)y.delete(k);return js(y),y})},[]),u=o.useCallback(p=>e.has(p),[e]);return{hiddenTabs:e,toggleTab:r,hideTab:n,showTab:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function Io(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 dp(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=Io(a,s),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>Io(u,s)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function yc(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 up(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))yc(s,a)===i&&(delete n[a],r=!0);return r?n:e}function mp({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{Ai()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:Xi(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Xd(a),o.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(l=>{const u=Date.now(),p={};for(const[m,h]of Object.entries(l))u-h<5e3&&(p[m]=h);return Object.keys(p).length===Object.keys(l).length?l:p})},5500);return()=>clearTimeout(c)},[s,r]),o.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const u=l.filter(p=>p.timestamp>c).slice(-100);return u.length===l.length?l:u})},6e4);return()=>clearInterval(i)},[n]),null}function pp(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 An(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 fp(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?fp(Ps(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 hp(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 xp(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 bp(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 gp(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 yp(e,s){const r=new Map;for(const n of e){const a=s.get(n.routeId)||n;for(const i of is({routeId:n.routeId}))r.set(i,a);for(const i of is({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of is({tabKey:n.tabKey}))r.set(i,n)}return r}function vp(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function wp(e){const s=vp(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=Ps(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function jp({ides:e,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:a}){const i=o.useMemo(()=>pp(e),[e]),c=o.useMemo(()=>sc(e),[e]),l=o.useRef([]),u=o.useRef([]),p=o.useRef([]),m=o.useRef(new Map),h=o.useRef(new Map),y=o.useMemo(()=>{const g=new Map,I=[];for(const $ of i){const{connectionState:N="new",machineName:L}=rc($,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),T=bp($,r),K=hp($),F=m.current.get($.id);if(F&&F.ide===$&&F.sourceSignature===K&&F.connectionState===N&&F.machineName===L&&gp(F.localRefs,T)){g.set($.id,F),I.push(...F.conversations);continue}const M=Ma($,r,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),P={ide:$,sourceSignature:K,connectionState:N,machineName:L,localRefs:T,conversations:M};g.set($.id,P),I.push(...M)}m.current=g;const j=new Map,w=$=>{const N=wp($),L=h.current.get($.tabKey);if(L&&L.signature===N)return j.set($.tabKey,L),L.timestamp;const T={signature:N,timestamp:$i($)||(L==null?void 0:L.timestamp)||0};return j.set($.tabKey,T),T.timestamp},x=[...I].sort(($,N)=>Bi($,N,w));return h.current=j,x},[i,r,s,c]),k=o.useMemo(()=>{const g=xp(y,n);return An(l.current,g)?l.current:(l.current=g,g)},[y,n]),A=o.useMemo(()=>{const g=new Map,I=Array.from(new Set(k.map(j=>j.routeId)));for(const j of I){const w=Bt(k,j);w&&g.set(j,w)}return g},[k]),d=o.useMemo(()=>{const g=new Map;for(const I of k){const j=A.get(I.routeId),w=I.streamSource==="native"&&j?j:I;for(const x of is({providerSessionId:I.providerSessionId,sessionId:I.sessionId}))g.set(x,w)}return g},[k,A]),b=o.useMemo(()=>yp(k,A),[k,A]),v=o.useCallback(g=>{if(g)return d.get(g)},[d]),f=o.useCallback(g=>{if(g)return b.get(g)},[b]),C=o.useMemo(()=>{const g=k.filter(I=>!a.has(I.tabKey));return An(u.current,g)?u.current:(u.current=g,g)},[k,a]),_=o.useMemo(()=>{const g=C.map(I=>I.tabKey);return An(p.current,g)?p.current:(p.current=g,g)},[C]);return{chatIdes:i,conversations:k,visibleConversations:C,visibleTabKeys:_,resolveConversationBySessionId:v,resolveConversationByTarget:f}}function kp({isMobile:e,urlActiveTab:s,resolveConversationBySessionId:r,setSearchParams:n}){const a=o.useMemo(()=>{var l;return e||!s?null:((l=r(s))==null?void 0:l.tabKey)??null},[e,r,s]),i=o.useMemo(()=>{var l;return!e||!s?null:((l=r(s))==null?void 0:l.tabKey)??null},[e,r,s]),c=o.useCallback(()=>{s&&n(l=>{const u=new URLSearchParams(l);return u.delete("activeTab"),u},{replace:!0})},[n,s]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function Sp({ides:e,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:a}){o.useEffect(()=>{lt.setIdes(e)},[e]),o.useEffect(()=>{lt.setResolveAction((i,c,l)=>{s(i,c,l).catch(()=>{})})},[s]),o.useEffect(()=>{const i=lt.onToast(u=>{r(m=>m.some(y=>y.message===u.message&&u.timestamp-y.timestamp<3e3)?m:[...m.slice(-4),{id:u.id,message:u.message,type:u.type,timestamp:u.timestamp,targetKey:u.targetKey,actions:u.actions}]);const p=u.duration||5e3;setTimeout(()=>r(m=>m.filter(h=>h.id!==u.id)),p)}),c=lt.onSystemMessage((u,p)=>{var k,A;const m=a(u),h=(k=p._localId)==null?void 0:k.startsWith("sys_approval_"),y=!!(m&&(m.status==="waiting_approval"||(A=m.modalButtons)!=null&&A.length||m.modalMessage));h&&y||n(d=>({...d,[u]:[...d[u]||[],p]}))}),l=lt.onClearSystemMessage((u,p)=>{n(m=>{var h;return(h=m[u])!=null&&h.length?{...m,[u]:m[u].filter(y=>{var k;return!(y.role==="system"&&((k=y._localId)!=null&&k.startsWith(p)))})}:m})});return()=>{i(),c(),l()}},[r,n]),o.useEffect(()=>{const i=Vi.on("status_event",c=>{lt.handleRawEvent(c,"ws")});return()=>{i()}},[]),o.useEffect(()=>{var c;const i=l=>{var b;const u=l.data;if((u==null?void 0:u.type)!=="notification_action"||typeof u.action!="string"||!u.action.startsWith("approval_")||!(u.daemonId||u.targetSessionId||u.targetKey))return;const p=u.targetSessionId||u.targetKey||u.daemonId,m=a(p),h=(m==null?void 0:m.routeId)||u.daemonId;if(!h)return;const y=Number(u.buttonIndex),k=u.button||((b=m==null?void 0:m.modalButtons)==null?void 0:b[y])||"Approve",A=String(k).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),d=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(A);s(h,"resolve_action",{action:d?"approve":"reject",button:k,...Number.isFinite(y)&&{buttonIndex:y},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...u.targetSessionId&&{targetSessionId:u.targetSessionId}}).catch(v=>console.error("[SW Action] approval failed:",v))};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 Np="adhdev_dashboardLayout_v1",Cp="adhdev_dashboardDockview_v1",Ip="adhdev_dashboardDockviewHiddenRestore_v1",Ys={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Ra(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function vc(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function wc(e){return`${Np}:${e}`}function Ap(e){const s=wc(e);return Ra(s,null)}function Tp(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=wc(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function jc(e){return`${Cp}:${e}`}function Mp(e){const s=jc(e);return Ra(s,null)}function Lp(e,s){try{const r=jc(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function kc(e){return`${Ip}:${e}`}function _p(e){const s=kc(e);return Ra(s,{})}function Rp(e,s){try{const r=kc(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Pp(){return{groupAssignments:[...Ys.groupAssignments],focusedGroup:Ys.focusedGroup,groupActiveTabIds:{...Ys.groupActiveTabIds},groupTabOrders:{...Ys.groupTabOrders},groupSizes:[...Ys.groupSizes]}}function Dp(){const[e]=o.useState(()=>vc(typeof window<"u"?window.innerWidth:1280)),[s,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,u]=o.useState({}),[p,m]=o.useState([]),[h,y]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[k,A]=o.useState(!1),d=o.useCallback(()=>{if(k)return;const b=Ap(e)??Pp();r(new Map(b.groupAssignments)),a(b.focusedGroup),c(b.groupActiveTabIds),u(b.groupTabOrders),m(b.groupSizes),A(!0)},[k,e]);return o.useEffect(()=>{k&&Tp(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:p})},[k,e,s,n,i,l,p]),o.useEffect(()=>{const b=window.matchMedia("(max-width: 767px)"),v=f=>y(f.matches);return b.addEventListener("change",v),()=>b.removeEventListener("change",v)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:a,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:l,setGroupTabOrders:u,groupSizes:p,setGroupSizes:m,isMobile:h,hasHydratedStoredLayout:k,hydrateStoredLayout:d}}function Ep(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=ha(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function $p({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:l,setSearchParams:u,historyModalOpen:p,activeConv:m,isRefreshingHistory:h,ides:y,handleRefreshHistory:k}){const A=o.useRef(!1),d=o.useRef(!1),b=o.useRef(null),v=o.useRef(!1);o.useEffect(()=>{if(!e||A.current||s.length===0)return;if(!a){i();return}const f=r(e);if(!f)return;const C=n.get(f.tabKey)??0;c(_=>({..._,[C]:f.tabKey})),l(C),A.current=!0,d.current=!0,b.current!=null&&(window.clearTimeout(b.current),b.current=null),u(_=>{const g=new URLSearchParams(_);return g.delete("activeTab"),g},{replace:!0})},[e,s,r,n,a,i,c,l,u]),o.useEffect(()=>{if(!(d.current||a)&&s.length!==0){if(!e){i(),d.current=!0;return}if(A.current){d.current=!0;return}if(b.current==null)return b.current=window.setTimeout(()=>{b.current=null,!(d.current||a)&&(i(),d.current=!0)},1500),()=>{b.current!=null&&(window.clearTimeout(b.current),b.current=null)}}},[e,s.length,a,i]),o.useEffect(()=>{if(!p){v.current=!1;return}if(!m||v.current||h)return;const f=y.find(C=>C.id===m.routeId);f&&(!f.chats||f.chats.length===0||Ep(f.chats,m))&&(v.current=!0,k())},[p,m,h,y,k]),o.useEffect(()=>{if(!m)return;let f=null,C=0,_=-1,g=0;const I=()=>{f=null;const j=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(x=>x.offsetParent!==null);if(j.length===0){C<18&&(C+=1,f=requestAnimationFrame(I));return}let w=0;for(const x of j)x.scrollTop=x.scrollHeight,w+=x.scrollHeight;w===_?g+=1:(g=0,_=w),C+=1,!(g>=2||C>=18)&&(f=requestAnimationFrame(I))};return f=requestAnimationFrame(I),()=>{f!=null&&cancelAnimationFrame(f)}},[m==null?void 0:m.tabKey])}function Bp({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[u,p]=o.useState(null),[m,h]=o.useState(null),y=o.useMemo(()=>{if(e||!n)return null;const v=l(n);return v&&!et(v)&&!Je(v)?v:null},[e,n,l]),k=o.useMemo(()=>{const v=u==null?void 0:u.routeId;if(!v)return null;const f=u!=null&&u.tabKey?i.find(C=>C.tabKey===u.tabKey):a?i.find(C=>C.tabKey===a):null;return(f==null?void 0:f.routeId)===v?f:Bt(i,v)},[i,u,a]),A=o.useMemo(()=>{if(k)return c.find(v=>v.id===k.routeId)},[c,k]);o.useEffect(()=>{y&&(p({routeId:y.routeId,tabKey:po(y)}),h(y),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,y]);const d=o.useCallback(v=>{v&&(p({routeId:v.routeId,tabKey:po(v)}),h(v))},[]),b=o.useCallback(()=>{p(null),h(null)},[]);return{remoteDialogConv:k,remoteDialogIdeEntry:A,remoteDialogActiveConv:m,setRemoteDialogActiveConv:h,openRemoteDialog:d,closeRemoteDialog:b}}function Tn(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=ha(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function To({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:a,setLocalUserMessages:i,setClearedTabs:c}){const[l,u]=o.useState(!1),[p,m]=o.useState(!1),h=o.useCallback(async d=>{try{await e("standalone","launch_ide",{ideType:d,enableCdp:!0})}catch(b){console.error("Launch failed",b)}},[e]),y=o.useCallback(async(d,b)=>{try{const v=d||(s==null?void 0:s.daemonId)||"",f=await e(v,"switch_chat",{id:b,sessionId:b,...Ms(s)}),C=f==null?void 0:f.result;if((f==null?void 0:f.success)===!0||C==="switched"||C==="switched-by-title")return;C===!1||C==="not_found"?Gs(a,"⚠️ Session tab not found — try refreshing history"):typeof C=="string"&&C.startsWith("error:")?Gs(a,`⚠️ Switch error: ${C}`):Gs(a,"⚠️ Session switch failed")}catch(v){console.error("Switch failed",v),Gs(a,`❌ Switch failed: ${v.message||"connection error"}`)}},[s,e,a]),k=o.useCallback(async()=>{if(!(!s||l)){u(!0);try{const d=lr(s);await e(d,"new_chat",{...Ms(s)}),c(b=>({...b,[s.tabKey]:Date.now()})),i(b=>({...b,[s.tabKey]:[]}))}catch(d){console.error("New chat failed",d)}finally{u(!1)}}},[s,l,e,c,i]),A=o.useCallback(async()=>{var d,b;if(!(!s||p)){m(!0);try{const v=lr(s),f=async()=>e(v,"list_chats",{forceExpand:!0,...Ms(s)});let C=await f(),_=(C==null?void 0:C.chats)||((d=C==null?void 0:C.result)==null?void 0:d.chats);Tn(_,s)&&(await new Promise(g=>setTimeout(g,450)),C=await f(),_=(C==null?void 0:C.chats)||((b=C==null?void 0:C.result)==null?void 0:b.chats)),C!=null&&C.success&&Array.isArray(_)&&(n(s.routeId,_),Tn(_,s)&&!Tn(r,s)&&Gs(a,"⚠️ History dialog did not fully open — try once more"))}catch(v){console.error("Refresh history failed",v)}finally{m(!1)}}},[s,r,p,e,n,a]);return{isCreatingChat:l,isRefreshingHistory:p,handleLaunchIde:h,handleSwitchSession:y,handleNewChat:k,handleRefreshHistory:A}}function Kp(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 Wp(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function Mo(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 kr(e,s){const r=new Set(s),n=s.length>0?[0]:[];for(const[c,l]of e)!r.has(c)||l<=0||n.includes(l)||n.push(l);n.sort((c,l)=>c-l);const a={};n.forEach((c,l)=>{a[c]=l}),n.length===0&&(a[0]=0);const i=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const u=a[l];typeof u=="number"&&u>0&&i.set(c,u)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function Lo(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 Op(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 Hp(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 _o(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 Ro(e){return Array(e).fill(100/e)}function Up({groupAssignments:e,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:a,groupSizes:i,setGroupSizes:c,isMobile:l,visibleConversations:u,visibleTabKeys:p}){const m=o.useRef(null),h=o.useMemo(()=>kr(e,p),[e,p]),y=h.assignments,k=o.useMemo(()=>l?1:h.groupCount,[h.groupCount,l]),A=k>1,d=o.useCallback((g,I)=>{s(j=>{const w=new Map(kr(j,p).assignments);return I===0?w.delete(g):w.set(g,I),w}),n(j=>({...j,[I]:g})),r(I)},[s,p,n,r]),b=o.useCallback(g=>{s(I=>{const j=kr(I,p).assignments,w=new Map;for(const[x,$]of j)$!==g&&($>g?w.set(x,$-1):w.set(x,$));return w}),c(I=>{if(I.length<=1)return[];const j=[...I];j.splice(g,1);const w=j.reduce((x,$)=>x+$,0);return w>0?j.map(x=>x/w*100):[]}),r(0)},[s,p,c,r]),v=o.useCallback((g,I)=>{I.preventDefault();const j=m.current;if(!j)return;const w=I.clientX,x=j.offsetWidth,$=i.length===k?[...i]:Ro(k),N=T=>{const F=(T.clientX-w)/x*100,M=[...$];M[g]=Math.max(15,$[g]+F),M[g+1]=Math.max(15,$[g+1]-F),c(M)},L=()=>{document.removeEventListener("mousemove",N),document.removeEventListener("mouseup",L),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",N),document.addEventListener("mouseup",L)},[i,k,c]),f=o.useCallback((g,I,j)=>{if(k>=4)return;const w=j==="left"?I:I+1;s(x=>{const $=kr(x,p).assignments,N=new Map;for(const L of u){const T=$.get(L.tabKey)??0,K=T>=w?T+1:T;K>0&&N.set(L.tabKey,K)}return w>0&&N.set(g,w),N}),c(x=>{const $=x.length===k?[...x]:Ro(k),N=$[I]??100/k,L=Math.max(15,N/2),T=Math.max(15,N/2),K=[...$];K[I]=L,K.splice(w,0,T);const F=K.reduce((M,P)=>M+P,0);return K.map(M=>M/F*100)}),n(x=>{const $=_o(x,w);return $[w]=g,$}),a(x=>{const $=_o(x,w);return $[w]=[g],$}),r(w)},[k,s,p,u,c,n,a,r]);o.useEffect(()=>{Kp(e,y)||s(y)},[e,y,s]),o.useEffect(()=>{const{mapping:g,usedGroups:I}=h;n(j=>{const w=Lo(j,g);return Mo(j,w)?j:w}),a(j=>{const w=Lo(j,g);return Mo(j,w)?j:w}),r(j=>{const w=l?0:Op(j,I,g);return j===w?j:w}),c(j=>{const w=l?[]:Hp(j,I,h.groupCount);return Wp(j,w)?j:w})},[h,l,n,a,r,c]);const C=o.useMemo(()=>{const g=Array.from({length:k},()=>[]);for(const I of u){const j=y.get(I.tabKey)??0,w=Math.min(j,k-1);g[w].push(I)}return g},[u,y,k]),_=o.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:m,normalizedGroupAssignments:y,numGroups:k,isSplitMode:A,groupedConvs:C,moveTabToGroup:d,closeGroup:b,handleResizeStart:v,splitTabRelative:f,clearAllSplits:_}}function Fp({ides:e,sendDaemonCommand:s}){const r="0.8.79",n=o.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:dc(m,r)).sort((m,h)=>Number(sr(h,r))-Number(sr(m,r))),[r,e]),a=o.useMemo(()=>n.some(m=>sr(m,r)),[r,n]),[i,c]=o.useState(!1),[l,u]=o.useState({}),p=o.useCallback(async m=>{var h,y;u(k=>({...k,[m]:"upgrading"}));try{const k=await s(m,"daemon_upgrade",{});(h=k==null?void 0:k.result)!=null&&h.upgraded||(y=k==null?void 0:k.result)!=null&&y.success?u(A=>({...A,[m]:"done"})):u(A=>({...A,[m]:"error"}))}catch{u(k=>({...k,[m]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:p}}const sa="adhdev_dashboard_notifications_v1",Pa=80;function Er(e,s=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:s}function qr(e){return{...e,createdAt:Er(e.createdAt),updatedAt:Er(e.updatedAt,e.createdAt),lastEventAt:Er(e.lastEventAt,e.updatedAt||e.createdAt)}}function zp(e){const s=yi(e);return s==="unknown:"?e.id:s}function Vp(e){return[e.type,gi(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Gp(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 u=Er(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),p=Vp({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(qr({id:p,dedupKey:p,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Pi(a),preview:yu(a),createdAt:u,updatedAt:u,lastEventAt:u}))}return n.sort((a,i)=>i.updatedAt-a.updatedAt)}function qp(e,s,r=Pa){const n=new Map;for(const i of e)i.deletedAt||n.set(i.id,qr(i));for(const i of s){const c=qr(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=zp(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 Yp(e,s,r=Date.now()){return e.map(n=>n.id===s?{...n,readAt:r,updatedAt:Math.max(n.updatedAt,r)}:n)}function Xp(e,s){return e.map(r=>{if(r.id!==s)return r;const n={...r};return delete n.readAt,n})}function Qp(e,s,r=Date.now()){return e.map(n=>Or(n,s)?{...n,readAt:r,updatedAt:Math.max(n.updatedAt,r)}:n)}function Jp(e,s){return e.filter(r=>r.id!==s)}function Zp(e){return e.filter(s=>!s.readAt&&!s.deletedAt).length}function ef(e){const s=new Map;for(const r of e){if(r.deletedAt)continue;const n=is(r);if(n.length===0)continue;const a=r.readAt?0:1;for(const i of n){const c=s.get(i);if(!c){s.set(i,{unreadCount:a,latestNotificationAt:r.updatedAt,latestRecordId:r.id});continue}s.set(i,{unreadCount:c.unreadCount+a,latestNotificationAt:Math.max(c.latestNotificationAt,r.updatedAt),latestRecordId:c.latestNotificationAt>=r.updatedAt?c.latestRecordId:r.id})}}return s}function tf(){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(sa),s=e?JSON.parse(e):[];return Array.isArray(s)?s.map(r=>qr(r)).filter(r=>!r.deletedAt):[]}catch{return[]}}function sf(e){if(!(typeof window>"u"))try{const s=e.filter(r=>!r.deletedAt).slice(0,Pa);if(s.length===0){window.localStorage.removeItem(sa);return}window.localStorage.setItem(sa,JSON.stringify(s))}catch{}}function rf(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 nf(e){const{conversations:s,liveSessionInboxState:r,maxItems:n=Pa}=e,a=o.useMemo(()=>Gp(s,r),[s,r]),[i,c]=o.useState(()=>tf());o.useEffect(()=>{c(k=>{const A=qp(k,a,n);return rf(k,A)?k:A})},[a,n]),o.useEffect(()=>{sf(i)},[i]);const l=o.useMemo(()=>Zp(i),[i]),u=o.useMemo(()=>ef(i),[i]),p=o.useCallback((k,A)=>{c(d=>Yp(d,k,A))},[]),m=o.useCallback(k=>{c(A=>Xp(A,k))},[]),h=o.useCallback((k,A)=>{c(d=>Qp(d,k,A))},[]),y=o.useCallback(k=>{c(A=>Jp(A,k))},[]);return{notifications:i,unreadCount:l,notificationStateBySessionId:u,markRead:p,markUnread:m,markTargetRead:h,deleteNotification:y}}function Sc(){return"select_session"}function af(){return"open_panel"}function of({hasMessage:e,blockedMessage:s}){return e?!!s:!0}function cf(e,s,r=2e3){return e?e.tabKey===s.tabKey&&e.message===s.message&&s.timestamp-e.timestamp<r:!1}function Po(e,s){return e?e.tabKey===s.tabKey&&e.message===s.message&&e.timestamp===s.timestamp?null:e:null}function Do(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Da(e){return e instanceof Error?e.message:String(e||"")}function Eo(e){const s=Da(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function $o(e,s){const r=Da(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function on({sendDaemonCommand:e,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:a}){const[i,c]=o.useState(!1),[l,u]=o.useState(!1),[p,m]=o.useState(null),h=o.useRef(!1),y=o.useRef(null);o.useEffect(()=>{m(null)},[s==null?void 0:s.tabKey]);const k=o.useCallback(async v=>{if(!s)return!1;const f=v.trim(),C=ka(s);if(of({hasMessage:!!f,blockedMessage:C,sendInFlight:h.current}))return C&&m(C),!1;const _=Date.now(),g={tabKey:s.tabKey,message:f,timestamp:_};if(cf(y.current,g))return m(null),!0;h.current=!0,u(!0),m(null),y.current=g;const I=`${_}-${Math.random().toString(36).slice(2,8)}`,j={role:"user",content:f,timestamp:_,_localId:I},w=!0;r(x=>({...x,[g.tabKey]:[...x[g.tabKey]||[],j]}));try{const x=lr(s);if(!x)return y.current=Po(y.current,g),w&&r(L=>({...L,[g.tabKey]:(L[g.tabKey]||[]).filter(T=>T._localId!==I)})),m("Unable to send message right now."),!1;const $=await e(x,"send_chat",{message:f,...Ms(s)}),N=Do($);if(w&&(N!=null&&N.deduplicated))return r(L=>({...L,[g.tabKey]:(L[g.tabKey]||[]).filter(T=>T._localId!==I)})),m(null),!0;if((N==null?void 0:N.sent)===!1)throw new Error((N==null?void 0:N.error)||"Send failed");if((N==null?void 0:N.success)===!1)throw new Error((N==null?void 0:N.error)||"Send failed");return setTimeout(()=>{const L=Date.now()-6e4;r(T=>{const K=T[g.tabKey];if(!K)return T;const F=K.filter(M=>M.timestamp>L);return F.length===K.length?T:{...T,[g.tabKey]:F}})},6e4),m(null),!0}catch(x){const $=Da(x);return $.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",$):console.warn("Send blocked/failed",x),y.current=Po(y.current,g),r(N=>({...N,[g.tabKey]:(N[g.tabKey]||[]).filter(L=>L._localId!==I)})),m(Bu(x)),!1}finally{h.current=!1,u(!1)}},[s,e,n,r]),A=o.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await e(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(v){console.error("Relaunch failed",v)}},[s,e]),d=o.useCallback(async v=>{if(s)try{const C=(s.modalButtons||[]).indexOf(v),_=v.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),g=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(_),I=lr(s);if(!I)return;const j=await e(I,"resolve_action",{button:v,action:g?"approve":"reject",...C>=0&&{buttonIndex:C},...Ms(s)}),w=Do(j);w.success||n(x=>[...x,{routeId:s.tabKey,text:$o(v,w==null?void 0:w.error),timestamp:Date.now()}])}catch(f){Eo(f)||console.error("[ModalButton] Error:",f),n(C=>[...C,{routeId:s.tabKey,text:Eo(f)?$o(v,f):`❌ **${v}** error`,timestamp:Date.now()}])}},[s,e,n]),b=o.useCallback(async()=>{if(!(!s||i)){c(!0);try{await e(s.routeId,af(),{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(v){console.error("Focus agent failed",v)}finally{c(!1)}}},[s,i,e]);return{isSendingChat:l,sendFeedbackMessage:p,isFocusingAgent:i,handleSendChat:k,handleRelaunch:A,handleModalButton:d,handleFocusAgent:b}}const Ea=o.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m=null,handleFocusAgent:h,isFocusingAgent:y,actionLogs:k,userName:A,scrollToBottomRequestNonce:d,isInputActive:b=!0}){const v=bc(s),f=v.status||v.modalMessage||v.modalButtons?{...s,...v.status?{status:v.status}:{},...v.modalMessage!==void 0?{modalMessage:v.modalMessage}:{},...v.modalButtons!==void 0?{modalButtons:v.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(ji,{activeConv:f,onModalButton:c}),f.transport!=="pty"&&f.transport!=="acp"&&f.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(bs,{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,f.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(om,{activeConv:f,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m,isVisible:n})}),!n&&t.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(Jn,{activeConv:f,ideEntry:a,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m,handleFocusAgent:h,isFocusingAgent:y,actionLogs:k,userName:A,scrollToBottomRequestNonce:d,isInputActive:b})})]}):t.jsx(Jn,{activeConv:f,ideEntry:a,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m,handleFocusAgent:h,isFocusingAgent:y,actionLogs:k,userName:A,scrollToBottomRequestNonce:d,isInputActive:b})]})},(e,s)=>e.activeConv===s.activeConv&&e.isCliTerminal===s.isCliTerminal&&e.ideEntry===s.ideEntry&&e.terminalRef===s.terminalRef&&e.handleModalButton===s.handleModalButton&&e.handleRelaunch===s.handleRelaunch&&e.handleSendChat===s.handleSendChat&&e.isSendingChat===s.isSendingChat&&e.sendFeedbackMessage===s.sendFeedbackMessage&&e.handleFocusAgent===s.handleFocusAgent&&e.isFocusingAgent===s.isFocusingAgent&&e.actionLogs===s.actionLogs&&e.userName===s.userName&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&e.isInputActive===s.isInputActive);function lf({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:u,onBack:p,onOpenNativeConversation:m,onOpenMachine:h,onOpenHistory:y,onOpenRemote:k,onHideConversation:A,onStopCli:d,cliViewMode:b,onSetCliViewMode:v,handleSendChat:f,handleFocusAgent:C,handleModalButton:_,handleRelaunch:g}){const I=o.useRef(null),j=et(e)&&!s,w=j&&b==="terminal",x=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:`flex items-center justify-between gap-3 ${x} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:t.jsx(ca,{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:dt(e)}),t.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:t.jsx(Wi,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>m(e),onOpenMachine:()=>h(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[j&&b&&t.jsx(Sa,{mode:b,onChange:v,compact:!0}),j&&d&&t.jsx("button",{onClick:()=>{d(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:t.jsx(Nt,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>y(e),type:"button",children:t.jsx(da,{size:14})}),!s&&!j&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>k(e),type:"button",children:t.jsx(Lt,{size:14})}),A&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>A(e),type:"button",title:"Close chat",children:t.jsx(Nt,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(Ea,{activeConv:e,clearToken:0,isCliTerminal:w,ideEntry:n,terminalRef:I,handleModalButton:_,handleRelaunch:g,handleSendChat:f,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:C,isFocusingAgent:u,actionLogs:a,userName:i})})]})}const Mn={unix:{cmd:"curl -fsSL https://adhf.dev/install | sh",shell:"Terminal",prompt:"$ "},powershell:{cmd:"irm https://adhf.dev/install.ps1 | iex",shell:"PowerShell",prompt:"PS> "},cmd:{cmd:"curl -fsSL https://adhf.dev/install.cmd -o %TEMP%\\adhdev.cmd && %TEMP%\\adhdev.cmd",shell:"CMD",prompt:"> "}};function df(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Nc(){const[e,s]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{s(df())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(Mn[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:Mn[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:Mn[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 Cc({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:Lt},{key:"chats",label:"Chats",icon:Vt}];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 Sr({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 ks({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 Xs({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 Nr({item:e,type:s,getAvatarText:r,onOpenConversation:n}){const a=s==="needs_attention"||s==="task_complete",i=s==="working",c=s==="earlier",l=s==="task_complete",{isReconnecting:u,isConnecting:p}=Us(e.conversation),m=dt(e.conversation),h=ys(e.conversation),y=Yi(e.conversation,{requiresAction:s==="needs_attention"}),k=a?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":i?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",A=a?"bg-accent-primary shadow-glow":i?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":c?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",d=c?"text-text-secondary":"text-text-primary",b=c?"text-text-muted":"text-text-secondary",v=c?"text-text-secondary opacity-80":"text-text-muted",f=c?"text-text-muted opacity-80":"text-text-muted",C="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] ${k}`,onClick:()=>n(e.conversation),type:"button",children:[a||i?t.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,t.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${A}`,style:a?{color:"var(--accent-on-primary)"}:void 0,children:r(m)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${d}`,children:m}),!i&&t.jsx("span",{className:`text-[11px] font-medium shrink-0 ${f}`,children:wi(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${b}`,children:[h,u?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${C} 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…"})]}):y==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:C,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${v}`,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 Bo({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 uf({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:u,onShowConversation:p,onShowAllHidden:m,onOpenNewSession:h,onOpenMachine:y,onOpenSettings:k,onSectionChange:A,wsStatus:d="connected",isStandalone:b=!1}){const v=d==="disconnected"||d==="reconnecting"||d==="offline"||d==="auth_failed",f=c.length>0,C=s.length>0||r.length>0||n.length>0||a.length>0,_=e==="machines"?"Machines":"Chats",g=b?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",I=b?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]";return t.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[t.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${g}`,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(Zr,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:k,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(Qr,{size:18})})]})]})}),t.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${I}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:v?t.jsx(Xs,{icon:t.jsx(Bo,{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(Xs,{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(Nc,{})})}):t.jsx(ks,{children:c.map((j,w)=>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] ${w>0?"border-t border-border-subtle/70":""}`,onClick:()=>y(j.id),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:l(j.label)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:j.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:j.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[j.unread," new"]}):j.total>0?`${j.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:j.subtitle}),j.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[j.total," chat",j.total!==1?"s":"",j.unread>0?` · ${j.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},j.id))})}),e==="chats"&&s.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Sr,{title:"Needs attention",className:"mb-0"}),t.jsx(ks,{children:s.map((j,w)=>t.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:t.jsx(Nr,{item:j,type:"needs_attention",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&r.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Sr,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(ks,{children:r.map((j,w)=>t.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:t.jsx(Nr,{item:j,type:"task_complete",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&n.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Sr,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(ks,{children:n.map((j,w)=>t.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:t.jsx(Nr,{item:j,type:"working",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&t.jsx(Sr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?t.jsx(ks,{children:a.map((j,w)=>t.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:t.jsx(Nr,{item:j,type:"earlier",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))}):C?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):v?t.jsx(Xs,{icon:t.jsx(Bo,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):f?t.jsx(Xs,{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(Vt,{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(Xs,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),e==="chats"&&i.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsxs("div",{className:"mx-1 mt-4 mb-1 flex items-center justify-between gap-2 px-1 py-1 text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:[t.jsx("span",{children:"Hidden"}),t.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:m,children:"Restore all"})]}),t.jsx(ks,{className:"bg-bg-secondary/25",children:i.map((j,w)=>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 ${w>0?"border-t border-border-subtle/70":""}`,onClick:()=>p(j),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-bg-primary border border-border-subtle text-text-secondary",children:l(dt(j))}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:dt(j)}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:ys(j)}),t.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},j.tabKey))})]})]}),e==="chats"&&h&&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:h,"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(Cc,{section:e,onSectionChange:A})]})}function mf(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 Ic(e){const s=[e.workspace||"Workspace unknown"],r=gs(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=mf(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function cn(...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 pf(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 ln(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=pf(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 ff(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 hf(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function dn(e,s,r){const n=await e(s,"file_list_browse",{path:r}),a=hf(n);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(n==null?void 0:n.error)||"Could not browse folder");const i=typeof(a==null?void 0:a.path)=="string"?a.path:r,c=i.includes("\\")?"\\":"/",l=(p,m)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${m}`:p==="/"||p==="\\"?`${c}${m}`:`${p.replace(/[\\/]+$/,"")}${c}${m}`,u=Array.isArray(a==null?void 0:a.files)?a.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:typeof(p==null?void 0:p.path)=="string"&&p.path.trim()?p.path:l(i,p.name)})).sort((p,m)=>p.name.localeCompare(m.name)):[];return{path:i,directories:u}}function un({title:e,description:s,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:u,onConfirm:p}){const[m,h]=o.useState(r);o.useEffect(()=>{h(r)},[r]);const y=ff(r),k=m.trim();return t.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:t.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:l,"aria-label":"Close folder browser",children:t.jsx(Nt,{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:()=>{!y||a||u(y)},disabled:!y||a,children:[t.jsx(ca,{size:15}),"Parent"]}),t.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"text",value:m,onChange:A=>h(A.target.value),onKeyDown:A=>{A.key!=="Enter"||!k||a||(A.preventDefault(),u(k))},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:()=>{!k||a||u(k)},disabled:!k||a,children:"Go"})]})]})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):i?t.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):n.length===0?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):t.jsx("div",{className:"p-3",children:n.map(A=>t.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>u(A.path),children:[t.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(Rs,{size:17})}),t.jsxs("span",{className:"min-w-0 flex-1",children:[t.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:A.name}),t.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:A.path})]})]},A.path))})}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(k||r),disabled:!k&&!r||a,children:c})]})]})})}function $a({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:u=!1,showArgsInput:p,argsValue:m,onArgsChange:h,showModelInput:y,modelValue:k,onModelChange:A,historyProviderNode:d,onConfirm:b,onCancel:v}){const f=n==null?void 0:n.find(C=>C.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:v,"aria-label":"Close launch confirmation",children:t.jsx(Nt,{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:C=>i(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:u,children:n.map(C=>t.jsx("option",{value:C.key,children:C.label},C.key))}),(f==null?void 0:f.description)&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:f.description})]}),d,r.map(C=>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:C.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:C.value})]},`${C.label}:${C.value}`)),y&&A&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),t.jsx("input",{type:"text",value:k||"",onChange:C=>A(C.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]}),p&&h&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),t.jsx("input",{type:"text",value:m||"",onChange:C=>h(C.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:v,disabled:u,children:"Cancel"}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:b,disabled:u,children:[t.jsx(pa,{size:14}),u?l:c]})]})]})})}function Ko(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function hs(e){const{machine:s,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,i=[];a&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const u of s.workspaces||[])i.push({key:`saved:${u.id}`,label:`${u.id===s.defaultWorkspaceId?"⭐ ":""}${Ko(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const c=(r==null?void 0:r.trim())||"",l=c?(s.workspaces||[]).find(u=>u.path===c):null;if(c&&!l&&i.push({key:`custom:${c}`,label:Ko(c),description:c,workspaceId:null,workspacePath:c}),n){const u=`saved:${n}`;if(i.some(p=>p.key===u))return{options:i,selectedKey:u}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function xf(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function bf(e){return[xf(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function gf(e){return e.lastLaunchedAt?tn(e.lastLaunchedAt):""}function Ac(e){return{metaText:bf(e),updatedLabel:gf(e)}}function Ln(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function yf({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var Ve,it,ht,pt;const c=ur(),[l,u]=o.useState(!1),p=(((Ve=e.detectedIdes)==null?void 0:Ve.length)||0)>0,m=o.useMemo(()=>(e.workspaces||[]).map(je=>({id:je.id,path:je.path,label:je.label})),[e]),h=e.defaultWorkspaceId||null,[y,k]=o.useState(h||((it=m[0])==null?void 0:it.id)||""),[A,d]=o.useState(""),[b,v]=o.useState(""),[f,C]=o.useState([]),[_,g]=o.useState(!1),[I,j]=o.useState(""),[w,x]=o.useState(!1),[$,N]=o.useState(Ln(p,s.length,r.length)),L=o.useRef(null),[T,K]=o.useState(null),F=o.useRef("__home__"),[M,P]=o.useState("__home__"),[O,S]=o.useState(""),[D,z]=o.useState(""),[U,ae]=o.useState(""),[q,ue]=o.useState([]),[Z,se]=o.useState(()=>yt().textQuery),[oe,Ne]=o.useState(()=>yt().workspaceQuery),[me,he]=o.useState(()=>yt().modelQuery),[ie,V]=o.useState(()=>yt().resumableOnly),[ye,Q]=o.useState(()=>yt().sortMode),[ge,te]=o.useState(!1),[ce,ne]=o.useState(!1),we=o.useRef(null),xe=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const B=y==="__custom__"?A.trim():((ht=m.find(je=>je.id===y))==null?void 0:ht.path)||"",ke=y==="__custom__"&&!!B&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),ve=y!=="__custom__"&&((pt=m.find(je=>je.id===y))==null?void 0:pt.path)||"",Ce=o.useMemo(()=>(e.recentLaunches||[]).map(je=>je.workspace),[e]),J=o.useCallback(async je=>{g(!0),j("");try{const Ue=await a(je);v(Ue.path),d(Ue.path),C(Ue.directories)}catch(Ue){j(Ue instanceof Error?Ue.message:"Could not load folder")}finally{g(!1)}},[a]),Te=o.useCallback(()=>{var Ue;k("__custom__"),x(!0);const je=ln(e.platform,cn(A.trim(),ve,Ce,e.defaultWorkspacePath,(Ue=m.find(ze=>ze.id===h))==null?void 0:Ue.path,m.map(ze=>ze.path)));J(je)},[A,h,J,Ce,ve,e.platform,m]),He=o.useCallback(je=>{if(je!=null&&je.workspaceId){k(je.workspaceId),d("");return}if(je!=null&&je.workspacePath){k("__custom__"),d(je.workspacePath);return}k(""),d("")},[]),De=o.useCallback(je=>{if(k(je),je==="__custom__"){Te();return}d("")},[Te]),Ze=o.useCallback(je=>{k("__custom__"),d(je)},[]),Ge=o.useCallback((je,Ue)=>{L.current=Ue,F.current=je.selectedWorkspaceKey||"__home__",P(je.selectedWorkspaceKey||"__home__"),S(je.initialArgs||""),z(je.initialModel||""),ae(""),ue([]);const ze=je.providerType?`${e.id}:${je.providerType}`:null;if(dm(xe.current,ze)){const Xe=yt();se(Xe.textQuery),Ne(Xe.workspaceQuery),he(Xe.modelQuery),V(Xe.resumableOnly),Q(Xe.sortMode)}xe.current=ze,K(je),je.providerType&&i&&(te(!0),i(je.providerType).then(Xe=>ue(Xe||[])).catch(Xe=>console.warn("Failed to load saved sessions",Xe)).finally(()=>te(!1)))},[i,e.id]),Ye=o.useMemo(()=>Ji(q,{textQuery:Z,workspaceQuery:oe,modelQuery:me,resumableOnly:ie,sortMode:ye}),[me,ie,q,ye,Z,oe]);o.useEffect(()=>{U&&(Ye.some(je=>je.providerSessionId===U)||ae(""))},[Ye,U]);const ot=o.useCallback(()=>{L.current&&(ne(!0),L.current().finally(()=>{L.current=null,ne(!1),K(null)}))},[]),tt=o.useCallback(()=>{L.current=null,K(null)},[]),mt=o.useCallback(je=>{F.current=je,P(je)},[]);return o.useEffect(()=>{var je;we.current!==e.id&&(we.current=e.id,k(h||((je=m[0])==null?void 0:je.id)||"__custom__"),d(""),v(""),C([]),j(""),x(!1),se(yt().textQuery),Ne(yt().workspaceQuery),he(yt().modelQuery),V(yt().resumableOnly),Q(yt().sortMode),xe.current=null,N(Ln(p,s.length,r.length)))},[r.length,s.length,h,p,e.id,m]),o.useEffect(()=>{var je;y!=="__custom__"&&(y&&m.some(Ue=>Ue.id===y)||k(h||((je=m[0])==null?void 0:je.id)||"__custom__"))},[h,y,m]),o.useEffect(()=>{$==="ide"&&p||$==="cli"&&s.length>0||$==="acp"&&r.length>0||N(Ln(p,s.length,r.length))},[$,r.length,s.length,p]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:p,workspaceRows:m,defaultWorkspaceId:h,workspaceChoice:y,customWorkspacePath:A,browseCurrentPath:b,browseDirectories:f,browseBusy:_,browseError:I,browseDialogOpen:w,activeLauncherKind:$,launchConfirm:T,launchConfirmWorkspaceKeyRef:F,launchConfirmWorkspaceKey:M,launchConfirmArgs:O,launchConfirmModel:D,launchConfirmResumeId:U,launchConfirmSavedSessions:q,launchConfirmTextFilter:Z,launchConfirmWorkspaceFilter:oe,launchConfirmModelFilter:me,launchConfirmResumableOnly:ie,launchConfirmSortMode:ye,filteredLaunchConfirmSavedSessions:Ye,launchConfirmSessionsLoading:ge,launchConfirmBusy:ce,resolvedWorkspacePath:B,canCreateMissingWorkspace:ke,openBrowseDialog:Te,loadBrowsePath:J,handleWorkspaceChoiceChange:De,chooseCustomWorkspacePath:Ze,setCustomWorkspacePath:d,setBrowseDialogOpen:x,setActiveLauncherKind:N,openLaunchConfirm:Ge,handleConfirmLaunch:ot,closeLaunchConfirm:tt,setWorkspaceSelectionFromOption:He,setLaunchConfirmWorkspaceKeyAndSync:mt,setLaunchConfirmArgs:S,setLaunchConfirmModel:z,setLaunchConfirmResumeId:ae,setLaunchConfirmTextFilter:se,setLaunchConfirmWorkspaceFilter:Ne,setLaunchConfirmModelFilter:he,setLaunchConfirmResumableOnly:V,setLaunchConfirmSortMode:Q}}function vf({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:u,section:p,showBottomNav:m,onBack:h,onSectionChange:y,onOpenConversation:k,onOpenRecent:A,onOpenMachineDetails:d,onMachineUpgrade:b,onLaunchDetectedIde:v,onAddWorkspace:f,onBrowseDirectory:C,onLaunchWorkspaceProvider:_,onListSavedSessions:g}){const I=M=>M==="ide"?"IDE":M==="cli"?"CLI":"ACP",j=r.slice(0,4),w=s.slice(0,3),x=yf({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:C,onListSavedSessions:g}),$=o.useMemo(()=>j.map(M=>{const{metaText:P,updatedLabel:O}=Ac(M);return{key:`recent-launch:${M.id}`,primary:M.label,secondary:P,updatedLabel:O,onClick:()=>{const{options:S,selectedKey:D}=hs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspacePath:M.workspace});x.openLaunchConfirm({title:M.kind==="ide"?us("restart-ide",M.label):M.providerSessionId?Ia(M.label):us("start-fresh",M.label),description:M.kind==="ide"?ms("restart-ide"):M.providerSessionId?Aa():ms("start-fresh"),confirmLabel:M.kind==="ide"?Ks("restart-ide"):M.providerSessionId?zr(!0):Ks("start-fresh"),busyLabel:M.kind==="ide"?Ws("restart-ide"):M.providerSessionId?Na(!0):Ws("start-fresh"),workspaceOptions:S,selectedWorkspaceKey:D,details:[{label:"Mode",value:I(M.kind)},...M.providerType?[{label:"Provider",value:M.providerType}]:[]]},async()=>{const z=S.find(U=>U.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(z),await A({...M,workspace:(z==null?void 0:z.workspacePath)??null})})}}}),[x,A,j]),N=o.useMemo(()=>w.map(M=>({key:`recent-chat:${M.conversation.tabKey}`,primary:dt(M.conversation),secondary:sm(M.conversation,{timestampLabel:M.timestamp?wi(M.timestamp):null}),unread:M.unread,onClick:()=>k(M.conversation)})),[k,w]),L=x.showAllRecent?$:$.slice(0,4),T=$.length>0,K=N.length>0,F=u?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:`flex items-center justify-between gap-3 ${F} 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:h,type:"button","aria-label":"Back",children:t.jsx(ca,{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:Mt(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:[K&&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:N.map(M=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${M.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:M.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:M.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:M.secondary})]},M.key))})]}),T&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:L.map(M=>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:M.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:M.primary}),M.updatedLabel&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:M.updatedLabel})]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:M.secondary})]},M.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(M=>!M),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:M=>x.handleWorkspaceChoiceChange(M.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(M=>t.jsxs("option",{value:M.id,children:[M.id===x.defaultWorkspaceId?"⭐ ":"",rn(M.path,M.label)||M.path]},M.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(Rs,{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&&f(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(M=>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:P,selectedKey:O}=hs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspaceId:x.workspaceChoice!=="__custom__"?x.workspaceChoice:null,currentWorkspacePath:x.resolvedWorkspacePath});x.openLaunchConfirm({title:`Launch ${M.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:P,selectedWorkspaceKey:O,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:M.name}]},async()=>{const S=P.find(D=>D.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(S),v(M.type,{workspacePath:(S==null?void 0:S.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:M.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath||"Use selected workspace"})]},M.type)):(x.activeLauncherKind==="cli"?n:a).map(M=>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 P=x.activeLauncherKind==="cli"?"cli":"acp",{options:O,selectedKey:S}=hs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspaceId:x.workspaceChoice!=="__custom__"?x.workspaceChoice:null,currentWorkspacePath:x.resolvedWorkspacePath});x.openLaunchConfirm({title:`Launch ${M.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${P.toUpperCase()}`,workspaceOptions:O,selectedWorkspaceKey:S,details:[{label:"Mode",value:P.toUpperCase()},{label:"Provider",value:M.displayName}],showArgsInput:!0,showModelInput:P==="acp",initialArgs:"",initialModel:"",providerType:M.type},async()=>{const D=O.find(z=>z.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(D),_(P,M.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:[M.icon?`${M.icon} `:"",M.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath||"Use selected workspace"})]},M.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:()=>f(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(un,{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:M=>{x.loadBrowsePath(M)},onConfirm:M=>{x.chooseCustomWorkspacePath(M),x.setBrowseDialogOpen(!1)}}),x.launchConfirm&&t.jsx($a,{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?zr(!!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:Ca()}),t.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[t.jsx("input",{type:"text",value:x.launchConfirmTextFilter,onChange:M=>x.setLaunchConfirmTextFilter(M.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:M=>x.setLaunchConfirmWorkspaceFilter(M.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:M=>x.setLaunchConfirmModelFilter(M.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:M=>x.setLaunchConfirmSortMode(M.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:M=>x.setLaunchConfirmResumableOnly(M.target.checked),disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),"Resume-ready only"]}),t.jsxs("select",{value:x.launchConfirmResumeId,onChange:M=>x.setLaunchConfirmResumeId(M.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:pm()}),x.filteredLaunchConfirmSavedSessions.map(M=>t.jsxs("option",{value:M.providerSessionId,disabled:!M.canResume,children:[M.title||M.providerSessionId," ",M.canResume?"":"(workspace missing)"]},M.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 M=x.filteredLaunchConfirmSavedSessions.find(O=>O.providerSessionId===x.launchConfirmResumeId);if(!M)return null;const P=Ic(M);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:P.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:P.providerSessionId}),t.jsx("div",{className:"mt-1",children:P.metaLine}),P.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:P.updatedLabel}),P.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:P.preview})]})})()]}),onConfirm:x.handleConfirmLaunch,onCancel:x.closeLaunchConfirm}),m&&t.jsx(Cc,{section:p,onSectionChange:y})]})}function Tc(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 wf(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:gs(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):s.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var c,l,u,p,m;const a=ir(n)?"cli":As(n)?"acp":"ide",i=gs(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(ir(n)?n.cliName||n.type:As(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:As(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((m=(p=(u=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:u.at)==null?void 0:p.call(u,-1))==null?void 0:m.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function jf(e,s){const r=new Map;for(const n of s){const a=ts(n.conversation),i=r.get(a);i?i.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],i=[...a].sort((h,y)=>y.timestamp-h.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=Gn(n),u=a.filter(h=>h.unread||h.requiresAction).length,p=Tc(n),m=[n.platform||"machine",p].filter(Boolean);return{id:n.id,label:Mt(n,{fallbackId:n.id}),subtitle:m.join(" · "),unread:u,total:a.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?rm(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 Cr(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 kf({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:m,onRequestedMachineConsumed:h,requestedMobileSection:y,onRequestedMobileSectionConsumed:k,setSelectedTabKey:A,setScreen:d,setSelectedMachineId:b,setSection:v,setMachineBackTarget:f,resetMachineAction:C,markNotificationTargetRead:_}){const g=o.useRef(null),I=o.useCallback(j=>{if(!(j!=null&&j.sessionId))return;const w=Hr(j,c),x=Math.max(Date.now(),cs(j),w.lastUpdated||0);Cr("mark_read:start",{tabKey:j.tabKey,sessionId:j.sessionId,displayPrimary:dt(j),inboxBucket:w.inboxBucket,unread:w.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,activityAt:cs(j),readAt:x}),_({sessionId:j.sessionId,providerSessionId:j.providerSessionId,tabKey:j.tabKey,routeId:j.routeId}),l(ts(j)||j.routeId,"mark_session_seen",{sessionId:j.sessionId,seenAt:x}).then($=>{Cr("mark_read:result",{tabKey:j.tabKey,sessionId:j.sessionId,result:$})}).catch($=>{Cr("mark_read:error",{tabKey:j.tabKey,sessionId:j.sessionId,error:$ instanceof Error?$.message:String($)})})},[c,l]);return o.useEffect(()=>{var w;if(!n){d("inbox"),A(((w=e[0])==null?void 0:w.tabKey)||null),g.current=null;return}if(i!=="chat"){g.current=null;return}const j=`${n.tabKey}:${n.sessionId||""}`;g.current!==j&&(g.current=j,I(n))},[e,I,i,n,d,A]),o.useEffect(()=>{if(!u)return;const j=e.find(w=>w.tabKey===u);j&&(A(j.tabKey),d("chat"),p==null||p())},[e,p,u,d,A]),o.useEffect(()=>{if(!m)return;const j=s.find(w=>w.id===m);j&&(b(j.id),C(),v("machines"),f("inbox"),d("machine"),h==null||h())},[s,h,m,C,f,d,v,b]),o.useEffect(()=>{y&&(v(y),d("inbox"),k==null||k())},[k,y,d,v]),o.useEffect(()=>{const j=r.filter(w=>w.inboxBucket==="task_complete"||w.unread);j.length!==0&&Cr("inbox_state",{screen:i,selectedTabKey:a,items:j.map(w=>{const x=Hr(w.conversation,c);return{liveState:x,tabKey:w.conversation.tabKey,sessionId:w.conversation.sessionId,displayPrimary:dt(w.conversation),serverBucket:x.inboxBucket,computedBucket:w.inboxBucket,serverUnread:x.unread,computedUnread:w.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,activityAt:cs(w.conversation)}})})},[r,c,i,a]),{markConversationRead:I}}function Sf(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Wo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Nf(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Cf({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[u,p]=o.useState(null),m=o.useCallback(()=>{i("idle"),l(""),p(null)},[]),h=o.useCallback(async(f,C,_)=>{var g;try{i("loading"),l(`Launching ${C}…`);const I={ideType:C,enableCdp:!0};(g=_==null?void 0:_.workspacePath)!=null&&g.trim()&&(I.workspace=_.workspacePath.trim()),await e(f,"launch_ide",I),i("done"),l(`${C} launch requested`)}catch(I){i("error"),l(I instanceof Error?I.message:"Launch IDE failed"),console.error("Launch IDE failed",I)}},[e]),y=o.useCallback(async(f,C,_)=>{if(C.trim())try{i("loading"),l(_!=null&&_.createIfMissing?"Creating folder…":"Saving workspace…");const g=await e(f,"workspace_add",{path:C.trim(),createIfMissing:(_==null?void 0:_.createIfMissing)===!0});if(g!=null&&g.success){i("done"),l(_!=null&&_.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((g==null?void 0:g.error)||"Could not save workspace")}catch(g){i("error"),l(g instanceof Error?g.message:"Could not save workspace")}},[e]),k=o.useCallback(async f=>{var C,_,g,I,j,w;try{i("loading"),l("Starting daemon upgrade…");const x=await e(f,"daemon_upgrade",{});if((C=x==null?void 0:x.result)!=null&&C.alreadyLatest){i("done"),l(`Already on v${((_=x==null?void 0:x.result)==null?void 0:_.version)||"latest"}.`);return}if((g=x==null?void 0:x.result)!=null&&g.upgraded||(I=x==null?void 0:x.result)!=null&&I.success){i("done"),l(`Upgrade to v${((j=x==null?void 0:x.result)==null?void 0:j.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((w=x==null?void 0:x.result)==null?void 0:w.error)||"Upgrade failed")}catch(x){i("error"),l(x instanceof Error?x.message:"Upgrade failed")}},[e]),A=o.useCallback(async(f,C,_,g)=>{var w,x,$;const I=Date.now(),j={machineId:f,kind:C,providerType:_,workspaceId:(g==null?void 0:g.workspaceId)||null,workspacePath:(g==null?void 0:g.workspacePath)||null,resumeSessionId:(g==null?void 0:g.resumeSessionId)||null,startedAt:I};try{i("loading"),l(`Launching ${_}…`),p(j);const N={cliType:_};(w=g==null?void 0:g.workspacePath)!=null&&w.trim()?N.dir=g.workspacePath.trim():g!=null&&g.workspaceId&&(N.workspaceId=g.workspaceId),g!=null&&g.resumeSessionId&&(N.resumeSessionId=g.resumeSessionId),(x=g==null?void 0:g.args)!=null&&x.trim()&&(N.cliArgs=g.args.trim().split(/\s+/).filter(Boolean)),($=g==null?void 0:g.model)!=null&&$.trim()&&(N.initialModel=g.model.trim());const L=await e(f,"launch_cli",N),T=(L==null?void 0:L.result)||L,K=(T==null?void 0:T.sessionId)||(T==null?void 0:T.id);if(L!=null&&L.success&&K){p(null),i("done"),l(`${_} launched`),s(Zt(K));return}if(L!=null&&L.success){i("loading"),l(`${_} launch requested — waiting for session…`);return}p(null),i("error"),l((L==null?void 0:L.error)||(T==null?void 0:T.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(N){if(Nf(N)){i("loading"),l(`${_} launch requested — waiting for session…`);return}p(null),i("error"),l(N instanceof Error?N.message:`Could not launch ${C.toUpperCase()} workspace`)}},[s,e]),d=o.useCallback(async(f,C)=>{try{const _=await e(f,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),g=(_==null?void 0:_.result)??_;return Array.isArray(g==null?void 0:g.sessions)?g.sessions:[]}catch(_){return console.error("Failed to list saved sessions on mobile:",_),[]}},[e]),b=o.useCallback(async(f,C)=>dn(e,f,C),[e]);o.useEffect(()=>{if(!u)return;const f=Wo(u.workspacePath),C=r.find(g=>{var N,L,T,K;if(!g||g.type==="adhdev-daemon"||Sf(g.daemonId||g.id)!==u.machineId||(g.transport==="acp"?"acp":g.transport==="pty"?"cli":null)!==u.kind||String(g.agentType||g.type||"")!==u.providerType)return!1;const x=String(g.providerSessionId||"");if(u.resumeSessionId&&x)return x===u.resumeSessionId;if(f){const F=Wo(g.workspace||g.runtimeWorkspaceLabel);return F?F===f:!1}return Number(g.lastUpdated||g._lastUpdate||g.timestamp||((K=(T=(L=(N=g.activeChat)==null?void 0:N.messages)==null?void 0:L.at)==null?void 0:T.call(L,-1))==null?void 0:K.timestamp)||0)>=u.startedAt-5e3});if(!C)return;const _=Ki({entrySessionId:C.sessionId,entryInstanceId:C.instanceId,entryRouteId:C.id,conversations:n});_&&(p(null),i("done"),l(`${u.providerType} launched`),s(Zt(_)))},[n,r,s,u]),o.useEffect(()=>{if(!u)return;const f=window.setTimeout(()=>{p(C=>!C||C.startedAt!==u.startedAt?C:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(f)},[u]);const v=o.useCallback(async(f,C)=>{if(C.kind==="ide"&&C.providerType){await h(f,C.providerType,{workspacePath:C.workspace||null});return}(C.kind==="cli"||C.kind==="acp")&&C.providerType&&await A(f,C.kind,C.providerType,{workspacePath:C.workspace||null,resumeSessionId:C.providerSessionId||null})},[h,A]);return{machineAction:{state:a,message:c},resetMachineAction:m,handleLaunchDetectedIde:h,handleAddWorkspace:y,handleMachineUpgrade:k,handleLaunchWorkspaceProvider:A,handleListSavedSessions:d,handleBrowseDirectory:b,handleOpenRecent:v}}function If({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:p}){const m=o.useCallback(v=>{i(v.tabKey),c("chat"),n(v)},[n,c,i]),h=o.useCallback(v=>{const f=e.find(C=>C.routeId===v.routeId&&C.streamSource==="native");f&&(i(f.tabKey),c("chat"),n(f))},[e,n,c,i]),y=o.useCallback(()=>{n(s),c("inbox")},[n,s,c]),k=o.useCallback((v,f="inbox")=>{l(v),a(),u("machines"),p(f),c("machine")},[a,p,c,u,l]),A=o.useCallback(v=>{const f=ts(v);f&&k(f,"chat")},[k]),d=o.useCallback(()=>{a(),c(r)},[r,a,c]),b=o.useCallback(v=>{u(v),c("inbox")},[c,u]);return{openConversation:m,openNativeConversation:h,backFromConversation:y,openMachine:k,openConversationMachine:A,backFromMachine:d,changeMachineSection:b}}function Af(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function Tf(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 Ir(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Mf({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,userName:u,requestedActiveTabKey:p,onRequestedActiveTabConsumed:m,requestedMachineId:h,onRequestedMachineConsumed:y,requestedMobileSection:k,onRequestedMobileSectionConsumed:A,onOpenHistory:d,onOpenRemote:b,onStopCli:v,wsStatus:f,isConnected:C,onShowHiddenConversation:_,onShowAllHiddenConversations:g,onHideConversation:I,onOpenNewSession:j,notificationStateBySessionId:w,onMarkNotificationTargetRead:x}){const[$,N]=o.useState(()=>{var J;return((J=e[0])==null?void 0:J.tabKey)||null}),[L,T]=o.useState(()=>e[0]?"chat":"inbox"),[K,F]=o.useState("chats"),[M,P]=o.useState(null),[O,S]=o.useState("inbox"),D=Os(),z="0.8.79",U=o.useMemo(()=>e.find(J=>J.tabKey===$)||e[0]||null,[e,$]),ae=o.useMemo(()=>U?r.find(J=>J.id===U.routeId):void 0,[r,U]),q=o.useMemo(()=>!U||Je(U)||!et(U)?null:Es(U),[U]),ue=o.useMemo(()=>r.filter(J=>J.type==="adhdev-daemon").sort(ga),[r]),Z=o.useMemo(()=>ue.find(J=>J.id===M)||null,[ue,M]),se=o.useMemo(()=>sn(r),[r]),oe=on({sendDaemonCommand:a,activeConv:U||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),Ne=Cf({sendDaemonCommand:a,navigate:D,ides:r,conversations:e}),me=o.useMemo(()=>e.map(J=>{const Te=L==="chat"&&(U==null?void 0:U.tabKey)===J.tabKey,He=xa(J,se,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Te,notificationStateBySessionId:w}),De=cs(J),Ze=qi(J);return{conversation:J,timestamp:De,preview:Ze,unread:He.unread,requiresAction:He.requiresAction,isWorking:He.isWorking,inboxBucket:He.inboxBucket}}),[e,se,w,L,U]),{markConversationRead:he}=kf({conversations:e,machineEntries:ue,items:me,selectedConversation:U,selectedTabKey:$,screen:L,liveSessionInboxState:se,sendDaemonCommand:a,requestedActiveTabKey:p,onRequestedActiveTabConsumed:m,requestedMachineId:h,onRequestedMachineConsumed:y,requestedMobileSection:k,onRequestedMobileSectionConsumed:A,setSelectedTabKey:N,setScreen:T,setSelectedMachineId:P,setSection:F,setMachineBackTarget:S,resetMachineAction:Ne.resetMachineAction,markNotificationTargetRead:x}),ie=If({conversations:e,selectedConversation:U,machineBackTarget:O,markConversationRead:he,resetMachineAction:Ne.resetMachineAction,setSelectedTabKey:N,setScreen:T,setSelectedMachineId:P,setSection:F,setMachineBackTarget:S}),V=o.useMemo(()=>Ir(me.filter(J=>J.requiresAction)),[me]),ye=o.useMemo(()=>Ir(me.filter(J=>J.unread&&!J.requiresAction)),[me]),Q=o.useMemo(()=>Ir(me.filter(J=>!J.unread&&!J.requiresAction&&J.isWorking)),[me]),ge=o.useMemo(()=>Ir(me.filter(J=>!J.unread&&!J.requiresAction&&!J.isWorking)),[me]),te=o.useMemo(()=>Z?me.filter(J=>ts(J.conversation)===Z.id):[],[me,Z]),ce=o.useMemo(()=>wf(Z,r),[r,Z]),ne=(Z==null?void 0:Z.version)||null,we=!!Z&&!!ne&&!0&&ne!==z,xe=o.useMemo(()=>(Z==null?void 0:Z.availableProviders)||[],[Z]),B=o.useMemo(()=>xe.filter(J=>J.category==="cli"&&J.installed!==!1).map(J=>({type:J.type,displayName:J.displayName||J.type,icon:J.icon})),[xe]),ke=o.useMemo(()=>xe.filter(J=>J.category==="acp"&&J.installed!==!1).map(J=>({type:J.type,displayName:J.displayName||J.type,icon:J.icon})),[xe]),ve=o.useMemo(()=>jf(ue,me),[me,ue]),Ce=o.useCallback(async J=>{Z&&await Ne.handleOpenRecent(Z.id,J)},[Ne,Z]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:L==="chat"&&U?t.jsx(lf,{selectedConversation:U,isAcp:Je(U),isStandalone:l,selectedIdeEntry:ae,actionLogs:n,userName:u,isSendingChat:oe.isSendingChat,sendFeedbackMessage:oe.sendFeedbackMessage,isFocusingAgent:oe.isFocusingAgent,handleModalButton:oe.handleModalButton,handleRelaunch:oe.handleRelaunch,onBack:ie.backFromConversation,onOpenNativeConversation:ie.openNativeConversation,onOpenMachine:ie.openConversationMachine,onHideConversation:I,onOpenHistory:d,onOpenRemote:b,onStopCli:v,cliViewMode:q,onSetCliViewMode:async J=>{if(U&&q!==J)try{await a(ts(U)||U.routeId,"set_cli_view_mode",{targetSessionId:U.sessionId,cliType:Et(U),mode:J})}catch(Te){Tf(Te)?console.warn("Skipped CLI view mode switch:",Te instanceof Error?Te.message:String(Te)):console.error("Failed to switch CLI view mode:",Te)}},handleSendChat:oe.handleSendChat,handleFocusAgent:oe.handleFocusAgent}):L==="machine"&&Z?t.jsx(vf,{selectedMachineEntry:Z,selectedMachineConversations:te,selectedMachineRecentLaunches:ce,cliProviders:B,acpProviders:ke,selectedMachineNeedsUpgrade:we,appVersion:z,machineAction:Ne.machineAction,isStandalone:l,section:K,showBottomNav:O==="inbox",onBack:ie.backFromMachine,onSectionChange:ie.changeMachineSection,onOpenConversation:ie.openConversation,onOpenRecent:Ce,onOpenMachineDetails:()=>D(`/machines/${Z.id}`),onMachineUpgrade:()=>Ne.handleMachineUpgrade(Z.id),onLaunchDetectedIde:(J,Te)=>Ne.handleLaunchDetectedIde(Z.id,J,Te),onAddWorkspace:(J,Te)=>Ne.handleAddWorkspace(Z.id,J,Te),onBrowseDirectory:J=>Ne.handleBrowseDirectory(Z.id,J),onLaunchWorkspaceProvider:(J,Te,He)=>Ne.handleLaunchWorkspaceProvider(Z.id,J,Te,He),onListSavedSessions:J=>Ne.handleListSavedSessions(Z.id,J)}):t.jsx(uf,{section:K,attentionItems:V,unreadItems:ye,workingItems:Q,completedItems:ge,hiddenConversations:s,machineCards:ve,getAvatarText:Af,onOpenConversation:ie.openConversation,onShowConversation:_,onShowAllHidden:g,onOpenNewSession:j,onOpenMachine:ie.openMachine,onOpenSettings:()=>D("/settings"),onSectionChange:F,wsStatus:f,isConnected:C,isStandalone:l})})}function _n(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function Lf({conversations:e,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,u]=o.useState(!1),[p,m]=o.useState(null),h=o.useCallback(()=>{c.current=0,u(!1),m(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const y=o.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),k=o.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!_n(s,r)){m("merge");return}const v=b.currentTarget.getBoundingClientRect(),f=b.clientX-v.left,C=v.width/3;f<C?m("split-left"):f>C*2?m("split-right"):m("merge")},[s,r]),A=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,u(!1),m(null))},[]),d=o.useCallback(b=>{c.current=0,u(!1);const v=b.dataTransfer.getData("text/tab-key"),f=v?e.some(_=>_.tabKey===v):!1,C=p;if(m(null),i(),!!v){if(b.preventDefault(),C==="split-left"&&_n(s,r)){r==null||r(v,"split-left");return}if(C==="split-right"&&_n(s,r)){r==null||r(v,"split-right");return}if(f){a(v);return}n==null||n(v)}},[e,p,s,r,n,a,i]);return{dragOver:l,dropAction:p,resetDragState:h,handleDragEnter:y,handleDragOver:k,handleDragLeave:A,handleDrop:d}}function _f(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 Rf({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(s??null),[l,u]=o.useState(r??[]),[p,m]=o.useState(null),h=o.useRef(null),y=o.useRef(null),k=o.useRef(n),A=o.useRef(a);o.useEffect(()=>{k.current=n},[n]),o.useEffect(()=>{A.current=a},[a]),o.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),o.useEffect(()=>{u(j=>{const w=_f(j,e);return w.length===j.length&&w.every((x,$)=>x===j[$])?j:w})},[e]);const d=o.useMemo(()=>{const j=p??l;if(j.length===0)return e;const w=new Map(j.map((x,$)=>[x,$]));return[...e].sort((x,$)=>{const N=w.get(x.tabKey)??999,L=w.get($.tabKey)??999;return N-L})},[e,p,l]);o.useEffect(()=>{var w,x;if(d.length===0){i!==null&&(c(null),(w=k.current)==null||w.call(k,null));return}if(i&&d.some($=>$.tabKey===i))return;const j=d[0].tabKey;j!==i&&(c(j),(x=k.current)==null||x.call(k,j))},[d,i]);const b=o.useMemo(()=>d.find(j=>j.tabKey===i),[d,i]),v=o.useCallback(j=>{var w;c(j),(w=k.current)==null||w.call(k,j)},[]),f=o.useCallback((j,w,x)=>{u($=>{var K;const N=$.filter(F=>F!==j),L=N.indexOf(w);if(L<0)return $;const T=x==="left"?L:L+1;return N.splice(T,0,j),(K=A.current)==null||K.call(A,N),N}),m(null)},[]),C=o.useCallback((j,w,x)=>{const N=(l.length>0?l:e.map(K=>K.tabKey)).filter(K=>K!==j),L=N.indexOf(w);if(L<0)return;const T=x==="left"?L:L+1;N.splice(T,0,j),h.current=N,m(N)},[l,e]),_=o.useCallback(()=>{var w;const j=h.current;j&&(u(j),(w=A.current)==null||w.call(A,j))},[]),g=o.useCallback(()=>{h.current=null,m(null)},[]),I=o.useCallback(j=>{u(w=>{var $;const x=w.filter(N=>N!==j);return x.push(j),($=A.current)==null||$.call(A,x),x})},[]);return{activeTabId:i,activeConv:b,sortedConversations:d,previewOrderRef:h,draggingTabRef:y,selectTab:v,handleTabReorder:f,updatePreviewOrder:C,commitPreviewOrder:_,clearPreviewOrder:g,moveTabToEnd:I,setDraggingTabKey:j=>{y.current=j}}}function Pf({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 Ba({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(Nc,{}),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 Mc="adhdev-tab-shortcuts";function Lc(){try{return JSON.parse(localStorage.getItem(Mc)||"{}")}catch{return{}}}function _c({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>Lc()),[l,u]=o.useState(null),p=o.useCallback(h=>{const y=[];return h.metaKey&&y.push(a?"⌘":"Meta"),h.ctrlKey&&y.push("Ctrl"),h.altKey&&y.push(a?"⌥":"Alt"),h.shiftKey&&y.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(y.push(h.key.length===1?h.key.toUpperCase():h.key),y.join("+"))},[a]),m=o.useCallback(h=>{c(h);try{localStorage.setItem(Mc,JSON.stringify(h))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const h=y=>{if(y.preventDefault(),y.stopPropagation(),y.key==="Escape"){u(null);return}const k=p(y);if(!k)return;const A={...i};for(const[d,b]of Object.entries(A))b===k&&delete A[d];A[l]=k,m(A),u(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,l,i,m,p]),o.useEffect(()=>{if(!e)return;const h=y=>{if(!(!y.ctrlKey&&!y.metaKey&&!y.altKey)){for(const[k,A]of Object.entries(i))if(s.includes(k)&&p(y)===A){y.preventDefault(),r(),n(k);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,i,s,r,n,p]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:u,saveShortcuts:m}}const Df=o.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:u,onSelectTab:p,onConversationActivated:m,onPreviewReorder:h,onReorderTab:y,onCommitPreviewOrder:k,onClearPreviewOrder:A,onDragStateReset:d,onDragTabKeyChange:b,onReceiveTab:v,onOpenContextMenu:f,longPressTimer:C,isGroupActive:_}){const g=Us(s),I=g.isGenerating?"agent-tab-generating":g.isWaiting?"agent-tab-waiting":"",j=g.isReconnecting,w=o.useCallback(P=>{l.current=s.tabKey,b(s.tabKey),P.dataTransfer.setData("text/tab-key",s.tabKey),P.dataTransfer.effectAllowed="move"},[s.tabKey,l,b]),x=o.useCallback(()=>{l.current=null,b(null),k(),A(),d()},[l,b,k,A,d]),$=o.useCallback(P=>{const O=l.current;if(!(!O||O===s.tabKey)&&P.dataTransfer.types.includes("text/tab-key")){P.preventDefault(),P.stopPropagation();const S=P.currentTarget.getBoundingClientRect(),D=P.clientX<S.left+S.width/2?"left":"right";h(O,s.tabKey,D)}},[s.tabKey,l,h]),N=o.useCallback(P=>{P.preventDefault(),P.stopPropagation();const O=P.dataTransfer.getData("text/tab-key");if(O&&O!==s.tabKey){const S=P.currentTarget.getBoundingClientRect(),D=P.clientX<S.left+S.width/2?"left":"right";c.includes(O)?y(O,s.tabKey,D):v&&v(O)}A()},[s.tabKey,c,y,v,A]),L=o.useCallback(P=>{P.stopPropagation(),u(),p(s.tabKey),m(s)},[s,m,u,p]),T=o.useCallback(P=>{P.preventDefault(),f(P.clientX,P.clientY,s.tabKey)},[s.tabKey,f]),K=o.useCallback(P=>{const O=P.touches[0];C.current=setTimeout(()=>{f(O.clientX,O.clientY,s.tabKey)},600)},[s.tabKey,C,f]),F=o.useCallback(()=>{C.current&&clearTimeout(C.current)},[C]),M=["adhdev-dockview-tab",I,r&&"is-active",_&&"is-group-active",j&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:M,draggable:!0,onDragStart:w,onDragEnd:x,onDragOver:$,onDrop:N,onClick:L,onContextMenu:T,onTouchStart:K,onTouchEnd:F,onTouchMove:F,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:g.isGenerating?t.jsx("div",{className:"tab-spinner"}):g.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):g.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:dt(s),children:dt(s)}),t.jsx("span",{className:"adhdev-dockview-tab-meta",children:j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ds(s)}):g.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[ds(s),t.jsx("span",{className:"connecting-dots"})]}):ds(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 Ef({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:m,onClearPreviewOrder:h,onDragStateReset:y,onDragTabKeyChange:k,onReceiveTab:A,onHideTab:d,isGroupActive:b,allowTabShortcuts:v=!0}){const[f,C]=o.useState(null),_=o.useRef(null),g=o.useRef(null),I=o.useMemo(()=>e.map(T=>T.tabKey),[e]);dr("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(f==null?void 0:f.tabKey)||null});const{isMac:j,tabShortcuts:w,shortcutListening:x,setShortcutListening:$,saveShortcuts:N}=_c({enabled:v,sortedTabKeys:e.map(T=>T.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!f)return;const T=K=>{const F=document.querySelector("[data-pane-context-menu]");F&&F.contains(K.target)||C(null)};return window.addEventListener("mousedown",T,!0),()=>window.removeEventListener("mousedown",T,!0)},[f]),o.useEffect(()=>{const T=g.current;if(!T)return;const K=F=>{Math.abs(F.deltaY)<=Math.abs(F.deltaX)||(F.preventDefault(),T.scrollLeft+=F.deltaY)};return T.addEventListener("wheel",K,{passive:!1}),()=>T.removeEventListener("wheel",K)},[]);const L=o.useCallback((T,K,F)=>{C({x:T,y:K,tabKey:F})},[]);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:g,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(T=>t.jsx(Df,{conv:T,isActive:s===T.tabKey,isDraggedTab:a.current===T.tabKey,isTaskCompleteUnread:n.has(T.tabKey),shortcut:v?w[T.tabKey]:void 0,conversationKeys:I,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:m,onClearPreviewOrder:h,onDragStateReset:y,onDragTabKeyChange:k,onReceiveTab:A,onOpenContextMenu:L,longPressTimer:_,isGroupActive:b},T.tabKey)),e.length===0&&t.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),f&&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:f.x,top:f.y},children:[v&&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:T=>{T.stopPropagation(),$(f.tabKey),C(null)},children:["⌨ ",w[f.tabKey]?`Change shortcut (${w[f.tabKey]})`:"Set shortcut"]}),w[f.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 T={...w};delete T[f.tabKey],N(T),C(null)},children:"✕ Remove shortcut"})]}),d&&t.jsxs(t.Fragment,{children:[v&&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(f.tabKey),C(null)},children:"🚫 Hide from Dashboard"})]})]}),v&&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:T=>T.stopPropagation(),children:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",j?"⌘+1":"Ctrl+1",", ",j?"⌥+A":"Alt+A",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function $f({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:u,userName:p,groupIndex:m,onFocus:h,isSplitMode:y,numGroups:k,onMoveTab:A,onReceiveTab:d,style:b,onActiveTabChange:v,initialActiveTabId:f,initialTabOrder:C,onTabOrderChange:_,onHideTab:g,isFocused:I,allowTabShortcuts:j=!0}){const{sendCommand:w}=Dt(),x=o.useRef(null),{activeTabId:$,activeConv:N,sortedConversations:L,draggingTabRef:T,selectTab:K,handleTabReorder:F,updatePreviewOrder:M,commitPreviewOrder:P,clearPreviewOrder:O,moveTabToEnd:S,setDraggingTabKey:D}=Rf({conversations:e,initialActiveTabId:f,initialTabOrder:C,onActiveTabChange:v,onTabOrderChange:_}),z=on({sendDaemonCommand:a,activeConv:N,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),{dragOver:U,dropAction:ae,resetDragState:q,handleDragEnter:ue,handleDragOver:Z,handleDragLeave:se,handleDrop:oe}=Lf({conversations:e,numGroups:k,onMoveTab:A,onReceiveTab:d,onOwnTabDrop:S,onClearPreviewOrder:O}),Ne=N&&!Je(N)&&Es(N)==="terminal",me=o.useMemo(()=>N?s.find(Q=>Q.id===N.routeId):void 0,[s,N]),he=o.useMemo(()=>N?n.filter(Q=>Q.routeId===N.tabKey):[],[n,N]),ie=o.useMemo(()=>sn(s),[s]),V=o.useMemo(()=>new Set(L.filter(Q=>Id(Q,ie,{isOpenConversation:Q.tabKey===$})).map(Q=>Q.tabKey)),[$,ie,L]);dr("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:$,dragOver:U});const ye=o.useCallback(Q=>{Q.streamSource==="agent-stream"&&Q.agentType&&w(Q.routeId,Sc(),{agentType:Q.agentType,...Q.sessionId&&{targetSessionId:Q.sessionId}}).catch(()=>{})},[w]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:h,style:{...b,outline:U?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(Ef,{conversations:L,activeTabId:$,groupIndex:m,numGroups:k,unreadTabKeys:V,draggingTabRef:T,onFocus:h,onSelectTab:K,onConversationActivated:ye,onPreviewReorder:M,onReorderTab:F,onCommitPreviewOrder:P,onClearPreviewOrder:O,onDragStateReset:q,onDragTabKeyChange:D,onMoveTab:A,onReceiveTab:d,onHideTab:g,isGroupActive:I??!1,allowTabShortcuts:j}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ue,onDragOver:Z,onDragLeave:se,onDrop:oe,children:[U&&t.jsx(Pf,{dropAction:ae,canSplit:!!(k<4&&A)}),N?t.jsx(Ea,{activeConv:N,clearToken:r[N.tabKey]||0,isCliTerminal:!!Ne,ideEntry:me,terminalRef:x,handleModalButton:z.handleModalButton,handleRelaunch:z.handleRelaunch,handleSendChat:z.handleSendChat,isSendingChat:z.isSendingChat,sendFeedbackMessage:z.sendFeedbackMessage,handleFocusAgent:z.handleFocusAgent,isFocusingAgent:z.isFocusingAgent,actionLogs:he,userName:p,isInputActive:!y||!!I}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(Ba,{conversationsCount:e.length,isSplitMode:y,isStandalone:l,hasRegisteredMachines:u})})]})]})}function Bf({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:p,setActionLogs:m,isStandalone:h,hasRegisteredMachines:y,userName:k,focusedGroup:A,setFocusedGroup:d,moveTabToGroup:b,splitTabRelative:v,closeGroup:f,handleResizeStart:C,groupActiveTabIds:_,setGroupActiveTabIds:g,groupTabOrders:I,setGroupTabOrders:j,toggleHiddenTab:w,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(($,N)=>{const L=s&&n.length===r?`${n[N]}%`:void 0;return t.jsxs(nt.Fragment,{children:[s&&N>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:T=>C(N-1,T),onDoubleClick:()=>f(N),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($f,{style:s?{flexBasis:L??`${100/r}%`,flexGrow:L?0:1,flexShrink:L?0:1}:void 0,conversations:$,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:p,setActionLogs:m,isStandalone:h,hasRegisteredMachines:y,userName:k,groupIndex:N,isFocused:s&&A===N,onFocus:()=>d(N),isSplitMode:s,numGroups:r,onMoveTab:(T,K)=>{K==="left"&&N>0?b(T,N-1):K==="right"&&N<r-1?b(T,N+1):K==="split-left"&&r<4?v(T,N,"left"):K==="split-right"&&r<4&&v(T,N,"right")},onReceiveTab:T=>b(T,N),onActiveTabChange:T=>g(K=>(K[N]??null)===(T??null)?K:{...K,[N]:T}),initialActiveTabId:_[N],initialTabOrder:I[N],onTabOrderChange:T=>j(K=>{const F=K[N]||[];return F.length===T.length&&F.every((M,P)=>M===T[P])?K:{...K,[N]:T}}),onHideTab:w,allowTabShortcuts:x})]},N)})})}function Rc({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?ut.onScreenshot("ide-page",(m,h)=>{if(m!==e)return;const y=new FileReader;y.onload=()=>i(y.result),y.readAsDataURL(h)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var m;return e?((m=ut.onStatus)==null?void 0:m.call(ut,(h,y)=>{h===e&&y!=null&&y.screenshotUsage&&l(y.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,s]),o.useEffect(()=>{const p=e?ut.get(e):null;if(!(!p||r!=="connected"))return n!=="chat"&&s?p.startScreenshots(s):p.stopScreenshots(s),()=>{p.stopScreenshots(s)}},[n,r,s,e]);const u=o.useCallback(async(p,m)=>{const h=e?ut.get(e):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(p,m,s)},[e,r,s]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:u}}const Pc="adhdev-dashboard-action-shortcuts",Kf=1200,Wf={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Of(){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 Dc(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 ra(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function Yr(e){const s=Object.fromEntries(Dc(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Pc)||"{}"),n={...s,...r};for(const[a,i]of Object.entries(Wf))n[a]===i&&(n[a]=s[a]);return n}catch{return s}}function Ec(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Hf({enabled:e=!0,onTrigger:s}){const r=Of(),[n,a]=o.useState(()=>Yr(r)),[i,c]=o.useState(null),[l,u]=o.useState([]),p=o.useRef({parts:[],timer:null}),m=o.useCallback(d=>{const b=[];return d.metaKey&&b.push(r?"⌘":"Meta"),d.ctrlKey&&b.push("Ctrl"),d.altKey&&b.push(r?"⌥":"Alt"),d.shiftKey&&d.key.length!==1&&b.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(d.key)?null:(b.push(Ec(d.key)),b.join("+"))},[r]),h=o.useCallback(d=>{a(d);try{localStorage.setItem(Pc,JSON.stringify(d))}catch{}},[]);o.useEffect(()=>{const d=Yr(r),b=Object.entries(n),v=Object.entries(d);b.length===v.length&&b.every(([f,C])=>d[f]===C)||h(d)},[n,r,h]);const y=o.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),k=o.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},Kf))},[]);o.useEffect(()=>{if(!i)return;const d=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){c(null),u([]);return}const v=m(b);if(!v)return;const C=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(v);if(l.length===0&&C){u([v]);return}const g=[...l,v].slice(0,2).join(" "),I={...n};for(const[j,w]of Object.entries(I))w===g&&delete I[j];I[i]=g,h(I),c(null),u([])};return window.addEventListener("keydown",d,!0),()=>window.removeEventListener("keydown",d,!0)},[n,m,h,i,l]),o.useEffect(()=>{if(!e||i)return;const d=b=>{if(b.defaultPrevented)return;const v=m(b);if(!v)return;const f=b.metaKey||b.ctrlKey||b.altKey;if(ra(b.target)&&!f)return;const C=p.current.parts,_=f?[v]:[...C.slice(-1),v].slice(-2),g=_.join(" "),I=_[_.length-1],j=Object.entries(n).filter(([,L])=>!!L),w=j.find(([,L])=>L===g);if(w){b.preventDefault(),y(),s(w[0]);return}if(j.some(([,L])=>L.startsWith(`${g} `))){b.preventDefault(),p.current.parts=_,k();return}const $=j.find(([,L])=>L===I);if($){b.preventDefault(),y(),s($[0]);return}if(j.some(([,L])=>L.startsWith(`${I} `))){b.preventDefault(),p.current.parts=[I],k();return}y()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n,k,e,m,s,y,i]),o.useEffect(()=>()=>y(),[y]);const A=o.useMemo(()=>Dc(r),[r]);return{isMac:r,actionDefinitions:A,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:h}}function Uf({isTabInPopout:e,isTabFloating:s,tabShortcut:r,actionShortcuts:n}){const a=[];return e?(s&&a.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:n.dockActiveTab}),a.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:n.dockActiveTab})):s?a.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:n.dockActiveTab}):a.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:n.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:n.popoutActiveTab}),a.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:r?`Change shortcut (${r})`:"Set shortcut",shortcut:n.setActiveTabShortcut}),r&&a.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),a.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:n.hideCurrentTab,tone:"muted"}),a}function Ff(e){return e.some(s=>s.type!=="adhdev-daemon")||e.some(s=>s.type==="adhdev-daemon"&&!!s.machine)}function Oo({hasStoredLayout:e,initialDataLoaded:s,visibleConversationCount:r,ides:n}){return!e||r>0?!1:s?!Ff(n):!0}const $c=o.createContext(null);function mn(){const e=o.useContext($c);if(!e)throw new Error("DashboardDockviewContext missing");return e}function $r(e){return dt(e)||e.tabKey}function zf(e){return`remote:${e}`}function Yt(e){return e.startsWith("remote:")}function Ho(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Rn(e){var r,n,a,i,c;const s=e==null?void 0:e.defaultView;if(s)try{s.focus(),(n=(r=e==null?void 0:e.body)==null?void 0:r.focus)==null||n.call(r),(i=(a=e==null?void 0:e.documentElement)==null?void 0:a.focus)==null||i.call(a),(c=s.requestAnimationFrame)==null||c.call(s,()=>{var l,u;try{s.focus(),(u=(l=e==null?void 0:e.body)==null?void 0:l.focus)==null||u.call(l)}catch{}})}catch{}}function Ar(e,s){e.classList.remove(Un.className,Fn.className),e.classList.add(s==="light"?Un.className:Fn.className)}function Uo(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 Vf(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 Gf(e,s,r){var c;const n=[s];let a;for(const l of n){let u;for(const p of l){const m=e.addPanel({id:p.tabKey,component:"conversation",title:$r(p),params:{kind:"conversation",tabKey:p.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});u||(u=m.id)}a=u??a}return r??((c=s[0])==null?void 0:c.tabKey)??null}function Fo(e,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...e.panels])Yt(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!==$r(n)&&a.api.setTitle($r(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:$r(n),params:{kind:"conversation",tabKey:n.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function zo(e,s,r){var u,p;const n=r?zf(r):null;for(const m of[...e.panels])Yt(m.id)&&(!n||m.id!==n)&&e.removePanel(m);if(!r||!n)return;const a=Bt(s,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=Qi(a);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((p=e.panels.find(m=>!Yt(m.id)))==null?void 0:p.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function qf({params:e,api:s}){var h;const r=mn(),n=o.useRef(null),[a,i]=o.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=on({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(s.isActive);const y=[s.onDidActiveChange(k=>i(k.isActive)),s.onDidActiveGroupChange(k=>{if(!s.isActive&&!k.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const k of y)k.dispose()}},[s]);const u=o.useMemo(()=>c?r.ides.find(y=>y.id===c.routeId):void 0,[r.ides,c]),p=o.useMemo(()=>c?r.actionLogs.filter(y=>y.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(Ba,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,suppressGuide:r.hasDetachedConversationPanels})});const m=!Je(c)&&Es(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(Ea,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:m,ideEntry:u,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:p,userName:r.userName,scrollToBottomRequestNonce:((h=r.scrollToBottomRequest)==null?void 0:h.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a})})}function Yf({params:e}){var u;const s=mn(),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)||((u=r==null?void 0:r.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:l}=Rc({doId:a,targetSessionId:r?Ei(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(bi,{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 Xf(){const e=mn();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(Ba,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,suppressGuide:e.hasDetachedConversationPanels})})}function Qf(e){var k,A;Vf(e);const s=mn(),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=((k=e.api.group.activePanel)==null?void 0:k.id)===e.api.id,v=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${b?" is-active":""}${v?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(d==null?void 0:d.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:d!=null&&d.machineName?t.jsxs(t.Fragment,{children:[t.jsx("span",{children:"Live remote view"}),t.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),t.jsx("span",{className:"adhdev-dockview-tab-machine",children:d.machineName})]}):t.jsx("span",{children:"Live remote view"})})]})]})}const n=s.conversationsByTabKey.get(e.params.tabKey);if(!n)return t.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:t.jsx("div",{className:"adhdev-dockview-tab-copy",children:t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const a=((A=e.api.group.activePanel)==null?void 0:A.id)===e.api.id,i=e.api.isGroupActive,c=xa(n,s.liveSessionInboxState,{isOpenConversation:a,notificationStateBySessionId:s.notificationStateBySessionId}),l=c.isReconnecting,u=c.isConnecting,p=c.isGenerating,m=c.isWaiting,h=c.unread,y=s.tabShortcuts[n.tabKey];return t.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:dt(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:[h&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:p?t.jsx("div",{className:"tab-spinner"}):m?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):u?t.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:dt(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ds(n)}):u?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ds(n)}):t.jsx("span",{children:ds(n)})})]}),y&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:y,children:y})]})}function Jf({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:u,initialDataLoaded:p,userName:m,toggleHiddenTab:h,actionShortcuts:y,registerActionHandlers:k,onActiveTabChange:A,requestedActiveTabKey:d,requestedRemoteIdeId:b,onRequestedActiveTabConsumed:v,scrollToBottomRequest:f,notificationStateBySessionId:C}){var It,Y,$e;const{theme:_}=La(),{sendCommand:g}=Dt(),I=o.useRef(null),j=o.useRef(null),w=o.useRef(!1),x=o.useRef(!1),$=o.useRef(!1),N=o.useRef(null),L=o.useRef([]),[T,K]=o.useState(null),[F,M]=o.useState(!1),[P,O]=o.useState(!1),[S,D]=o.useState(0),z=o.useRef(null),U=o.useMemo(()=>vc(typeof window<"u"?window.innerWidth:1280),[]),ae=o.useRef(typeof window>"u"?{}:_p(U)),q=o.useMemo(()=>new Map(e.map(R=>[R.tabKey,R])),[e]),ue=o.useMemo(()=>sn(r),[r]),Z=o.useMemo(()=>{const R=I.current;return R?R.groups.some(W=>{try{const H=W.model.location.type;return H!=="floating"&&H!=="popout"?!1:W.panels.some(G=>q.has(G.id))}catch{return!1}}):!1},[q,S,e]),se=o.useCallback(()=>{var R;(R=I.current)==null||R.focus()},[]),oe=o.useCallback(R=>{const W=document,H=R.document;for(const Ie of W.querySelectorAll('link[rel="stylesheet"]')){const We=H.createElement("link");We.rel="stylesheet",We.href=Ie.href,Ie.crossOrigin&&(We.crossOrigin=Ie.crossOrigin),H.head.appendChild(We)}for(const Ie of W.querySelectorAll("style")){const We=H.createElement("style");We.textContent=Ie.textContent,H.head.appendChild(We)}const G=[];for(const Ie of W.styleSheets)try{for(const We of Ie.cssRules)We instanceof CSSStyleRule&&(We.selectorText===":root"||We.selectorText==="html")&&G.push(We.cssText)}catch{}if(G.length>0){const Ie=H.createElement("style");Ie.textContent=G.join(`
|
|
44
44
|
`),H.head.appendChild(Ie)}const re=W.documentElement.getAttribute("data-theme");re&&H.documentElement.setAttribute("data-theme",re),H.documentElement.style.colorScheme=re==="light"?"light":"dark",H.body.className=W.body.className;const Se=W.documentElement.getAttribute("style");Se&&H.documentElement.setAttribute("style",Se);const Me=H.getElementById("dv-popout-window");Me instanceof HTMLElement&&(Me.classList.add("adhdev-dockview"),Ar(Me,_))},[_]),Ne=o.useCallback(()=>{var W;const R=I.current;if(R)for(const H of R.groups)try{const G=(W=H.element)==null?void 0:W.ownerDocument;if(!G||G===document)continue;const re=G.getElementById("dv-popout-window");re instanceof HTMLElement&&(re.classList.add("adhdev-dockview"),Ar(re,_));const Se=document.documentElement.getAttribute("data-theme");Se&&G.documentElement.setAttribute("data-theme",Se),G.documentElement.style.colorScheme=Se==="light"?"light":"dark",G.body.className=document.body.className;const Me=document.documentElement.getAttribute("style");Me?G.documentElement.setAttribute("style",Me):G.documentElement.removeAttribute("style")}catch{}},[_]),me=o.useCallback(()=>{var W;const R=I.current;if(R)for(const H of R.groups)try{const G=(W=H.element)==null?void 0:W.ownerDocument;if(!G||G===document)continue;const re=G.getElementById("dv-popout-window");if(!(re instanceof HTMLElement))continue;re.classList.add("adhdev-dockview"),Ar(re,_),re.classList.toggle("is-showing-dockview-overlay",P),re.classList.toggle("is-dragging-dockview",F)}catch{}},[F,P,_]),he=o.useCallback(R=>{const W=I.current;if(!W)return;const H=W.getPanel(R);H&&W.addPopoutGroup(H,{popoutUrl:"/popout.html",onDidOpen:({window:G})=>{oe(G),we();const re=q.get(R);G.document.title=re?`${dt(re)} — ADHDev`:"ADHDev — Popout"}})},[q,oe]),ie=o.useCallback(R=>{const W=I.current,H=W==null?void 0:W.getPanel(R);if(!W||!H)return;const G=W.groups.filter(re=>{var Se;try{return((Se=re.element)==null?void 0:Se.ownerDocument)===document}catch{return!0}});G.length>0?H.api.moveTo({group:G[0],position:"center"}):H.api.moveTo({position:"center"}),H.api.setActive()},[]),V=o.useCallback(R=>{var G;const W=I.current;if(!W)return!1;const H=W.getPanel(R);if(!H)return!1;try{return((G=H.group.element)==null?void 0:G.ownerDocument)!==document}catch{return!1}},[]),ye=o.useCallback(R=>{V(R)&&ie(R),h(R)},[V,ie,h]),Q=o.useCallback(R=>{const W=I.current,H=W==null?void 0:W.getPanel(R);!W||!H||W.addFloatingGroup(H,{width:600,height:500})},[]),ge=o.useCallback(R=>{var H;const W=(H=I.current)==null?void 0:H.getPanel(R);if(!W)return!1;try{return W.group.model.location.type==="floating"}catch{return!1}},[]),te=o.useCallback(()=>{var W,H;const R=(H=(W=I.current)==null?void 0:W.activePanel)==null?void 0:H.id;return!R||Yt(R)?null:q.has(R)?R:null},[q]),ce=o.useCallback(R=>{const W=I.current,H=W==null?void 0:W.getPanel(R);if(!W||!H)return;const G=W.groups.filter(re=>{try{return re.model.location.type==="grid"}catch{return!0}});G.length>0?H.api.moveTo({group:G[0],position:"center"}):H.api.moveTo({position:"center"}),H.api.setActive()},[]),ne=o.useCallback(()=>{var Se;const R=I.current;if(!R)return;const H=R.groups.filter(Me=>{var Ie;try{return((Ie=Me.element)==null?void 0:Ie.ownerDocument)===document&&Me.model.location.type==="grid"}catch{return!1}})[0]||null,G=[...R.panels];for(const Me of G){const Ie=(Se=Me.group.element)==null?void 0:Se.ownerDocument,We=Me.group.model.location.type;Ie===document&&We==="grid"||(H&&H.id!==Me.group.id?Me.api.moveTo({group:H,position:"center"}):Me.api.moveTo({position:"center"}))}const re=R.activePanel;re&&(re.group.model.openPanel(re),re.api.setActive()),Rn(document)},[]),we=o.useCallback(()=>{var W,H;const R=I.current;if(R)for(const G of R.groups){const re=(W=G.element)==null?void 0:W.ownerDocument;if(!re||re===document)continue;const Se=re.getElementById("dv-popout-window");if(!(Se instanceof HTMLElement))continue;let Me=null,Ie=re.title||"ADHDev",We="Popout workspace";const Be=G.activePanel;if(Be)if(Me=Be.id,Yt(Be.id)){const Oe=((H=Be.params)==null?void 0:H.routeId)||Be.id.slice(7),Ee=Bt([...q.values()],Oe);Ie=Qi(Ee),We=Ee!=null&&Ee.machineName?`Remote view · ${Ee.machineName}`:"Remote view"}else{const Oe=q.get(Be.id);Ie=Oe?dt(Oe):Be.title||Be.id,We=Oe?ds(Oe):"Dockview panel"}re.title=`${Ie} — ADHDev`;let Ae=re.getElementById("adhdev-popout-header");Ae instanceof HTMLElement||(Ae=re.createElement("div"),Ae.id="adhdev-popout-header",re.body.appendChild(Ae)),Ae.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(";")),Ae.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!`]),v.current&&clearInterval(v.current))}catch{}},3e3)},[e,s.type,r,a]),I=async()=>{if(u.length!==0){i("running"),k(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${u.join(", ")}`,m?`💬 Comment: ${m}`:"",""]),d("");try{const w=await r(e,"provider_auto_fix",{providerType:s.type,functions:u,agent:c,...m?{comment:m}:{}});w!=null&&w.success&&(w!=null&&w.started||w!=null&&w.running)?(k(x=>[...x,"✅ Agent started. Monitoring progress..."]),g()):(i("error"),d((w==null?void 0:w.error)||"Failed to start auto-fix"))}catch(w){i("error"),d((w==null?void 0:w.message)||"Connection failed")}}},j=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:s.type}),k(w=>[...w,`
|
|
65
65
|
⚠️ Auto-fix cancelled.`]),i("done"),v.current&&clearInterval(v.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:w=>w.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:Th.map(w=>t.jsxs("button",{onClick:()=>l(w.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===w.value?w.color+"66":"var(--border-subtle)",background:c===w.value?w.color+"0d":"transparent"},children:[t.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===w.value?w.color:"var(--text-primary)"},children:w.label}),t.jsx("div",{className:"text-[10px] text-text-muted",children:w.desc})]},w.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:C,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:Xo.map(w=>t.jsxs("button",{onClick:()=>f(w),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:u.includes(w)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:u.includes(w)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:u.includes(w)?"#a78bfa":"var(--text-secondary)"},children:[u.includes(w)?"☑ ":"☐ ",w]},w))})]}),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:m,onChange:w=>h(w.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:[y.map((w,x)=>t.jsx("div",{className:w.startsWith("✅")?"text-green-400":"",style:w.startsWith("❌")||w.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:w},x)),a==="running"&&t.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),t.jsx("div",{ref:b})]}),A&&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:A})]})]}),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"&&u.length>0&&`${u.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:I,disabled:u.length===0,className:"machine-btn",style:{background:u.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:u.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:u.length>0?"#a78bfa":void 0,opacity:u.length===0?.4:1},children:"🚀 Start Fix"})]}),a==="running"&&t.jsx("button",{onClick:j,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"),k([]),d("")},className:"machine-btn",children:"← Back"}),t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Lh({machineId:e,providers:s,sendDaemonCommand:r,onClose:n,onCreated:a}){var g;const i=s.filter(I=>I.category==="ide"),[c,l]=o.useState(((g=i[0])==null?void 0:g.type)||""),[u,p]=o.useState(""),[m,h]=o.useState(""),[y,k]=o.useState(!1),[A,d]=o.useState(""),[b,v]=o.useState(!1),f=I=>{const j=I.toLowerCase().replace(/[^a-z0-9-]/g,"");p(j),(!m||m===C(u))&&h(C(j))},C=I=>I.split("-").map(j=>j.charAt(0).toUpperCase()+j.slice(1)).join(" "),_=async()=>{if(!(!u||!m||!c)){k(!0),d("");try{const I=await r(e,"provider_clone",{type:u,name:m,category:"ide",location:"user",cloneFrom:c});I!=null&&I.success||I!=null&&I.created?(v(!0),a==null||a(u)):d((I==null?void 0:I.error)||"Failed to create provider")}catch(I){d((I==null?void 0:I.message)||"Connection failed")}k(!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:I=>I.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:u})," has been created at ",t.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",u,"/"]})]}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",t.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",u]})," 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(I=>t.jsxs("button",{onClick:()=>l(I.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===I.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===I.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[t.jsx("div",{className:"text-lg",children:I.icon}),t.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===I.type?"#a78bfa":"var(--text-secondary)"},children:I.displayName})]},I.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:u,onChange:I=>f(I.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/",u||"...","/"]})]})]}),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:m,onChange:I=>h(I.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"})]}),A&&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:A})]})}),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:!u||!m||y,className:"machine-btn",style:{background:u&&m?"rgba(34,197,94,0.12)":void 0,borderColor:u&&m?"rgba(34,197,94,0.3)":void 0,color:u&&m?"#86efac":void 0,opacity:!u||!m||y?.4:1},children:y?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function _h({machineId:e,providers:s,sendDaemonCommand:r}){var N;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,u]=o.useState(null),[p,m]=o.useState("all"),[h,y]=o.useState(null),[k,A]=o.useState(!1),[d,b]=o.useState(null),[v,f]=o.useState("normal"),[C,_]=o.useState(""),[g,I]=o.useState(!1),j=o.useCallback(async()=>{if(e)try{const L=await r(e,"get_provider_source_config",{}),T=Yo(L);T&&(b(T),f(T.sourceMode),_(T.explicitProviderDir||""))}catch{}},[e,r]),w=o.useCallback(async()=>{if(e){c(!0);try{const L=await r(e,"get_provider_settings",{}),T=Ch(L);if(T){const K=Ih(T,s);K.sort((F,M)=>F.category.localeCompare(M.category)||F.displayName.localeCompare(M.displayName)),a(K)}}catch{}c(!1)}},[e,s,r]);o.useEffect(()=>{n.length===0&&w(),d||j()},[]);const x=async(L,T,K)=>{u(`${L}.${T}`),a(F=>F.map(M=>M.type===L?{...M,values:{...M.values,[T]:K}}:M));try{const F=await r(e,"set_provider_setting",{providerType:L,key:T,value:K});F!=null&&F.success||w()}catch{w()}u(null)},$=async()=>{I(!0);try{const L=await r(e,"set_provider_source_config",{providerSourceMode:v,providerDir:Ah(C)}),T=Yo(L);T?(b(T),f(T.sourceMode),_(T.explicitProviderDir||"")):await j(),await w()}catch{await j()}I(!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(L=>t.jsx("button",{onClick:()=>m(L),className:`machine-btn text-[10px] px-2 py-0.5 ${p===L?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:L.toUpperCase()},L))]}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:()=>A(!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:w,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:j,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:v,onChange:L=>f(L.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:C,onChange:L=>_(L.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),t.jsx("button",{onClick:()=>void $(),disabled:g,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:g?"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:"})," ",((N=d==null?void 0:d.providerRoots)==null?void 0:N.join(" → "))||"loading…"]})]})]}),p!=="all"&&n.filter(L=>L.category===p).length>1&&(()=>{const L=n.filter(M=>M.category===p),T=new Map;for(const M of L)for(const P of M.schema){if(P.type!=="boolean")continue;const O=T.get(P.key),S=!!(M.values[P.key]??P.default);O?(O.onCount+=S?1:0,O.total+=1):T.set(P.key,{label:P.label||P.key,onCount:S?1:0,total:1})}const K=[...T.entries()].filter(([,M])=>M.total===L.length);if(K.length===0)return null;const F=async(M,P)=>{for(const O of L)await x(O.type,M,P)};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 (",L.length,")"]}),t.jsx("div",{className:"flex flex-wrap gap-2",children:K.map(([M,P])=>{const O=P.onCount===P.total,S=P.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:P.label}),t.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",P.onCount,"/",P.total,")"]}),t.jsx("button",{onClick:()=>void F(M,!0),disabled:O,className:`machine-btn text-[9px] px-1.5 py-px ${O?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),t.jsx("button",{onClick:()=>void F(M,!1),disabled:S,className:`machine-btn text-[9px] px-1.5 py-px ${S?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},M)})})]})})(),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(L=>p==="all"||L.category===p).map(L=>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:L.icon}),t.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:L.displayName}),t.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:L.category==="acp"?"rgba(139,92,246,0.08)":L.category==="cli"?"rgba(59,130,246,0.08)":L.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:L.category==="acp"?"#a78bfa":L.category==="cli"?"#60a5fa":L.category==="ide"?"#86efac":"var(--status-warning)"},children:L.category}),L.category==="ide"&&t.jsx("button",{onClick:()=>y(s.find(T=>T.type===L.type)||{type:L.type,name:L.displayName,displayName:L.displayName,icon:L.icon,category:L.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:L.schema.map(T=>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:[T.label||T.key,l===`${L.type}.${T.key}`&&t.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),T.description&&t.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:T.description})]}),t.jsx("div",{className:"shrink-0",children:T.type==="boolean"?t.jsx("button",{onClick:()=>x(L.type,T.key,!(L.values[T.key]??T.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:L.values[T.key]??T.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:L.values[T.key]??T.default?21:3}})}):T.type==="number"?t.jsx("input",{type:"number",value:Number(L.values[T.key]??T.default??0)||0,min:T.min,max:T.max,onChange:K=>{const F=parseInt(K.target.value)||0;T.min!==void 0&&F<T.min||T.max!==void 0&&F>T.max||x(L.type,T.key,F)},className:"machine-input w-20 text-center text-[11px]"}):T.type==="select"&&T.options?t.jsx("select",{value:String(L.values[T.key]??T.default??""),onChange:K=>x(L.type,T.key,K.target.value),className:"machine-input text-[11px]",children:T.options.map(K=>t.jsx("option",{value:K,children:K},K))}):t.jsx("input",{type:"text",value:String(L.values[T.key]??T.default??""),onBlur:K=>x(L.type,T.key,K.target.value),className:"machine-input w-[120px] text-[11px]"})})]},T.key))})]},L.type))}),h&&t.jsx(Mh,{machineId:e,provider:h,sendDaemonCommand:r,onClose:()=>y(null)}),k&&t.jsx(Lh,{machineId:e,providers:s,sendDaemonCommand:r,onClose:()=>A(!1),onCreated:()=>{A(!1),w()}})]})}const Rh=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Ph({count:e,since:s,category:r}){return{count:e,since:s,...r==="all"?{}:{category:r}}}function Dh(e,s){return s==="all"?e:e.filter(r=>r.category===s)}function Qo(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 Eh({machineId:e,sendDaemonCommand:s}){const[r,n]=o.useState([]),[a,i]=o.useState([]),[c,l]=o.useState([]),[u,p]=o.useState(0),[m,h]=o.useState(0),[y,k]=o.useState(!0),[A,d]=o.useState("debug"),[b,v]=o.useState("all"),f=o.useRef(null),C=o.useRef(!1),_=Dh(a,b);return o.useEffect(()=>{if(!e||!y)return;const g=async()=>{try{const[j,w]=await Promise.all([s(e,"get_logs",{count:200,minLevel:A,since:u}),s(e,"get_debug_trace",Ph({count:120,since:m,category:b}))]),x=(j==null?void 0:j.result)||j;if(j!=null&&j.success&&Array.isArray(x==null?void 0:x.logs)&&x.logs.length>0){n(L=>[...L,...x.logs.map(K=>({timestamp:K.ts,level:K.level,message:`[${K.category}] ${K.message}`}))].slice(-300));const N=Math.max(...x.logs.map(L=>L.ts));p(N)}const $=(w==null?void 0:w.result)||w;if(w!=null&&w.success&&Array.isArray($==null?void 0:$.trace)){i($.trace.slice(-120));const N=$.trace.reduce((L,T)=>Math.max(L,Number(T.ts||0)),m);N>m&&h(N)}}catch{}l(_s.list({limit:120}))};g();const I=setInterval(g,3e3);return()=>clearInterval(I)},[e,y,u,m,A,b,s]),o.useEffect(()=>{if(y&&(r.length>0||a.length>0||c.length>0)){const g=C.current?"smooth":"instant";setTimeout(()=>{var I;(I=f.current)==null||I.scrollIntoView({behavior:g}),C.current=!0},50)}},[r.length,a.length,c.length,y]),o.useEffect(()=>{i([]),h(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(g=>t.jsx("button",{onClick:()=>{d(g),n([]),p(0)},className:`machine-btn text-[10px] px-2 py-0.5 ${A===g?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:g.toUpperCase()},g))]}),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:()=>k(!y),className:`machine-btn ${y?"text-green-500 border-green-500/30":""}`,children:y?"⏸ Pause":"▶ Resume"}),t.jsx("button",{onClick:()=>{n([]),i([]),l([]),p(0),h(0),_s.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((g,I)=>t.jsxs("div",{className:"flex gap-2 py-px",style:{color:g.level==="error"?"#ef4444":g.level==="warn"?"var(--status-warning)":g.level==="debug"?"#64748b":"#94a3b8"},children:[t.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(g.timestamp).toLocaleTimeString()}),t.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:g.level==="error"?"ERR":g.level==="warn"?"WRN":g.level==="debug"?"DBG":"INF"}),t.jsx("span",{children:g.message})]},`log-${I}`))]}),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:Rh.map(g=>t.jsx("button",{onClick:()=>v(g.value),className:`machine-btn text-[10px] px-2 py-0.5 ${b===g.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:g.label},g.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(g=>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(g.ts).toLocaleTimeString()}),t.jsx("span",{children:g.level.toUpperCase()}),t.jsxs("span",{children:[g.category,".",g.stage]}),g.interactionId&&t.jsxs("span",{children:["ix=",g.interactionId]})]}),t.jsx("div",{children:Qo(g.payload)})]},g.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(g=>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(g.ts).toLocaleTimeString()}),t.jsx("span",{children:g.kind}),g.topic&&t.jsxs("span",{children:["topic=",g.topic]}),g.interactionId&&t.jsxs("span",{children:["ix=",g.interactionId]})]}),t.jsx("div",{children:Qo(g.payload)})]},g.id))]})]}),t.jsx("div",{ref:f})]})}function Bn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Kn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Jo(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 $h(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Bh(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 Kh(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 Wh({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,u]=o.useState(!1),p=xc(e,{enabled:!!e,includeSessions:!0,limit:12,intervalMs:8e3}),m=p.diagnostics,h=p.loading,y=p.applyDiagnostics,k=o.useMemo(()=>sh({diagnostics:m,loading:h,refreshing:l,error:n}),[m,h,l,n]),A=o.useMemo(()=>new Map(s.map(N=>[N.sessionId||N.id,N])),[s]),d=o.useCallback(async()=>{if(e){u(!0);try{const N=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:12}),L=Bn(N);if(!(L!=null&&L.success))throw new Error((L==null?void 0:L.error)||"Could not load hosted runtime diagnostics");y(L.diagnostics||L.result||null),a("")}catch(N){const L=N instanceof Error?N.message:"Could not load hosted runtime diagnostics";a(L)}finally{u(!1)}}},[y,e,r]);o.useEffect(()=>{!e||m||h||l||d()},[m,h,e,d,l]);const b=o.useCallback(async(N,L)=>{const T=`${N}:${L.sessionId}`;if(!(N==="session_host_stop_session"&&!window.confirm(`Stop ${L.displayName}?
|
|
66
66
|
This will terminate the hosted runtime.`))){c(T);try{const K=await r(e,N,{sessionId:L.sessionId}),F=Bn(K);if(!(F!=null&&F.success))throw new Error((F==null?void 0:F.error)||"Session host action failed");const M=N==="session_host_resume_session"?"resumed":N==="session_host_restart_session"?"restarted":"stopped";lt.showToast(`Session host ${M}: ${L.displayName}`,"success"),await d()}catch(K){const F=K instanceof Error?K.message:"Session host action failed";lt.showToast(F,"warning"),a(F)}finally{c(K=>K===T?null:K)}}},[e,d,r]),v=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 L=await r(e,"session_host_prune_duplicate_sessions",{}),T=Bn(L);if(!(T!=null&&T.success))throw new Error((T==null?void 0:T.error)||"Duplicate prune failed");const K=T.result||{},F=Array.isArray(K.prunedSessionIds)?K.prunedSessionIds.length:0,M=typeof K.duplicateGroupCount=="number"?K.duplicateGroupCount:0;lt.showToast(`Pruned ${F} duplicate runtime(s) across ${M} group(s)`,"success"),await d()}catch(L){const T=L instanceof Error?L.message:"Duplicate prune failed";lt.showToast(T,"warning"),a(T)}finally{c(L=>L==="session_host_prune_duplicate_sessions"?null:L)}}},[e,d,r]),f=o.useMemo(()=>[...(m==null?void 0:m.sessions)||[]].sort((N,L)=>(L.lastActivityAt||0)-(N.lastActivityAt||0)),[m==null?void 0:m.sessions]),C=o.useMemo(()=>m!=null&&m.liveRuntimes||m!=null&&m.recoverySnapshots||m!=null&&m.inactiveRecords?{liveRuntimes:(m==null?void 0:m.liveRuntimes)||[],recoverySnapshots:(m==null?void 0:m.recoverySnapshots)||[],inactiveRecords:(m==null?void 0:m.inactiveRecords)||[]}:Uc(f),[m==null?void 0:m.inactiveRecords,m==null?void 0:m.liveRuntimes,m==null?void 0:m.recoverySnapshots,f]),_=C.liveRuntimes,g=C.recoverySnapshots,I=C.inactiveRecords,j=o.useMemo(()=>Kh(_),[_]),w=o.useMemo(()=>[...(m==null?void 0:m.recentTransitions)||[]].slice(-6).reverse(),[m==null?void 0:m.recentTransitions]),x=o.useMemo(()=>[...(m==null?void 0:m.recentLogs)||[]].reverse().find(N=>N.level==="warn"||N.level==="error")||null,[m==null?void 0:m.recentLogs]),$=(N,L)=>{var z;const T=i===`session_host_resume_session:${N.sessionId}`,K=i===`session_host_restart_session:${N.sessionId}`,F=i===`session_host_stop_session:${N.sessionId}`,M=Ka(N.meta),P=A.get(N.sessionId),O=N.attachedClients.length===1?"1 client":`${N.attachedClients.length} clients`,S=L==="recovery"?"Recover":"Resume",D=Fc(L);return t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:N.displayName||(P==null?void 0:P.cliName)||N.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Bh(N.lifecycle)}`,children:N.lifecycle}),M&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:M})]}),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:N.workspaceLabel||(P==null?void 0:P.runtimeWorkspaceLabel)||N.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:N.runtimeKey}),N.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",N.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((z=N.writeOwner)==null?void 0:z.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:$h(N.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(la,{size:11})," ",O]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",Jo(N.lastActivityAt)]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-sky-200",children:["Next: ",D]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[L==="recovery"&&(N.lifecycle==="interrupted"||N.lifecycle==="failed"||N.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{b("session_host_resume_session",N)},children:T?`${S}ing…`:S}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{b("session_host_restart_session",N)},children:K?"Restarting…":"Restart"}),L==="live"&&(N.lifecycle==="running"||N.lifecycle==="starting"||N.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",N)},children:F?"Stopping…":"Stop"})]})]})},N.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(zt,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:hm()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[j>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{v()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${j})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${k.toneClass}`,children:k.label}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{d()},disabled:h||l,children:[t.jsx(Hs,{size:13}),h||l?"Refreshing…":"Refresh"]})]})]}),n&&!m&&t.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(bs,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),t.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),m&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:m.runtimeCount})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:g.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:m.recentRequests.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),t.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:Jo(m.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Kn(m.hostStartedAt)})]})]}),x&&t.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[t.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[t.jsx(bs,{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:[Kn(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(Jr,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ls("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(N=>$(N,"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(zt,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ls("recovery")}),g.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:g.map(N=>$(N,"recovery"))})]}),I.length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ls("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:I.map(N=>$(N,"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"}),w.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:w.map(N=>{var T;const L=f.find(K=>K.sessionId===N.sessionId);return t.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-text-primary font-medium",children:(L==null?void 0:L.displayName)||((T=A.get(N.sessionId))==null?void 0:T.cliName)||N.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[N.action,N.lifecycle?` · ${N.lifecycle}`:"",N.detail?` · ${N.detail}`:"",N.error?` · ${N.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${N.success===!1?"text-red-300":"text-text-secondary"}`,children:Kn(N.timestamp)})]},`${N.sessionId}:${N.timestamp}:${N.action}`)})})]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",t.jsx("span",{className:"font-mono text-text-primary",children:m.endpoint||"unknown"}),n?t.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function Oh({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 Wn({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 On({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 Hh({machineEntry:e,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),u=r.slice(0,4),m=sr(e,"0.8.78");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(Wn,{icon:t.jsx(Vt,{size:13}),children:"Current Chats"}),t.jsx(On,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(h=>{const y=Yn(h);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(h),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:dt(h)}),y>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:tn(y)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ys(h)})]},h.tabKey)})})})]}),u.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Wn,{icon:t.jsx(pi,{size:13}),children:"Recent Launches"}),t.jsx(On,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(h=>{const{metaText:y,updatedLabel:k}=Ac(h);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(h),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:h.label}),k&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:k})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:y})]},h.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Wn,{icon:t.jsx(bs,{size:13}),children:"Daemon Update"}),t.jsx(On,{className:"border-amber-500/20 bg-amber-500/5",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:m?"Daemon update required":"Version mismatch detected"}),t.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:m?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),t.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:a,children:[t.jsx(Hs,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Uh(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const Fh={ide:{label:"IDE",plural:"IDEs",accent:"border-blue-500/[0.12]"},cli:{label:"CLI",plural:"CLIs",accent:"border-violet-500/[0.12]"},acp:{label:"ACP Agent",plural:"ACP agents",accent:"border-emerald-500/[0.12]"}};function Mr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function zh(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 Hn({category:e,machine:s,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:p}){const m=Os(),{handleLaunchIde:h,handleStopCli:y,handleRestartIde:k,handleStopIde:A,handleDetectIdes:d,launchingIde:b,launchingAgentType:v,addLog:f}=c,[C,_]=o.useState(null),g=o.useCallback(E=>{E&&m(Zt(E))},[m]),I=Fh[e],j=e==="ide",w=e==="acp",x=o.useMemo(()=>n.filter(E=>E.category===e&&(e==="ide"||E.installed!==!1)),[e,n]),$=o.useMemo(()=>new Map(x.map(E=>[E.type,E.displayName||E.type])),[x]),[N,L]=o.useState(""),[T,K]=o.useState(""),[F,M]=o.useState([]),[P,O]=o.useState(""),[S,D]=o.useState(""),[z,U]=o.useState([]),[ae,q]=o.useState(!1),[ue,Z]=o.useState(!1),[se,oe]=o.useState(""),[Ne,me]=o.useState(!1),[he,ie]=o.useState(()=>yt()),[V,ye]=o.useState(null),[Q,ge]=o.useState(p?"__custom__":u||s.defaultWorkspaceId||""),[te,ce]=o.useState(p||""),[ne,we]=o.useState([]),[xe,B]=o.useState(!1),[ke,ve]=o.useState(""),[Ce,J]=o.useState([]),[Te,He]=o.useState(!1),[De,Ze]=o.useState(""),Ge=o.useRef(null),[Ye,ot]=o.useState(null),tt=o.useRef("__home__"),[mt,Ve]=o.useState("__home__"),[it,ht]=o.useState(!1),pt=o.useRef(0),je=ne.filter(E=>!a.some(X=>X.type===E&&jt(X.status)!=="stopped")),Ue=o.useRef({});o.useEffect(()=>{s.defaultWorkspaceId&&!Q&&ge(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),o.useEffect(()=>{if(p){ge("__custom__"),ce(p);return}u&&(ge(u),ce(""))},[u,p]),o.useEffect(()=>{j||N&&(x.some(E=>E.type===N)||(L(""),D("")))},[x,j,N]);const ze=(()=>{if(Q==="__custom__")return te.trim();if(!Q)return"";const E=(s.workspaces||[]).find(X=>X.id===Q);return(E==null?void 0:E.path)||""})(),Xe=o.useCallback(E=>{const X=Ue.current[E];X&&(clearTimeout(X),delete Ue.current[E]),we(le=>le.includes(E)?le.filter(Pe=>Pe!==E):le)},[]),ft=o.useRef(new Set),gt=o.useCallback(async E=>{if(l){He(!0),Ze("");try{const X=await dn(l,r,E);ve(X.path),ce(X.path),J(X.directories)}catch(X){Ze(X instanceof Error?X.message:"Could not load folder")}finally{He(!1)}}},[r,l]),vt=o.useCallback(()=>{if(!l)return;ge("__custom__"),B(!0);const E=a.map(le=>le.workspace),X=ln(s.platform,cn(te.trim(),ze,p,E,s.defaultWorkspacePath,(s.workspaces||[]).map(le=>le.path)));gt(X)},[te,p,gt,s.defaultWorkspacePath,s.platform,s.workspaces,a,ze,l]),Ot=o.useCallback(E=>{const X=String(E.workspace||"").trim();if(!X)return;const le=(s.workspaces||[]).find(Pe=>Mr(Pe.path)===Mr(X));if(le){ge(le.id),ce("");return}ge("__custom__"),ce(X)},[s.workspaces]),Kt=o.useCallback(E=>{const X=String(E.workspace||"").trim();if(!X)return{workspaceId:null,workspacePath:"",useHome:!0};const le=(s.workspaces||[]).find(Pe=>Mr(Pe.path)===Mr(X));return le?{workspaceId:le.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:X,useHome:!1}},[s.workspaces]),Ct=o.useCallback(async E=>{if(!l||!E||e!=="cli"){U([]),q(!1),Z(!1),oe("");return}const X=pt.current+1;pt.current=X,q(!0),oe("");try{const le=await l(r,"list_saved_sessions",{providerType:E,kind:"cli",limit:30});if(pt.current!==X)return;const Pe=(le==null?void 0:le.result)??le;U(Array.isArray(Pe==null?void 0:Pe.sessions)?Pe.sessions:[])}catch(le){if(pt.current!==X)return;U([]),oe(le instanceof Error?le.message:"Could not load saved sessions")}finally{pt.current===X&&(q(!1),Z(!0))}},[e,r,l]),It=o.useMemo(()=>{if(e!=="cli"||!N)return null;const E=$.get(N)||N;return{routeId:r,daemonId:r,providerSessionId:S||void 0,transport:"pty",mode:"chat",agentName:E,agentType:N,status:"idle",title:E,messages:[],ideType:N,workspaceName:ze,displayPrimary:E,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${N}`}},[e,r,$,ze,S,N]),Y=o.useCallback(E=>{if(e==="ide"||!E){M([]);return}M(Oc(r,E))},[e,r]);o.useEffect(()=>{pt.current+=1,D(""),Y(N),Z(!1),U([]),oe(""),q(!1)},[e,Y,Ct,N]);const $e=o.useMemo(()=>z.find(E=>E.providerSessionId===S)||null,[z,S]);o.useEffect(()=>{if(!S)return;const E=z.find(X=>X.providerSessionId===S);E!=null&&E.canResume||D("")},[z,S]);const R=o.useCallback((E,X)=>{Ge.current=X,tt.current=E.selectedWorkspaceKey||"__home__",Ve(E.selectedWorkspaceKey||"__home__"),ot(E)},[]),W=o.useCallback(()=>{Ge.current&&(ht(!0),Ge.current().finally(()=>{Ge.current=null,ht(!1),ot(null)}))},[]),H=o.useCallback(E=>{if(!E)return;we(le=>le.includes(E)?le:[...le,E]);const X=Ue.current[E];X&&clearTimeout(X),Ue.current[E]=setTimeout(()=>{we(le=>le.includes(E)?le.filter(Pe=>Pe!==E):le),delete Ue.current[E]},2e4)},[]);o.useEffect(()=>{for(const X of a)jt(X.status)!=="stopped"&&(ne.includes(X.type)&&!ft.current.has(X.type)&&(ft.current.add(X.type),f("info",`${$.get(X.type)||X.type} launched`,!0)),Xe(X.type));const E=new Set(a.filter(X=>jt(X.status)!=="stopped").map(X=>X.type));ft.current.forEach(X=>{!ne.includes(X)&&!E.has(X)&&ft.current.delete(X)})},[f,Xe,a,ne,$]),o.useEffect(()=>()=>{Object.values(Ue.current).forEach(clearTimeout),Ue.current={}},[]);const[G,re]=o.useState({}),[Se,Me]=o.useState(null);o.useEffect(()=>{if(!j||!r||!l)return;(async()=>{try{const X=await l(r,"get_ide_extensions",{}),le=(X==null?void 0:X.result)||X;le!=null&&le.success&&(le!=null&&le.ideExtensions)&&re(le.ideExtensions)}catch{}})()},[j,r,l]);const Ie=E=>j?at(E.type):e==="cli"?E.cliName:E.acpName,We=j?s.detectedIdes||[]:[],Be=o.useCallback(async E=>{const X=(E==null?void 0:E.type)||N,le=(E==null?void 0:E.workspacePath)??ze;if(j){await h(X,le?{workspace:le}:void 0)&&H(X);return}const Pe=await c.runLaunchCliCore({cliType:X,dir:E!=null&&E.workspaceId?void 0:le||void 0,workspaceId:(E==null?void 0:E.workspaceId)||void 0,useHome:(E==null?void 0:E.useHome)||!(E!=null&&E.workspaceId)&&!le,argsStr:(E==null?void 0:E.argsStr)??(T||void 0),model:(E==null?void 0:E.model)??(w&&P||void 0),resumeSessionId:(E==null?void 0:E.resumeSessionId)||!w&&e==="cli"&&X===N&&S||void 0});if(Pe.success||Pe.pending){const pe=(E==null?void 0:E.argsStr)??T;!j&&(pe!=null&&pe.trim())&&(Hc(r,X,pe),Y(X)),H(X),Pe.success&&Pe.sessionId&&g(Pe.sessionId)}},[c,h,w,j,T,P,Y,H,r,g,ze,S,N]),Ae=Zi(j?"ide":w?"acp":"cli",!j&&!w&&!!S),ee=ec(j?"ide":w?"acp":"cli",!j&&!w&&!!S),Re=()=>{var pe;const E=j?at(N):$.get(N)||N,X=!j&&!w&&!!S,{options:le,selectedKey:Pe}=hs({machine:s,currentWorkspaceId:Q&&Q!=="__custom__"?Q:null,currentWorkspacePath:ze});R({title:X?Ia(E):us("start-fresh",E),description:X?Aa():ms("start-fresh"),confirmLabel:Ae,busyLabel:ee,workspaceOptions:le,selectedWorkspaceKey:Pe,details:[{label:"Mode",value:I.label},{label:"Provider",value:E},...!j&&e==="cli"&&S?[{label:"Resume",value:((pe=z.find(fe=>fe.providerSessionId===S))==null?void 0:pe.title)||S}]:[],...!j&&T.trim()?[{label:"Arguments",value:T.trim()}]:[],...w&&P.trim()?[{label:"Model",value:P.trim()}]:[]]},async()=>{const fe=le.find(Qe=>Qe.key===tt.current);fe!=null&&fe.workspaceId?(ge(fe.workspaceId),ce("")):fe!=null&&fe.workspacePath?(ge("__custom__"),ce(fe.workspacePath)):(ge(""),ce("")),await Be({workspaceId:(fe==null?void 0:fe.workspaceId)??null,workspacePath:(fe==null?void 0:fe.workspacePath)??"",useHome:!(fe!=null&&fe.workspaceId)&&!(fe!=null&&fe.workspacePath)})})},Oe=E=>{j?A(E):y(E.type,E.workspace,E.id)},Ee=o.useCallback(async(E,X,le=!1)=>{if(E.mode===X){le&&E.sessionId&&g(E.sessionId);return}if(!l||!E.sessionId){le&&E.sessionId&&g(E.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:E.sessionId,cliType:E.type,mode:X}),le&&g(E.sessionId)}catch(Pe){zh(Pe)?console.warn("Skipped CLI view mode switch:",Pe instanceof Error?Pe.message:String(Pe)):console.error("Failed to switch CLI view mode:",Pe)}},[r,g,l]),xt=t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:Q,onChange:E=>{const X=E.target.value;if(ge(X),X==="__custom__"&&l){vt();return}X!=="__custom__"&&ce("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(s.workspaces||[]).length>0?t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(s.workspaces||[]).map(E=>t.jsxs("option",{value:E.id,children:[E.id===s.defaultWorkspaceId?"⭐ ":"",rn(E.path,E.label)]},E.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…"})]})}),Q==="__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:vt,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:te,onChange:E=>ce(E.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:Q==="__custom__"?ze?t.jsx("span",{className:"font-mono truncate block",title:ze,children:ze}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":ze?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:Q===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:ze,children:ze})]}):"No workspace selected. This launches in the home directory."})]});return t.jsxs("div",{children:[t.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${I.accent} relative overflow-hidden`,children:[t.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[t.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",I.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:j?We.length>0?We.map(E=>{const X=a.find(Qe=>(Qe.type||"").toLowerCase()===(E.type||"").toLowerCase()&&jt(Qe.status)!=="stopped"),le=E.running||!!X,Pe=!!X&&X.cdpConnected,pe=ne.includes(E.type||E.id||""),fe=N===(E.type||"");return t.jsxs("button",{onClick:()=>{if(Pe&&X){const Qe=X.sessionId;Qe?m(Zt(Qe),{state:{openRemoteForTabKey:Qe}}):m("/dashboard",{state:{openRemoteForTabKey:X.id}});return}pe||L(Qe=>Qe===(E.type||"")?"":E.type||"")},disabled:!!b||pe,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Pe?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":fe?"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!==E.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(E.type)}),le&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Pe?"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:E.name||at(E.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Pe?"text-green-400":pe?"text-orange-400":fe?"text-accent-primary":"text-text-muted"}`,children:Pe?"Open Session":pe?"Starting...":fe?"Configure":"Select"})]})]},E.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(Fl,{size:14})," Scan System"]})]}):x.length>0?x.map(E=>{const X=N===E.type,le=ne.includes(E.type),pe=!!a.find(fe=>fe.type===E.type&&jt(fe.status)!=="stopped");return t.jsxs("button",{onClick:()=>L(fe=>fe===E.type?"":E.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${X?"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:E.icon}),pe&&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:E.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${le?"text-orange-400":X?"text-accent-primary":"text-text-muted"}`,children:le?"Starting...":X?"Configure":"Select"})]})]},E.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."})]})}),N&&(j?We.find(E=>E.type===N):x.find(E=>E.type===N))&&t.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[t.jsx("span",{children:"Launch Settings"}),t.jsx("span",{className:"text-accent-primary font-bold",children:j?at(N):$.get(N)||N})]}),xt,!j&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!w&&e==="cli"&&t.jsx(Vc,{busy:!!v||!!b||ne.includes(N),savedSessionsLoading:ae,savedSessionsError:se,selectedSession:$e,onRefresh:()=>void Ct(N),onOpenHistory:()=>{N&&(me(!0),zc({hasLoadedInitialResults:ue,isLoading:ae})&&Ct(N))},onClearSelection:()=>D("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[w&&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:P,onChange:E=>O(E.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:T,onChange:E=>K(E.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"}),F.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:F.map(E=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>K(E),title:E,children:E},E))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:Re,disabled:!!v||!!b||ne.includes(N),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:v===N||b===N?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+ne.filter(E=>!a.some(X=>X.type===E&&jt(X.status)!=="stopped")).length,")"]}),a.length===0&&je.length===0?t.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",I.plural," running"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[je.map(E=>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(E)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:j?at(E):$.get(E)||E}),t.jsx("div",{className:"text-[11px] text-text-muted",children:v===E?"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:${E}`)),a.map(E=>{const X=j?E:null,le=!j&&!w?E:null,Pe=jt(E.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(E.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Ie(E),(X==null?void 0:X.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",X.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[t.jsx("span",{children:E.workspace||"—"}),(le==null?void 0:le.mode)&&t.jsx("span",{className:le.mode==="chat"?"text-violet-400":"text-text-secondary",children:le.mode==="chat"?"Chat view":"Terminal view"})]}),le&&(le.runtimeKey||le.runtimeWriteOwner)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[le.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 ",le.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 pe;(pe=navigator.clipboard)==null||pe.writeText(`adhdev attach ${le.runtimeKey}`),_(le.runtimeKey||null),window.setTimeout(()=>{_(fe=>fe===le.runtimeKey?null:fe)},1200)},children:C===le.runtimeKey?"Copied":"Copy"})]}),le.runtimeWriteOwner&&t.jsx("span",{style:{color:le.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:le.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Uh(le.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 ${Pe==="stopped"?"bg-red-500/[0.08] text-red-500":Pe==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Pe}),j&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const pe=E.sessionId;if(pe){m(Zt(pe),{state:{openRemoteForTabKey:pe}});return}m("/dashboard",{state:{openRemoteForTabKey:E.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(Lt,{size:13})}),t.jsx("button",{onClick:()=>{const pe=E.workspace||"",{options:fe,selectedKey:Qe}=hs({machine:s,currentWorkspacePath:pe});R({title:us("restart-ide",at(E.type)),description:ms("restart-ide"),confirmLabel:Ks("restart-ide"),busyLabel:Ws("restart-ide"),workspaceOptions:fe,selectedWorkspaceKey:Qe,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:at(E.type)}]},async()=>{const St=fe.find(qt=>qt.key===tt.current),ct=(St==null?void 0:St.workspacePath)??"";if(ct&&ct!==pe){await Be({type:E.type,workspacePath:ct});return}await k(E)})},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(Hs,{size:14})})]}),w&&t.jsx("button",{onClick:()=>{const pe=E.sessionId;pe&&g(pe)},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:!E.sessionId,children:t.jsx(Vt,{size:14})}),le&&Pe!=="stopped"&&t.jsxs(t.Fragment,{children:[le.mode&&t.jsx(Sa,{mode:le.mode,onChange:pe=>void Ee(le,pe,!1),compact:!0}),t.jsx("button",{onClick:()=>{const pe=E.sessionId;pe&&g(pe)},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:!E.sessionId,children:le.mode==="chat"?t.jsx(Vt,{size:14}):t.jsx(Lt,{size:13})})]}),Pe==="stopped"?t.jsx("button",{onClick:()=>{const pe=E.workspace||"",fe=j?at(E.type):Ie(E),{options:Qe,selectedKey:St}=hs({machine:s,currentWorkspacePath:pe});R({title:us("restart-stopped",fe),description:ms("restart-stopped"),confirmLabel:Ks("restart-stopped"),busyLabel:Ws("restart-stopped"),workspaceOptions:Qe,selectedWorkspaceKey:St,details:[{label:"Mode",value:I.label},{label:"Provider",value:fe}]},async()=>{const ct=Qe.find(qt=>qt.key===tt.current);await Be({type:E.type,workspaceId:(ct==null?void 0:ct.workspaceId)??null,workspacePath:(ct==null?void 0:ct.workspacePath)??"",useHome:!(ct!=null&&ct.workspaceId)&&!(ct!=null&&ct.workspacePath)})})},disabled:ne.includes(E.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:ne.includes(E.type)?"⏳":t.jsx(pa,{size:14})}):t.jsx("button",{onClick:()=>Oe(E),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(Nt,{size:14})})]})]}),X&&X.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:X.aiAgents.map(pe=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${ki(pe.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[pe.name," · ",jt(pe.status)]},pe.id))}),X&&(G[X.type]||[]).length>0&&l&&t.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[t.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:(G[X.type]||[]).map(pe=>t.jsxs("button",{disabled:Se===`${X.type}.${pe.type}`,onClick:async()=>{const fe=`${X.type}.${pe.type}`;Me(fe);try{await l(r,"set_ide_extension",{ideType:X.type,extensionType:pe.type,enabled:!pe.enabled}),re(Qe=>({...Qe,[X.type]:(Qe[X.type]||[]).map(St=>St.type===pe.type?{...St,enabled:!St.enabled}:St)}))}catch(Qe){console.error("Extension toggle failed:",Qe)}finally{Me(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 ${pe.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 ${pe.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),pe.name,t.jsx("span",{className:"text-[9px] font-normal",children:pe.enabled?"ON":"OFF"})]},pe.type))})]})]},E.id)})]}),xe&&l&&t.jsx(un,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:ke,directories:Ce,busy:Te,error:De,confirmLabel:"Use this folder",onClose:()=>B(!1),onNavigate:E=>{gt(E)},onConfirm:E=>{ce(E),ge("__custom__"),B(!1)}}),Ye&&t.jsx($a,{title:Ye.title,description:Ye.description,details:Ye.details,workspaceOptions:Ye.workspaceOptions,selectedWorkspaceKey:mt,onWorkspaceChange:E=>{tt.current=E,Ve(E)},confirmLabel:Ye.confirmLabel,busyLabel:Ye.busyLabel,busy:it,onConfirm:W,onCancel:()=>{Ge.current=null,ot(null)}}),Ne&&It&&t.jsx(Ta,{activeConv:It,ides:[],isCreatingChat:!1,isRefreshingHistory:ae,savedSessions:z,isSavedSessionsLoading:ae,isResumingSavedSessionId:V,savedHistoryFilters:he,onSavedHistoryFiltersChange:ie,onClose:()=>me(!1),onNewChat:()=>{D(""),me(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Ct(N)},onResumeSavedSession:E=>{if(!E.canResume||V)return;const X=Kt(E);D(E.providerSessionId),Ot(E),ye(E.providerSessionId),me(!1),Be({type:E.providerType,workspaceId:X.workspaceId,workspacePath:X.workspacePath,useHome:X.useHome,resumeSessionId:E.providerSessionId}).finally(()=>{ye(le=>le===E.providerSessionId?null:le)})}})]})}const Zo=[{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 Vh({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:u="ide",initialWorkspaceId:p,initialWorkspacePath:m,sendDaemonCommand:h}){var d;const[y,k]=o.useState(u);o.useEffect(()=>{k(u)},[u]);const A=o.useMemo(()=>({ide:n.length,cli:a.length,acp:i.length}),[n.length,a.length,i.length]);return t.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[t.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),t.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),t.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[t.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:Zo.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 ${y===b.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>k(b.id),children:[t.jsx("span",{children:b.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${y===b.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:A[b.id]})]},b.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(d=Zo.find(b=>b.id===y))==null?void 0:d.helper})]}),y==="ide"&&t.jsx(Hn,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:p,initialWorkspacePath:m}),y==="cli"&&t.jsx(Hn,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:p,initialWorkspacePath:m}),y==="acp"&&t.jsx(Hn,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:p,initialWorkspacePath:m})]})}function Gh({onNicknameSynced:e}={}){var V,ye,Q,ge,te,ce,ne,we,xe;const{id:s}=jl(),r=Os(),n=ia(),{sendCommand:a}=Dt(),i=ur(),c=zi(),l=c.ides||[],u=c.initialLoaded??!0,p=l.find(B=>B.id===s&&B.type==="adhdev-daemon"),m=l.some(B=>B.type==="adhdev-daemon"),[h,y]=o.useState("workspace"),[k,A]=o.useState("ide"),d=o.useRef(null),[b,v]=o.useState(null),f=o.useRef("__home__"),[C,_]=o.useState("__home__"),[g,I]=o.useState(!1),j=o.useRef(null);o.useEffect(()=>{!s||!p||!(!p.workspaces||!p.availableProviders||!p.detectedIdes||!p.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,p,s]),ap(s&&h==="overview"?[s]:[],{enabled:h==="overview",intervalMs:15e3});const w=()=>{if(m){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},x=Sh({machineId:s,registeredMachineId:(p==null?void 0:p.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:j});o.useEffect(()=>lt.onToast(ke=>{c.setToasts(Ce=>{if(Ce.some(He=>He.message===ke.message&&ke.timestamp-He.timestamp<3e3))return Ce;const Te={id:ke.id,message:ke.message,type:ke.type,timestamp:ke.timestamp,targetKey:ke.targetKey,actions:ke.actions};return[...Ce.slice(-4),Te]});const ve=ke.duration||5e3;setTimeout(()=>c.setToasts(Ce=>Ce.filter(J=>J.id!==ke.id)),ve)}),[c]);const $=(p==null?void 0:p.availableProviders)||[],N={};for(const B of $)N[B.type]=B.icon;const L=B=>N[B]||"",T=p?{id:p.id,hostname:Si(p,{fallbackId:p.id}),platform:((V=p.machine)==null?void 0:V.platform)||"unknown",arch:((ye=p.machine)==null?void 0:ye.arch)||"",cpus:((Q=p.machine)==null?void 0:Q.cpus)||0,totalMem:((ge=p.machine)==null?void 0:ge.totalMem)||0,freeMem:(te=p.machine)==null?void 0:te.freeMem,availableMem:(ce=p.machine)==null?void 0:ce.availableMem,loadavg:(ne=p.machine)==null?void 0:ne.loadavg,uptime:(we=p.machine)==null?void 0:we.uptime,release:((xe=p.machine)==null?void 0:xe.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,K=l.filter(B=>B.daemonId===s&&B.type!=="adhdev-daemon").filter(B=>!ir(B)&&!As(B)).map(B=>({id:B.id,sessionId:B.sessionId,type:B.type,version:B.version||"",instanceId:B.instanceId||"",status:B.status,workspace:B.workspace||null,terminals:B.terminals||0,aiAgents:Bd(B.aiAgents||(B.agents||[]).map(ke=>({id:ke.name,name:ke.name,status:ke.status,version:ke.version}))),activeChat:B.activeChat||null,chats:B.chats||[],childSessions:B.childSessions||[],cdpConnected:B.cdpConnected||!1,daemonId:s})),F=l.filter(B=>B.daemonId===s&&ir(B)).map(B=>({id:B.id,sessionId:B.sessionId,type:B.type,cliName:B.cliName||B.type,status:B.status,workspace:B.workspace||"",activeChat:B.activeChat||null,providerSessionId:B.providerSessionId,mode:B.mode,runtimeKey:B.runtimeKey,runtimeDisplayName:B.runtimeDisplayName,runtimeWorkspaceLabel:B.runtimeWorkspaceLabel,runtimeWriteOwner:B.runtimeWriteOwner||null,runtimeAttachedClients:B.runtimeAttachedClients||[],daemonId:s})),M=l.filter(B=>B.daemonId===s&&As(B)).map(B=>({id:B.id,sessionId:B.sessionId,type:B.type,acpName:B.cliName||B.type,status:B.status,workspace:B.workspace||"",activeChat:B.activeChat||null,providerSessionId:B.providerSessionId,daemonId:s})),P=p?Mt(p,{fallbackId:s}):"",O="workspace",S=n.state,D=S==null?void 0:S.initialMachineTab,z=S==null?void 0:S.initialWorkspaceCategory,U=S==null?void 0:S.initialWorkspaceId,ae=S==null?void 0:S.initialWorkspacePath,q=D==="ides"||D==="clis"||D==="acps"?"workspace":D||O,ue=D==="ides"?"ide":D==="clis"?"cli":D==="acps"?"acp":z,Z=[...K.map(B=>{var ke,ve,Ce,J,Te;return{id:`ide:${B.type}:${B.workspace||""}`,label:((ke=B.activeChat)==null?void 0:ke.title)||B.type,kind:"ide",providerType:B.type,subtitle:B.workspace||void 0,workspace:B.workspace||void 0,lastLaunchedAt:((Te=(J=(Ce=(ve=B.activeChat)==null?void 0:ve.messages)==null?void 0:Ce.at)==null?void 0:J.call(Ce,-1))==null?void 0:Te.timestamp)||0}}),...F.map(B=>{var ke,ve,Ce,J,Te;return{id:`cli:${B.type}:${B.workspace||""}`,label:((ke=B.activeChat)==null?void 0:ke.title)||B.cliName,kind:"cli",providerType:B.type,providerSessionId:B.providerSessionId,subtitle:B.workspace||void 0,workspace:B.workspace||void 0,lastLaunchedAt:((Te=(J=(Ce=(ve=B.activeChat)==null?void 0:ve.messages)==null?void 0:Ce.at)==null?void 0:J.call(Ce,-1))==null?void 0:Te.timestamp)||0}}),...M.map(B=>{var ke,ve,Ce,J,Te;return{id:`acp:${B.type}:${B.workspace||""}`,label:((ke=B.activeChat)==null?void 0:ke.title)||B.acpName,kind:"acp",providerType:B.type,providerSessionId:B.providerSessionId,subtitle:gs(B.summaryMetadata)||B.workspace||void 0,workspace:B.workspace||void 0,lastLaunchedAt:((Te=(J=(Ce=(ve=B.activeChat)==null?void 0:ve.messages)==null?void 0:Ce.at)==null?void 0:J.call(Ce,-1))==null?void 0:Te.timestamp)||0}})].sort((B,ke)=>(ke.lastLaunchedAt||0)-(B.lastLaunchedAt||0)),se=((p==null?void 0:p.recentLaunches)||[]).length>0?((p==null?void 0:p.recentLaunches)||[]).map(B=>({id:B.id,label:B.title||B.providerName||B.providerType,kind:B.kind,providerType:B.providerType,providerSessionId:B.providerSessionId,subtitle:gs(B.summaryMetadata)||B.workspace||void 0,workspace:B.workspace,summaryMetadata:B.summaryMetadata,lastLaunchedAt:B.lastLaunchedAt})):Z,oe=o.useMemo(()=>{var ke;const B=((ke=c.connectionStates)==null?void 0:ke[s||""])||void 0;return l.filter(ve=>ve.daemonId===s&&ve.type!=="adhdev-daemon").flatMap(ve=>Ma(ve,{},{connectionStates:s&&B?{[s]:B}:void 0,defaultConnectionState:B})).filter(ve=>!(ve.transport==="pty"&&ve.mode==="terminal")).sort((ve,Ce)=>Yn(Ce)-Yn(ve))},[l,c.connectionStates,s]),Ne=o.useCallback(B=>{const ke=wa(B);ke&&r(Zt(ke))},[r]),me=o.useCallback(()=>{d.current&&(I(!0),d.current().finally(()=>{d.current=null,I(!1),v(null)}))},[]),he=o.useCallback(B=>{if(!T)return;const{options:ke,selectedKey:ve}=hs({machine:T,currentWorkspacePath:B.workspace}),Ce=async()=>{A(B.kind),y("workspace")};d.current=async()=>{const J=ke.find(De=>De.key===f.current),Te=(J==null?void 0:J.workspacePath)??null,He=(J==null?void 0:J.workspaceId)??null;if(B.kind==="ide"&&B.providerType){await x.handleLaunchIde(B.providerType,Te?{workspace:Te}:void 0);return}if((B.kind==="cli"||B.kind==="acp")&&B.providerType){await x.runLaunchCliCore({cliType:B.providerType,dir:He?void 0:Te||"",workspaceId:He||void 0,model:B.kind==="acp"&&Ci(B.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:B.providerSessionId});return}await Ce()},f.current=ve,_(ve),v({title:B.kind==="ide"?us("restart-ide",B.label):B.providerSessionId?Ia(B.label):us("start-fresh",B.label),description:B.kind==="ide"?ms("restart-ide"):B.providerSessionId?Aa():ms("start-fresh"),confirmLabel:B.kind==="ide"?Ks("restart-ide"):B.providerSessionId?zr(!0):Ks("start-fresh"),busyLabel:B.kind==="ide"?Ws("restart-ide"):B.providerSessionId?Na(!0):Ws("start-fresh"),workspaceOptions:ke,details:[{label:"Mode",value:B.kind.toUpperCase()},...B.providerType?[{label:"Provider",value:B.providerType}]:[]]})},[x,T]);if(o.useEffect(()=>{y(q)},[O,q,s]),o.useEffect(()=>{ue&&A(ue)},[ue,s]),!T)return u?t.jsxs("div",{className:"p-10 text-center text-text-muted",children:[t.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),t.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),t.jsx("button",{onClick:w,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 ie=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Lt,{size:14})," Workspace"]}),count:K.length+F.length+M.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(zt,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Qr,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(zl,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Hl,{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:w,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:B=>x.setNicknameInput(B.target.value),onKeyDown:B=>{B.key==="Enter"&&x.handleSaveNickname(),B.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(T.machineNickname||"")},title:"Click to set nickname",children:P}),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:[T.platform," · ",T.arch]}),t.jsxs("span",{children:[T.cpus," cores"]}),(p==null?void 0:p.version)&&t.jsxs("span",{children:["v",p.version]}),T.p2p.available&&t.jsxs("span",{children:["P2P ",T.p2p.state==="connected"?"connected":T.p2p.state]}),T.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:T.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ie.map(B=>t.jsxs("button",{onClick:()=>y(B.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${h===B.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[B.label,B.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${h===B.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:B.count})]},B.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:[h==="workspace"&&t.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[t.jsx(Hh,{machineEntry:p,providers:$,recentLaunches:se,currentConversations:oe,onUpgradeDaemon:async()=>{try{await a(s,"daemon_upgrade",{})}catch{}},onOpenRecent:he,onOpenConversation:Ne}),t.jsx(Vh,{machine:T,machineId:s,providers:$,ideSessions:K,cliSessions:F,acpSessions:M,actions:x,getIcon:L,initialCategory:k,initialWorkspaceId:U,initialWorkspacePath:ae,sendDaemonCommand:a})]}),h==="providers"&&t.jsx(_h,{machineId:s,providers:$,sendDaemonCommand:a}),h==="overview"&&t.jsx(Nh,{machineId:s,machine:T,ideSessions:K,cliSessions:F,acpSessions:M,actions:x,sendDaemonCommand:a}),h==="session-host"&&t.jsx(Wh,{machineId:s,cliSessions:F,sendDaemonCommand:a}),h==="logs"&&t.jsx(Eh,{machineId:s,sendDaemonCommand:a})]})})}),x.launchPick&&T&&t.jsx(Oh,{machine:T,launchPick:x.launchPick,actions:x}),b&&t.jsx($a,{title:b.title,description:b.description,details:b.details,workspaceOptions:b.workspaceOptions,selectedWorkspaceKey:C,onWorkspaceChange:B=>{f.current=B,_(B)},confirmLabel:b.confirmLabel,busyLabel:b.busyLabel,busy:g,onConfirm:me,onCancel:()=>{d.current=null,v(null)}}),t.jsx(tc,{toasts:c.toasts||[],onDismiss:B=>c.setToasts(ke=>ke.filter(ve=>ve.id!==B)),onClickToast:B=>{B.targetKey&&r(Zt(B.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 L=await r(e,"session_host_prune_duplicate_sessions",{}),T=Bn(L);if(!(T!=null&&T.success))throw new Error((T==null?void 0:T.error)||"Duplicate prune failed");const K=T.result||{},F=Array.isArray(K.prunedSessionIds)?K.prunedSessionIds.length:0,M=typeof K.duplicateGroupCount=="number"?K.duplicateGroupCount:0;lt.showToast(`Pruned ${F} duplicate runtime(s) across ${M} group(s)`,"success"),await d()}catch(L){const T=L instanceof Error?L.message:"Duplicate prune failed";lt.showToast(T,"warning"),a(T)}finally{c(L=>L==="session_host_prune_duplicate_sessions"?null:L)}}},[e,d,r]),f=o.useMemo(()=>[...(m==null?void 0:m.sessions)||[]].sort((N,L)=>(L.lastActivityAt||0)-(N.lastActivityAt||0)),[m==null?void 0:m.sessions]),C=o.useMemo(()=>m!=null&&m.liveRuntimes||m!=null&&m.recoverySnapshots||m!=null&&m.inactiveRecords?{liveRuntimes:(m==null?void 0:m.liveRuntimes)||[],recoverySnapshots:(m==null?void 0:m.recoverySnapshots)||[],inactiveRecords:(m==null?void 0:m.inactiveRecords)||[]}:Uc(f),[m==null?void 0:m.inactiveRecords,m==null?void 0:m.liveRuntimes,m==null?void 0:m.recoverySnapshots,f]),_=C.liveRuntimes,g=C.recoverySnapshots,I=C.inactiveRecords,j=o.useMemo(()=>Kh(_),[_]),w=o.useMemo(()=>[...(m==null?void 0:m.recentTransitions)||[]].slice(-6).reverse(),[m==null?void 0:m.recentTransitions]),x=o.useMemo(()=>[...(m==null?void 0:m.recentLogs)||[]].reverse().find(N=>N.level==="warn"||N.level==="error")||null,[m==null?void 0:m.recentLogs]),$=(N,L)=>{var z;const T=i===`session_host_resume_session:${N.sessionId}`,K=i===`session_host_restart_session:${N.sessionId}`,F=i===`session_host_stop_session:${N.sessionId}`,M=Ka(N.meta),P=A.get(N.sessionId),O=N.attachedClients.length===1?"1 client":`${N.attachedClients.length} clients`,S=L==="recovery"?"Recover":"Resume",D=Fc(L);return t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:N.displayName||(P==null?void 0:P.cliName)||N.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Bh(N.lifecycle)}`,children:N.lifecycle}),M&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:M})]}),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:N.workspaceLabel||(P==null?void 0:P.runtimeWorkspaceLabel)||N.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:N.runtimeKey}),N.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",N.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((z=N.writeOwner)==null?void 0:z.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:$h(N.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(la,{size:11})," ",O]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",Jo(N.lastActivityAt)]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-sky-200",children:["Next: ",D]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[L==="recovery"&&(N.lifecycle==="interrupted"||N.lifecycle==="failed"||N.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{b("session_host_resume_session",N)},children:T?`${S}ing…`:S}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{b("session_host_restart_session",N)},children:K?"Restarting…":"Restart"}),L==="live"&&(N.lifecycle==="running"||N.lifecycle==="starting"||N.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",N)},children:F?"Stopping…":"Stop"})]})]})},N.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(zt,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:hm()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[j>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{v()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${j})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${k.toneClass}`,children:k.label}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{d()},disabled:h||l,children:[t.jsx(Hs,{size:13}),h||l?"Refreshing…":"Refresh"]})]})]}),n&&!m&&t.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(bs,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),t.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),m&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:m.runtimeCount})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:g.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:m.recentRequests.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),t.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:Jo(m.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Kn(m.hostStartedAt)})]})]}),x&&t.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[t.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[t.jsx(bs,{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:[Kn(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(Jr,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ls("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(N=>$(N,"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(zt,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ls("recovery")}),g.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:g.map(N=>$(N,"recovery"))})]}),I.length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ls("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:I.map(N=>$(N,"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"}),w.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:w.map(N=>{var T;const L=f.find(K=>K.sessionId===N.sessionId);return t.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-text-primary font-medium",children:(L==null?void 0:L.displayName)||((T=A.get(N.sessionId))==null?void 0:T.cliName)||N.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[N.action,N.lifecycle?` · ${N.lifecycle}`:"",N.detail?` · ${N.detail}`:"",N.error?` · ${N.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${N.success===!1?"text-red-300":"text-text-secondary"}`,children:Kn(N.timestamp)})]},`${N.sessionId}:${N.timestamp}:${N.action}`)})})]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",t.jsx("span",{className:"font-mono text-text-primary",children:m.endpoint||"unknown"}),n?t.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function Oh({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 Wn({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 On({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 Hh({machineEntry:e,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),u=r.slice(0,4),m=sr(e,"0.8.79");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(Wn,{icon:t.jsx(Vt,{size:13}),children:"Current Chats"}),t.jsx(On,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(h=>{const y=Yn(h);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(h),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:dt(h)}),y>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:tn(y)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ys(h)})]},h.tabKey)})})})]}),u.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Wn,{icon:t.jsx(pi,{size:13}),children:"Recent Launches"}),t.jsx(On,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(h=>{const{metaText:y,updatedLabel:k}=Ac(h);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(h),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:h.label}),k&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:k})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:y})]},h.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Wn,{icon:t.jsx(bs,{size:13}),children:"Daemon Update"}),t.jsx(On,{className:"border-amber-500/20 bg-amber-500/5",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:m?"Daemon update required":"Version mismatch detected"}),t.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:m?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),t.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:a,children:[t.jsx(Hs,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Uh(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const Fh={ide:{label:"IDE",plural:"IDEs",accent:"border-blue-500/[0.12]"},cli:{label:"CLI",plural:"CLIs",accent:"border-violet-500/[0.12]"},acp:{label:"ACP Agent",plural:"ACP agents",accent:"border-emerald-500/[0.12]"}};function Mr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function zh(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 Hn({category:e,machine:s,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:p}){const m=Os(),{handleLaunchIde:h,handleStopCli:y,handleRestartIde:k,handleStopIde:A,handleDetectIdes:d,launchingIde:b,launchingAgentType:v,addLog:f}=c,[C,_]=o.useState(null),g=o.useCallback(E=>{E&&m(Zt(E))},[m]),I=Fh[e],j=e==="ide",w=e==="acp",x=o.useMemo(()=>n.filter(E=>E.category===e&&(e==="ide"||E.installed!==!1)),[e,n]),$=o.useMemo(()=>new Map(x.map(E=>[E.type,E.displayName||E.type])),[x]),[N,L]=o.useState(""),[T,K]=o.useState(""),[F,M]=o.useState([]),[P,O]=o.useState(""),[S,D]=o.useState(""),[z,U]=o.useState([]),[ae,q]=o.useState(!1),[ue,Z]=o.useState(!1),[se,oe]=o.useState(""),[Ne,me]=o.useState(!1),[he,ie]=o.useState(()=>yt()),[V,ye]=o.useState(null),[Q,ge]=o.useState(p?"__custom__":u||s.defaultWorkspaceId||""),[te,ce]=o.useState(p||""),[ne,we]=o.useState([]),[xe,B]=o.useState(!1),[ke,ve]=o.useState(""),[Ce,J]=o.useState([]),[Te,He]=o.useState(!1),[De,Ze]=o.useState(""),Ge=o.useRef(null),[Ye,ot]=o.useState(null),tt=o.useRef("__home__"),[mt,Ve]=o.useState("__home__"),[it,ht]=o.useState(!1),pt=o.useRef(0),je=ne.filter(E=>!a.some(X=>X.type===E&&jt(X.status)!=="stopped")),Ue=o.useRef({});o.useEffect(()=>{s.defaultWorkspaceId&&!Q&&ge(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),o.useEffect(()=>{if(p){ge("__custom__"),ce(p);return}u&&(ge(u),ce(""))},[u,p]),o.useEffect(()=>{j||N&&(x.some(E=>E.type===N)||(L(""),D("")))},[x,j,N]);const ze=(()=>{if(Q==="__custom__")return te.trim();if(!Q)return"";const E=(s.workspaces||[]).find(X=>X.id===Q);return(E==null?void 0:E.path)||""})(),Xe=o.useCallback(E=>{const X=Ue.current[E];X&&(clearTimeout(X),delete Ue.current[E]),we(le=>le.includes(E)?le.filter(Pe=>Pe!==E):le)},[]),ft=o.useRef(new Set),gt=o.useCallback(async E=>{if(l){He(!0),Ze("");try{const X=await dn(l,r,E);ve(X.path),ce(X.path),J(X.directories)}catch(X){Ze(X instanceof Error?X.message:"Could not load folder")}finally{He(!1)}}},[r,l]),vt=o.useCallback(()=>{if(!l)return;ge("__custom__"),B(!0);const E=a.map(le=>le.workspace),X=ln(s.platform,cn(te.trim(),ze,p,E,s.defaultWorkspacePath,(s.workspaces||[]).map(le=>le.path)));gt(X)},[te,p,gt,s.defaultWorkspacePath,s.platform,s.workspaces,a,ze,l]),Ot=o.useCallback(E=>{const X=String(E.workspace||"").trim();if(!X)return;const le=(s.workspaces||[]).find(Pe=>Mr(Pe.path)===Mr(X));if(le){ge(le.id),ce("");return}ge("__custom__"),ce(X)},[s.workspaces]),Kt=o.useCallback(E=>{const X=String(E.workspace||"").trim();if(!X)return{workspaceId:null,workspacePath:"",useHome:!0};const le=(s.workspaces||[]).find(Pe=>Mr(Pe.path)===Mr(X));return le?{workspaceId:le.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:X,useHome:!1}},[s.workspaces]),Ct=o.useCallback(async E=>{if(!l||!E||e!=="cli"){U([]),q(!1),Z(!1),oe("");return}const X=pt.current+1;pt.current=X,q(!0),oe("");try{const le=await l(r,"list_saved_sessions",{providerType:E,kind:"cli",limit:30});if(pt.current!==X)return;const Pe=(le==null?void 0:le.result)??le;U(Array.isArray(Pe==null?void 0:Pe.sessions)?Pe.sessions:[])}catch(le){if(pt.current!==X)return;U([]),oe(le instanceof Error?le.message:"Could not load saved sessions")}finally{pt.current===X&&(q(!1),Z(!0))}},[e,r,l]),It=o.useMemo(()=>{if(e!=="cli"||!N)return null;const E=$.get(N)||N;return{routeId:r,daemonId:r,providerSessionId:S||void 0,transport:"pty",mode:"chat",agentName:E,agentType:N,status:"idle",title:E,messages:[],ideType:N,workspaceName:ze,displayPrimary:E,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${N}`}},[e,r,$,ze,S,N]),Y=o.useCallback(E=>{if(e==="ide"||!E){M([]);return}M(Oc(r,E))},[e,r]);o.useEffect(()=>{pt.current+=1,D(""),Y(N),Z(!1),U([]),oe(""),q(!1)},[e,Y,Ct,N]);const $e=o.useMemo(()=>z.find(E=>E.providerSessionId===S)||null,[z,S]);o.useEffect(()=>{if(!S)return;const E=z.find(X=>X.providerSessionId===S);E!=null&&E.canResume||D("")},[z,S]);const R=o.useCallback((E,X)=>{Ge.current=X,tt.current=E.selectedWorkspaceKey||"__home__",Ve(E.selectedWorkspaceKey||"__home__"),ot(E)},[]),W=o.useCallback(()=>{Ge.current&&(ht(!0),Ge.current().finally(()=>{Ge.current=null,ht(!1),ot(null)}))},[]),H=o.useCallback(E=>{if(!E)return;we(le=>le.includes(E)?le:[...le,E]);const X=Ue.current[E];X&&clearTimeout(X),Ue.current[E]=setTimeout(()=>{we(le=>le.includes(E)?le.filter(Pe=>Pe!==E):le),delete Ue.current[E]},2e4)},[]);o.useEffect(()=>{for(const X of a)jt(X.status)!=="stopped"&&(ne.includes(X.type)&&!ft.current.has(X.type)&&(ft.current.add(X.type),f("info",`${$.get(X.type)||X.type} launched`,!0)),Xe(X.type));const E=new Set(a.filter(X=>jt(X.status)!=="stopped").map(X=>X.type));ft.current.forEach(X=>{!ne.includes(X)&&!E.has(X)&&ft.current.delete(X)})},[f,Xe,a,ne,$]),o.useEffect(()=>()=>{Object.values(Ue.current).forEach(clearTimeout),Ue.current={}},[]);const[G,re]=o.useState({}),[Se,Me]=o.useState(null);o.useEffect(()=>{if(!j||!r||!l)return;(async()=>{try{const X=await l(r,"get_ide_extensions",{}),le=(X==null?void 0:X.result)||X;le!=null&&le.success&&(le!=null&&le.ideExtensions)&&re(le.ideExtensions)}catch{}})()},[j,r,l]);const Ie=E=>j?at(E.type):e==="cli"?E.cliName:E.acpName,We=j?s.detectedIdes||[]:[],Be=o.useCallback(async E=>{const X=(E==null?void 0:E.type)||N,le=(E==null?void 0:E.workspacePath)??ze;if(j){await h(X,le?{workspace:le}:void 0)&&H(X);return}const Pe=await c.runLaunchCliCore({cliType:X,dir:E!=null&&E.workspaceId?void 0:le||void 0,workspaceId:(E==null?void 0:E.workspaceId)||void 0,useHome:(E==null?void 0:E.useHome)||!(E!=null&&E.workspaceId)&&!le,argsStr:(E==null?void 0:E.argsStr)??(T||void 0),model:(E==null?void 0:E.model)??(w&&P||void 0),resumeSessionId:(E==null?void 0:E.resumeSessionId)||!w&&e==="cli"&&X===N&&S||void 0});if(Pe.success||Pe.pending){const pe=(E==null?void 0:E.argsStr)??T;!j&&(pe!=null&&pe.trim())&&(Hc(r,X,pe),Y(X)),H(X),Pe.success&&Pe.sessionId&&g(Pe.sessionId)}},[c,h,w,j,T,P,Y,H,r,g,ze,S,N]),Ae=Zi(j?"ide":w?"acp":"cli",!j&&!w&&!!S),ee=ec(j?"ide":w?"acp":"cli",!j&&!w&&!!S),Re=()=>{var pe;const E=j?at(N):$.get(N)||N,X=!j&&!w&&!!S,{options:le,selectedKey:Pe}=hs({machine:s,currentWorkspaceId:Q&&Q!=="__custom__"?Q:null,currentWorkspacePath:ze});R({title:X?Ia(E):us("start-fresh",E),description:X?Aa():ms("start-fresh"),confirmLabel:Ae,busyLabel:ee,workspaceOptions:le,selectedWorkspaceKey:Pe,details:[{label:"Mode",value:I.label},{label:"Provider",value:E},...!j&&e==="cli"&&S?[{label:"Resume",value:((pe=z.find(fe=>fe.providerSessionId===S))==null?void 0:pe.title)||S}]:[],...!j&&T.trim()?[{label:"Arguments",value:T.trim()}]:[],...w&&P.trim()?[{label:"Model",value:P.trim()}]:[]]},async()=>{const fe=le.find(Qe=>Qe.key===tt.current);fe!=null&&fe.workspaceId?(ge(fe.workspaceId),ce("")):fe!=null&&fe.workspacePath?(ge("__custom__"),ce(fe.workspacePath)):(ge(""),ce("")),await Be({workspaceId:(fe==null?void 0:fe.workspaceId)??null,workspacePath:(fe==null?void 0:fe.workspacePath)??"",useHome:!(fe!=null&&fe.workspaceId)&&!(fe!=null&&fe.workspacePath)})})},Oe=E=>{j?A(E):y(E.type,E.workspace,E.id)},Ee=o.useCallback(async(E,X,le=!1)=>{if(E.mode===X){le&&E.sessionId&&g(E.sessionId);return}if(!l||!E.sessionId){le&&E.sessionId&&g(E.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:E.sessionId,cliType:E.type,mode:X}),le&&g(E.sessionId)}catch(Pe){zh(Pe)?console.warn("Skipped CLI view mode switch:",Pe instanceof Error?Pe.message:String(Pe)):console.error("Failed to switch CLI view mode:",Pe)}},[r,g,l]),xt=t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:Q,onChange:E=>{const X=E.target.value;if(ge(X),X==="__custom__"&&l){vt();return}X!=="__custom__"&&ce("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(s.workspaces||[]).length>0?t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(s.workspaces||[]).map(E=>t.jsxs("option",{value:E.id,children:[E.id===s.defaultWorkspaceId?"⭐ ":"",rn(E.path,E.label)]},E.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…"})]})}),Q==="__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:vt,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:te,onChange:E=>ce(E.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:Q==="__custom__"?ze?t.jsx("span",{className:"font-mono truncate block",title:ze,children:ze}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":ze?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:Q===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:ze,children:ze})]}):"No workspace selected. This launches in the home directory."})]});return t.jsxs("div",{children:[t.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${I.accent} relative overflow-hidden`,children:[t.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[t.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",I.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:j?We.length>0?We.map(E=>{const X=a.find(Qe=>(Qe.type||"").toLowerCase()===(E.type||"").toLowerCase()&&jt(Qe.status)!=="stopped"),le=E.running||!!X,Pe=!!X&&X.cdpConnected,pe=ne.includes(E.type||E.id||""),fe=N===(E.type||"");return t.jsxs("button",{onClick:()=>{if(Pe&&X){const Qe=X.sessionId;Qe?m(Zt(Qe),{state:{openRemoteForTabKey:Qe}}):m("/dashboard",{state:{openRemoteForTabKey:X.id}});return}pe||L(Qe=>Qe===(E.type||"")?"":E.type||"")},disabled:!!b||pe,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Pe?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":fe?"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!==E.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(E.type)}),le&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Pe?"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:E.name||at(E.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Pe?"text-green-400":pe?"text-orange-400":fe?"text-accent-primary":"text-text-muted"}`,children:Pe?"Open Session":pe?"Starting...":fe?"Configure":"Select"})]})]},E.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(Fl,{size:14})," Scan System"]})]}):x.length>0?x.map(E=>{const X=N===E.type,le=ne.includes(E.type),pe=!!a.find(fe=>fe.type===E.type&&jt(fe.status)!=="stopped");return t.jsxs("button",{onClick:()=>L(fe=>fe===E.type?"":E.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${X?"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:E.icon}),pe&&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:E.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${le?"text-orange-400":X?"text-accent-primary":"text-text-muted"}`,children:le?"Starting...":X?"Configure":"Select"})]})]},E.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."})]})}),N&&(j?We.find(E=>E.type===N):x.find(E=>E.type===N))&&t.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[t.jsx("span",{children:"Launch Settings"}),t.jsx("span",{className:"text-accent-primary font-bold",children:j?at(N):$.get(N)||N})]}),xt,!j&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!w&&e==="cli"&&t.jsx(Vc,{busy:!!v||!!b||ne.includes(N),savedSessionsLoading:ae,savedSessionsError:se,selectedSession:$e,onRefresh:()=>void Ct(N),onOpenHistory:()=>{N&&(me(!0),zc({hasLoadedInitialResults:ue,isLoading:ae})&&Ct(N))},onClearSelection:()=>D("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[w&&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:P,onChange:E=>O(E.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:T,onChange:E=>K(E.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"}),F.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:F.map(E=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>K(E),title:E,children:E},E))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:Re,disabled:!!v||!!b||ne.includes(N),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:v===N||b===N?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+ne.filter(E=>!a.some(X=>X.type===E&&jt(X.status)!=="stopped")).length,")"]}),a.length===0&&je.length===0?t.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",I.plural," running"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[je.map(E=>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(E)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:j?at(E):$.get(E)||E}),t.jsx("div",{className:"text-[11px] text-text-muted",children:v===E?"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:${E}`)),a.map(E=>{const X=j?E:null,le=!j&&!w?E:null,Pe=jt(E.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(E.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Ie(E),(X==null?void 0:X.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",X.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[t.jsx("span",{children:E.workspace||"—"}),(le==null?void 0:le.mode)&&t.jsx("span",{className:le.mode==="chat"?"text-violet-400":"text-text-secondary",children:le.mode==="chat"?"Chat view":"Terminal view"})]}),le&&(le.runtimeKey||le.runtimeWriteOwner)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[le.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 ",le.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 pe;(pe=navigator.clipboard)==null||pe.writeText(`adhdev attach ${le.runtimeKey}`),_(le.runtimeKey||null),window.setTimeout(()=>{_(fe=>fe===le.runtimeKey?null:fe)},1200)},children:C===le.runtimeKey?"Copied":"Copy"})]}),le.runtimeWriteOwner&&t.jsx("span",{style:{color:le.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:le.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Uh(le.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 ${Pe==="stopped"?"bg-red-500/[0.08] text-red-500":Pe==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Pe}),j&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const pe=E.sessionId;if(pe){m(Zt(pe),{state:{openRemoteForTabKey:pe}});return}m("/dashboard",{state:{openRemoteForTabKey:E.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(Lt,{size:13})}),t.jsx("button",{onClick:()=>{const pe=E.workspace||"",{options:fe,selectedKey:Qe}=hs({machine:s,currentWorkspacePath:pe});R({title:us("restart-ide",at(E.type)),description:ms("restart-ide"),confirmLabel:Ks("restart-ide"),busyLabel:Ws("restart-ide"),workspaceOptions:fe,selectedWorkspaceKey:Qe,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:at(E.type)}]},async()=>{const St=fe.find(qt=>qt.key===tt.current),ct=(St==null?void 0:St.workspacePath)??"";if(ct&&ct!==pe){await Be({type:E.type,workspacePath:ct});return}await k(E)})},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(Hs,{size:14})})]}),w&&t.jsx("button",{onClick:()=>{const pe=E.sessionId;pe&&g(pe)},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:!E.sessionId,children:t.jsx(Vt,{size:14})}),le&&Pe!=="stopped"&&t.jsxs(t.Fragment,{children:[le.mode&&t.jsx(Sa,{mode:le.mode,onChange:pe=>void Ee(le,pe,!1),compact:!0}),t.jsx("button",{onClick:()=>{const pe=E.sessionId;pe&&g(pe)},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:!E.sessionId,children:le.mode==="chat"?t.jsx(Vt,{size:14}):t.jsx(Lt,{size:13})})]}),Pe==="stopped"?t.jsx("button",{onClick:()=>{const pe=E.workspace||"",fe=j?at(E.type):Ie(E),{options:Qe,selectedKey:St}=hs({machine:s,currentWorkspacePath:pe});R({title:us("restart-stopped",fe),description:ms("restart-stopped"),confirmLabel:Ks("restart-stopped"),busyLabel:Ws("restart-stopped"),workspaceOptions:Qe,selectedWorkspaceKey:St,details:[{label:"Mode",value:I.label},{label:"Provider",value:fe}]},async()=>{const ct=Qe.find(qt=>qt.key===tt.current);await Be({type:E.type,workspaceId:(ct==null?void 0:ct.workspaceId)??null,workspacePath:(ct==null?void 0:ct.workspacePath)??"",useHome:!(ct!=null&&ct.workspaceId)&&!(ct!=null&&ct.workspacePath)})})},disabled:ne.includes(E.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:ne.includes(E.type)?"⏳":t.jsx(pa,{size:14})}):t.jsx("button",{onClick:()=>Oe(E),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(Nt,{size:14})})]})]}),X&&X.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:X.aiAgents.map(pe=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${ki(pe.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[pe.name," · ",jt(pe.status)]},pe.id))}),X&&(G[X.type]||[]).length>0&&l&&t.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[t.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:(G[X.type]||[]).map(pe=>t.jsxs("button",{disabled:Se===`${X.type}.${pe.type}`,onClick:async()=>{const fe=`${X.type}.${pe.type}`;Me(fe);try{await l(r,"set_ide_extension",{ideType:X.type,extensionType:pe.type,enabled:!pe.enabled}),re(Qe=>({...Qe,[X.type]:(Qe[X.type]||[]).map(St=>St.type===pe.type?{...St,enabled:!St.enabled}:St)}))}catch(Qe){console.error("Extension toggle failed:",Qe)}finally{Me(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 ${pe.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 ${pe.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),pe.name,t.jsx("span",{className:"text-[9px] font-normal",children:pe.enabled?"ON":"OFF"})]},pe.type))})]})]},E.id)})]}),xe&&l&&t.jsx(un,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:ke,directories:Ce,busy:Te,error:De,confirmLabel:"Use this folder",onClose:()=>B(!1),onNavigate:E=>{gt(E)},onConfirm:E=>{ce(E),ge("__custom__"),B(!1)}}),Ye&&t.jsx($a,{title:Ye.title,description:Ye.description,details:Ye.details,workspaceOptions:Ye.workspaceOptions,selectedWorkspaceKey:mt,onWorkspaceChange:E=>{tt.current=E,Ve(E)},confirmLabel:Ye.confirmLabel,busyLabel:Ye.busyLabel,busy:it,onConfirm:W,onCancel:()=>{Ge.current=null,ot(null)}}),Ne&&It&&t.jsx(Ta,{activeConv:It,ides:[],isCreatingChat:!1,isRefreshingHistory:ae,savedSessions:z,isSavedSessionsLoading:ae,isResumingSavedSessionId:V,savedHistoryFilters:he,onSavedHistoryFiltersChange:ie,onClose:()=>me(!1),onNewChat:()=>{D(""),me(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Ct(N)},onResumeSavedSession:E=>{if(!E.canResume||V)return;const X=Kt(E);D(E.providerSessionId),Ot(E),ye(E.providerSessionId),me(!1),Be({type:E.providerType,workspaceId:X.workspaceId,workspacePath:X.workspacePath,useHome:X.useHome,resumeSessionId:E.providerSessionId}).finally(()=>{ye(le=>le===E.providerSessionId?null:le)})}})]})}const Zo=[{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 Vh({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:u="ide",initialWorkspaceId:p,initialWorkspacePath:m,sendDaemonCommand:h}){var d;const[y,k]=o.useState(u);o.useEffect(()=>{k(u)},[u]);const A=o.useMemo(()=>({ide:n.length,cli:a.length,acp:i.length}),[n.length,a.length,i.length]);return t.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[t.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),t.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),t.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[t.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:Zo.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 ${y===b.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>k(b.id),children:[t.jsx("span",{children:b.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${y===b.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:A[b.id]})]},b.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(d=Zo.find(b=>b.id===y))==null?void 0:d.helper})]}),y==="ide"&&t.jsx(Hn,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:p,initialWorkspacePath:m}),y==="cli"&&t.jsx(Hn,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:p,initialWorkspacePath:m}),y==="acp"&&t.jsx(Hn,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:p,initialWorkspacePath:m})]})}function Gh({onNicknameSynced:e}={}){var V,ye,Q,ge,te,ce,ne,we,xe;const{id:s}=jl(),r=Os(),n=ia(),{sendCommand:a}=Dt(),i=ur(),c=zi(),l=c.ides||[],u=c.initialLoaded??!0,p=l.find(B=>B.id===s&&B.type==="adhdev-daemon"),m=l.some(B=>B.type==="adhdev-daemon"),[h,y]=o.useState("workspace"),[k,A]=o.useState("ide"),d=o.useRef(null),[b,v]=o.useState(null),f=o.useRef("__home__"),[C,_]=o.useState("__home__"),[g,I]=o.useState(!1),j=o.useRef(null);o.useEffect(()=>{!s||!p||!(!p.workspaces||!p.availableProviders||!p.detectedIdes||!p.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,p,s]),ap(s&&h==="overview"?[s]:[],{enabled:h==="overview",intervalMs:15e3});const w=()=>{if(m){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},x=Sh({machineId:s,registeredMachineId:(p==null?void 0:p.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:j});o.useEffect(()=>lt.onToast(ke=>{c.setToasts(Ce=>{if(Ce.some(He=>He.message===ke.message&&ke.timestamp-He.timestamp<3e3))return Ce;const Te={id:ke.id,message:ke.message,type:ke.type,timestamp:ke.timestamp,targetKey:ke.targetKey,actions:ke.actions};return[...Ce.slice(-4),Te]});const ve=ke.duration||5e3;setTimeout(()=>c.setToasts(Ce=>Ce.filter(J=>J.id!==ke.id)),ve)}),[c]);const $=(p==null?void 0:p.availableProviders)||[],N={};for(const B of $)N[B.type]=B.icon;const L=B=>N[B]||"",T=p?{id:p.id,hostname:Si(p,{fallbackId:p.id}),platform:((V=p.machine)==null?void 0:V.platform)||"unknown",arch:((ye=p.machine)==null?void 0:ye.arch)||"",cpus:((Q=p.machine)==null?void 0:Q.cpus)||0,totalMem:((ge=p.machine)==null?void 0:ge.totalMem)||0,freeMem:(te=p.machine)==null?void 0:te.freeMem,availableMem:(ce=p.machine)==null?void 0:ce.availableMem,loadavg:(ne=p.machine)==null?void 0:ne.loadavg,uptime:(we=p.machine)==null?void 0:we.uptime,release:((xe=p.machine)==null?void 0:xe.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,K=l.filter(B=>B.daemonId===s&&B.type!=="adhdev-daemon").filter(B=>!ir(B)&&!As(B)).map(B=>({id:B.id,sessionId:B.sessionId,type:B.type,version:B.version||"",instanceId:B.instanceId||"",status:B.status,workspace:B.workspace||null,terminals:B.terminals||0,aiAgents:Bd(B.aiAgents||(B.agents||[]).map(ke=>({id:ke.name,name:ke.name,status:ke.status,version:ke.version}))),activeChat:B.activeChat||null,chats:B.chats||[],childSessions:B.childSessions||[],cdpConnected:B.cdpConnected||!1,daemonId:s})),F=l.filter(B=>B.daemonId===s&&ir(B)).map(B=>({id:B.id,sessionId:B.sessionId,type:B.type,cliName:B.cliName||B.type,status:B.status,workspace:B.workspace||"",activeChat:B.activeChat||null,providerSessionId:B.providerSessionId,mode:B.mode,runtimeKey:B.runtimeKey,runtimeDisplayName:B.runtimeDisplayName,runtimeWorkspaceLabel:B.runtimeWorkspaceLabel,runtimeWriteOwner:B.runtimeWriteOwner||null,runtimeAttachedClients:B.runtimeAttachedClients||[],daemonId:s})),M=l.filter(B=>B.daemonId===s&&As(B)).map(B=>({id:B.id,sessionId:B.sessionId,type:B.type,acpName:B.cliName||B.type,status:B.status,workspace:B.workspace||"",activeChat:B.activeChat||null,providerSessionId:B.providerSessionId,daemonId:s})),P=p?Mt(p,{fallbackId:s}):"",O="workspace",S=n.state,D=S==null?void 0:S.initialMachineTab,z=S==null?void 0:S.initialWorkspaceCategory,U=S==null?void 0:S.initialWorkspaceId,ae=S==null?void 0:S.initialWorkspacePath,q=D==="ides"||D==="clis"||D==="acps"?"workspace":D||O,ue=D==="ides"?"ide":D==="clis"?"cli":D==="acps"?"acp":z,Z=[...K.map(B=>{var ke,ve,Ce,J,Te;return{id:`ide:${B.type}:${B.workspace||""}`,label:((ke=B.activeChat)==null?void 0:ke.title)||B.type,kind:"ide",providerType:B.type,subtitle:B.workspace||void 0,workspace:B.workspace||void 0,lastLaunchedAt:((Te=(J=(Ce=(ve=B.activeChat)==null?void 0:ve.messages)==null?void 0:Ce.at)==null?void 0:J.call(Ce,-1))==null?void 0:Te.timestamp)||0}}),...F.map(B=>{var ke,ve,Ce,J,Te;return{id:`cli:${B.type}:${B.workspace||""}`,label:((ke=B.activeChat)==null?void 0:ke.title)||B.cliName,kind:"cli",providerType:B.type,providerSessionId:B.providerSessionId,subtitle:B.workspace||void 0,workspace:B.workspace||void 0,lastLaunchedAt:((Te=(J=(Ce=(ve=B.activeChat)==null?void 0:ve.messages)==null?void 0:Ce.at)==null?void 0:J.call(Ce,-1))==null?void 0:Te.timestamp)||0}}),...M.map(B=>{var ke,ve,Ce,J,Te;return{id:`acp:${B.type}:${B.workspace||""}`,label:((ke=B.activeChat)==null?void 0:ke.title)||B.acpName,kind:"acp",providerType:B.type,providerSessionId:B.providerSessionId,subtitle:gs(B.summaryMetadata)||B.workspace||void 0,workspace:B.workspace||void 0,lastLaunchedAt:((Te=(J=(Ce=(ve=B.activeChat)==null?void 0:ve.messages)==null?void 0:Ce.at)==null?void 0:J.call(Ce,-1))==null?void 0:Te.timestamp)||0}})].sort((B,ke)=>(ke.lastLaunchedAt||0)-(B.lastLaunchedAt||0)),se=((p==null?void 0:p.recentLaunches)||[]).length>0?((p==null?void 0:p.recentLaunches)||[]).map(B=>({id:B.id,label:B.title||B.providerName||B.providerType,kind:B.kind,providerType:B.providerType,providerSessionId:B.providerSessionId,subtitle:gs(B.summaryMetadata)||B.workspace||void 0,workspace:B.workspace,summaryMetadata:B.summaryMetadata,lastLaunchedAt:B.lastLaunchedAt})):Z,oe=o.useMemo(()=>{var ke;const B=((ke=c.connectionStates)==null?void 0:ke[s||""])||void 0;return l.filter(ve=>ve.daemonId===s&&ve.type!=="adhdev-daemon").flatMap(ve=>Ma(ve,{},{connectionStates:s&&B?{[s]:B}:void 0,defaultConnectionState:B})).filter(ve=>!(ve.transport==="pty"&&ve.mode==="terminal")).sort((ve,Ce)=>Yn(Ce)-Yn(ve))},[l,c.connectionStates,s]),Ne=o.useCallback(B=>{const ke=wa(B);ke&&r(Zt(ke))},[r]),me=o.useCallback(()=>{d.current&&(I(!0),d.current().finally(()=>{d.current=null,I(!1),v(null)}))},[]),he=o.useCallback(B=>{if(!T)return;const{options:ke,selectedKey:ve}=hs({machine:T,currentWorkspacePath:B.workspace}),Ce=async()=>{A(B.kind),y("workspace")};d.current=async()=>{const J=ke.find(De=>De.key===f.current),Te=(J==null?void 0:J.workspacePath)??null,He=(J==null?void 0:J.workspaceId)??null;if(B.kind==="ide"&&B.providerType){await x.handleLaunchIde(B.providerType,Te?{workspace:Te}:void 0);return}if((B.kind==="cli"||B.kind==="acp")&&B.providerType){await x.runLaunchCliCore({cliType:B.providerType,dir:He?void 0:Te||"",workspaceId:He||void 0,model:B.kind==="acp"&&Ci(B.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:B.providerSessionId});return}await Ce()},f.current=ve,_(ve),v({title:B.kind==="ide"?us("restart-ide",B.label):B.providerSessionId?Ia(B.label):us("start-fresh",B.label),description:B.kind==="ide"?ms("restart-ide"):B.providerSessionId?Aa():ms("start-fresh"),confirmLabel:B.kind==="ide"?Ks("restart-ide"):B.providerSessionId?zr(!0):Ks("start-fresh"),busyLabel:B.kind==="ide"?Ws("restart-ide"):B.providerSessionId?Na(!0):Ws("start-fresh"),workspaceOptions:ke,details:[{label:"Mode",value:B.kind.toUpperCase()},...B.providerType?[{label:"Provider",value:B.providerType}]:[]]})},[x,T]);if(o.useEffect(()=>{y(q)},[O,q,s]),o.useEffect(()=>{ue&&A(ue)},[ue,s]),!T)return u?t.jsxs("div",{className:"p-10 text-center text-text-muted",children:[t.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),t.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),t.jsx("button",{onClick:w,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 ie=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Lt,{size:14})," Workspace"]}),count:K.length+F.length+M.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(zt,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Qr,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(zl,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Hl,{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:w,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:B=>x.setNicknameInput(B.target.value),onKeyDown:B=>{B.key==="Enter"&&x.handleSaveNickname(),B.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(T.machineNickname||"")},title:"Click to set nickname",children:P}),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:[T.platform," · ",T.arch]}),t.jsxs("span",{children:[T.cpus," cores"]}),(p==null?void 0:p.version)&&t.jsxs("span",{children:["v",p.version]}),T.p2p.available&&t.jsxs("span",{children:["P2P ",T.p2p.state==="connected"?"connected":T.p2p.state]}),T.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:T.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ie.map(B=>t.jsxs("button",{onClick:()=>y(B.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${h===B.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[B.label,B.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${h===B.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:B.count})]},B.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:[h==="workspace"&&t.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[t.jsx(Hh,{machineEntry:p,providers:$,recentLaunches:se,currentConversations:oe,onUpgradeDaemon:async()=>{try{await a(s,"daemon_upgrade",{})}catch{}},onOpenRecent:he,onOpenConversation:Ne}),t.jsx(Vh,{machine:T,machineId:s,providers:$,ideSessions:K,cliSessions:F,acpSessions:M,actions:x,getIcon:L,initialCategory:k,initialWorkspaceId:U,initialWorkspacePath:ae,sendDaemonCommand:a})]}),h==="providers"&&t.jsx(_h,{machineId:s,providers:$,sendDaemonCommand:a}),h==="overview"&&t.jsx(Nh,{machineId:s,machine:T,ideSessions:K,cliSessions:F,acpSessions:M,actions:x,sendDaemonCommand:a}),h==="session-host"&&t.jsx(Wh,{machineId:s,cliSessions:F,sendDaemonCommand:a}),h==="logs"&&t.jsx(Eh,{machineId:s,sendDaemonCommand:a})]})})}),x.launchPick&&T&&t.jsx(Oh,{machine:T,launchPick:x.launchPick,actions:x}),b&&t.jsx($a,{title:b.title,description:b.description,details:b.details,workspaceOptions:b.workspaceOptions,selectedWorkspaceKey:C,onWorkspaceChange:B=>{f.current=B,_(B)},confirmLabel:b.confirmLabel,busyLabel:b.busyLabel,busy:g,onConfirm:me,onCancel:()=>{d.current=null,v(null)}}),t.jsx(tc,{toasts:c.toasts||[],onDismiss:B=>c.setToasts(ke=>ke.filter(ve=>ve.id!==B)),onClickToast:B=>{B.targetKey&&r(Zt(B.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
|
-
`})]})}function Wa(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function qh(e){if(typeof window>"u")return e;const s=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),r=Wa();return r&&!s.searchParams.has("token")&&s.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?s.toString():`${s.pathname}${s.search}${s.hash}`}async function Xt(e,s){return await fetch(qh(e),{credentials:"same-origin",...s})}function Gc(){if(typeof window>"u")return;const e=new URL(window.location.href);e.searchParams.has("token")&&(e.searchParams.delete("token"),window.history.replaceState({},"",`${e.pathname}${e.search}${e.hash}`))}class Yh{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}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 Xt(`/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 Ht=new Yh;function Xh(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=Wa();return r?`${s}?token=${encodeURIComponent(r)}`:s}const Lr=Xh(),ei=3e3,Qh=3e4;let Wt=null,Jh=0;const Xr=new Map;let as=null,nr=null;function ti(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function Qs(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function Zh(e){return e==="connected"?"connected":e}async function Br(e,s,r){const n=Im(e,r||{}),a=Wt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++Jh}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{Xr.delete(i),l(new Error(`WS command timeout: ${s}`))},3e4);Xr.set(i,{resolve:p=>{clearTimeout(u),c(p)},reject:p=>{clearTimeout(u),l(p)}}),a.send(JSON.stringify({type:"command",requestId:i,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function na(e,s){const r=Wt;if(!r||r.readyState!==WebSocket.OPEN||!s||s.type!=="subscribe"&&s.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class ex{constructor(s){qe(this,"daemonId");qe(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Wt==null?void 0:Wt.readyState)===WebSocket.OPEN}get connectionState(){return(Wt==null?void 0:Wt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return Br(this.daemonId,s,r)}async sendInput(s,r){return Br(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,as&&(clearInterval(as),as=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Br(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());Ht.emitScreenshot(this.daemonId,a)}}catch{}};r(),as=setInterval(r,2e3)}stopScreenshots(s){as&&(clearInterval(as),as=null)}}let Pt=null;function tx(e){return(!Pt||Pt.daemonId!==e)&&(Pt=new ex(e)),Pt}function sx({children:e}){const s=o.useRef(Wr()),r=Wr();s.current=r;const{setUserName:n}=xs(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),u=o.useCallback((d,b)=>{l(d),nr==null||nr(d,b)},[]),p=o.useRef(null),m=o.useRef(),h=o.useRef(ei),y=o.useRef(!0),k=o.useRef(!1),A=o.useRef("initial_connect");return o.useEffect(()=>{y.current=!0,k.current=!1;function d(){var f,C;if(!y.current||((f=p.current)==null?void 0:f.readyState)===WebSocket.OPEN||((C=p.current)==null?void 0:C.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${Lr}...`),Qs("connect_attempt",{url:Lr,reason:A.current,delayMs:h.current});let v;try{v=new WebSocket(Lr)}catch(_){console.error("[Standalone WS] Failed to create WebSocket:",_),b();return}p.current=v,v.onopen=()=>{if(!y.current){v.close();return}u("connected"),h.current=ei,Qs("open",{url:Lr,reason:A.current}),es.resubscribeAll({sendData:na}),console.log("[Standalone WS] Connected")},Wt=v,v.onmessage=_=>{var g,I;try{const j=JSON.parse(_.data);if((j.type==="command_result"||j.type==="error")&&j.requestId){const w=Xr.get(j.requestId);w&&(Xr.delete(j.requestId),j.type==="error"?w.reject(new Error(((g=j.data)==null?void 0:g.message)||"Command failed")):w.resolve(j.data));return}if(j.type==="session_output"){const w=j.sessionId||j.cliId||j.cliType;w&&Ht.emitSessionOutput(w,typeof j.data=="string"?j.data:"",typeof j.seq=="number"?j.seq:void 0);return}if(j.type==="runtime_snapshot"){Ht.emitRuntimeSnapshot(j.sessionId,typeof j.text=="string"?j.text:"",typeof j.seq=="number"?j.seq:0,!!j.truncated);return}if(j.type==="topic_update"){const w=j.update;w&&es.publish(w);return}if(j.type==="status"||j.type==="initial_state"){const w=j.data;if(!w)return;const{injectEntries:x,markLoaded:$,getIdes:N}=s.current,L=w.instanceId||"standalone",T=N().find(M=>M.id===L),K=tx(L);Ht.register(L,K),Ht.setState(L,"connected"),u("connected",L),Ht.emitStatus(L,w);const F=Fr(w,{daemonId:L,existingDaemon:T,existingEntries:N()});ti("ws_status",{type:j.type,daemonId:L,sessions:(w.sessions||[]).map(M=>({id:M.id,parentId:M.parentId,providerType:M.providerType,kind:M.kind,transport:M.transport,unread:M.unread,inboxBucket:M.inboxBucket,lastSeenAt:M.lastSeenAt,lastUpdated:M.lastUpdated,title:M.title})),recentLaunches:(w.recentLaunches||[]).map(M=>({id:M.id,providerType:M.providerType,kind:M.kind,workspace:M.workspace,lastLaunchedAt:M.lastLaunchedAt}))}),ti("entries",{daemonId:L,entries:F.filter(M=>M.type!=="adhdev-daemon").map(M=>({id:M.id,type:M.type,unread:M.unread,inboxBucket:M.inboxBucket,lastSeenAt:M.lastSeenAt,lastUpdated:M.lastUpdated,sessionId:M.sessionId}))}),F.length>0&&x(F,{authoritativeDaemonIds:[L]}),$(),c.current!==L&&((I=i.current)==null||I.call(i),c.current=L,i.current=es.subscribe({sendData:na},L,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${L}`,params:{includeSessions:!0}},M=>{if(M.topic!=="daemon.metadata")return;const P=s.current.getIdes(),O=P.find(D=>D.id===L),S=Fr(M.status,{daemonId:L,existingDaemon:O,existingEntries:P,timestamp:M.timestamp});S.length>0&&s.current.injectEntries(S),M.userName&&a.current&&a.current(M.userName)}))}}catch(j){console.error("[Standalone WS] Parse error:",j)}},v.onclose=_=>{y.current&&(Pt==null||Pt.stopScreenshots(),Pt&&Ht.setState(Pt.daemonId,"disconnected"),u("disconnected"),p.current=null,A.current=`close:${_.code}${_.wasClean?":clean":":unclean"}`,Qs("close",{code:_.code,reason:_.reason||"",wasClean:_.wasClean}),b())},v.onerror=_=>{k.current||!y.current||(A.current="error",Qs("error",{message:_ instanceof Event?"event":String(_),readyState:v.readyState}),console.warn("[Standalone WS] Error, will reconnect:",_))}}function b(){if(!y.current)return;clearTimeout(m.current);const v=h.current;console.log(`[Standalone WS] Reconnecting in ${v}ms...`),Qs("schedule_reconnect",{reason:A.current,delayMs:v}),m.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,Qh),d()},v)}return d(),()=>{var v;y.current=!1,k.current=!0,(v=i.current)==null||v.call(i),i.current=null,c.current=null,clearTimeout(m.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,Wt=null),Pt&&(Pt.stopScreenshots(),Ht.unregister(Pt.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function rx({children:e}){const[s,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(nr=(c,l)=>{r(c),l&&a(l)},()=>{nr=null}),[]);const i=o.useMemo(()=>{const c=s==="connected",l=Zh(s),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:s,isConnected:c,connectionStates:u}},[s,n]);return t.jsx(_l,{connectionOverrides:i,children:t.jsx(sx,{children:e})})}const nx=[{id:"dashboard",path:"/dashboard",icon:t.jsx(di,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(zt,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx(Qr,{}),label:"Settings"}];function ax({children:e}){const s=Os(),r=ia(),[n,a]=o.useState(!1),[i,c]=o.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),l=m=>{s(m),a(!1)},u=()=>{c(m=>{const h=!m;try{localStorage.setItem("sidebar-collapsed",h?"1":"0")}catch{}return h})},p=m=>`nav-item${r.pathname.startsWith(m)?" active":""} cursor-pointer ${i?"justify-center py-2.5 px-0":""}`;return t.jsxs("div",{className:`app-layout${n?" mobile-menu-open":""}${i?" sidebar-collapsed":""}`,children:[t.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:()=>a(!0),children:[t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"})]}),n&&t.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:()=>a(!1),onKeyDown:m=>m.key==="Escape"&&a(!1)}),t.jsxs("aside",{className:`sidebar ${n?"sidebar-open":""}`,children:[t.jsxs("div",{className:"sidebar-header",children:[t.jsxs("div",{className:`sidebar-logo ${i?"justify-center gap-0":""}`,children:[t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&t.jsx("span",{children:"ADHDev"})]}),t.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:()=>a(!1),children:t.jsx(Nt,{size:16})})]}),t.jsx("nav",{className:"sidebar-nav",children:nx.map(m=>t.jsxs("div",{className:p(m.path),id:`nav-${m.id}`,onClick:()=>l(m.path),title:i?m.label:void 0,children:[t.jsx("span",{className:"nav-icon",children:m.icon}),!i&&m.label]},m.id))}),t.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":""}`,id:"nav-docs",onClick:()=>window.open("https://docs.adhf.dev","_blank"),title:i?"Docs":void 0,children:[t.jsx("span",{className:"nav-icon",children:t.jsx(ui,{})}),!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(mi,{})}),!i&&"About"]}),!i&&t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.78"]}),t.jsx(Km,{collapsed:i}),t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:u,title:i?"Expand sidebar":"Collapse sidebar",children:[t.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&t.jsx("span",{className:"text-xs",children:"Collapse"})]})]})]}),t.jsx("main",{className:"main-content relative",children:t.jsx("div",{className:"main-content-inner",children:e})})]})}const ox=[{icon:t.jsx(zt,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(Vt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(ua,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(Lt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(or,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(ui,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],ix=[{icon:t.jsx(ql,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(di,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(Zr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(Ol,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(la,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(Ul,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],cx=[{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 lx(){return t.jsxs(ic,{icon:t.jsx(mi,{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.78"]}),children:[t.jsx(Tt,{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(Tt,{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:ox.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(Tt,{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:nc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:oc.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:ac.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(Tt,{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:ix.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(Tt,{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:cx.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(cc,{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(nd,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function dx(){const{ides:e}=xs(),s=e.find(O=>O.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=Dt(),{userName:a}=xs(),[i,c]=o.useState(a||""),[l,u]=o.useState(null),[p,m]=o.useState(null),[h,y]=o.useState("127.0.0.1"),[k,A]=o.useState(""),[d,b]=o.useState(""),[v,f]=o.useState(""),[C,_]=o.useState(""),[g,I]=o.useState(""),[j,w]=o.useState(!1),x=async()=>{const S=await(await Xt("/auth/session")).json();u(S)},$=async()=>{const S=await(await Xt("/api/v1/standalone/preferences")).json();m(S),y(S.standaloneBindHost)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([x(),$()]).catch(O=>{_(O instanceof Error?O.message:String(O))})},[]);const N=O=>{const S=O.target.value.trim();s!=null&&s.id&&S!==a&&n(s.id,"set_user_name",{userName:S}).catch(console.error)},[L,T]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),K=O=>{T(O);try{localStorage.setItem("adhdev_sound",O?"1":"0")}catch{}},F=async()=>{_(""),I(""),w(!0);try{const O=await Xt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:h})}),S=await O.json();if(!O.ok)throw new Error((S==null?void 0:S.error)||"Failed to save standalone network preference");m(S),y(S.standaloneBindHost),I(S.standaloneBindHost==="0.0.0.0"?"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.":"Default standalone network mode set to localhost only. Restart standalone to apply it.")}catch(O){_(O instanceof Error?O.message:String(O))}finally{w(!1)}},M=async()=>{if(_(""),I(""),d.trim().length<4){_("Password must be at least 4 characters.");return}if(d!==v){_("New password and confirmation do not match.");return}w(!0);try{const O=await Xt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:k,newPassword:d})}),S=await O.json();if(!O.ok)throw new Error((S==null?void 0:S.error)||"Failed to save password");u(S),await $(),A(""),b(""),f(""),I(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Gc()}catch(O){_(O instanceof Error?O.message:String(O))}finally{w(!1)}},P=async()=>{_(""),I(""),w(!0);try{const O=await Xt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:k,clear:!0})}),S=await O.json();if(!O.ok)throw new Error((S==null?void 0:S.error)||"Failed to clear password");u(S),await $(),A(""),b(""),f(""),I("Standalone password disabled.")}catch(O){_(O instanceof Error?O.message:String(O))}finally{w(!1)}};return t.jsxs(ic,{icon:t.jsx(Qr,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(wr,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint."}),(l==null?void 0:l.publicHostWarning)&&t.jsx(wr,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),t.jsx(Tt,{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.78"]}),t.jsx("span",{className:"text-text-muted",children:"Status"}),t.jsx("span",{className:s?"text-green-400":"text-yellow-400",children:s?"● Running":"○ Not connected"}),t.jsx("span",{className:"text-text-muted",children:"Current bind"}),t.jsx("span",{className:"font-mono text-xs",children:(p==null?void 0:p.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Default bind"}),t.jsx("span",{className:"font-mono text-xs",children:(p==null?void 0:p.standaloneBindHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Auth"}),t.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),t.jsx(Tt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[t.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[t.jsx("input",{type:"radio",name:"standalone-bind-host",checked:h==="127.0.0.1",onChange:()=>y("127.0.0.1")}),t.jsxs("span",{children:[t.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),t.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 127.0.0.1. Best when only this machine should open the dashboard."})]})]}),t.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[t.jsx("input",{type:"radio",name:"standalone-bind-host",checked:h==="0.0.0.0",onChange:()=>y("0.0.0.0")}),t.jsxs("span",{children:[t.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),t.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points."})]})]})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",onClick:()=>{F()},disabled:j,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:j?"Saving…":"Save default network mode"}),t.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(p==null?void 0:p.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),t.jsx(Tt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:l!=null&&l.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),C&&t.jsx(wr,{variant:"error",children:C}),g&&t.jsx(wr,{variant:"success",children:g}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[t.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:k,onChange:O=>A(O.target.value)}),t.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"New password":"New standalone password",value:d,onChange:O=>b(O.target.value)}),t.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors md:col-span-2",placeholder:"Confirm new password",value:v,onChange:O=>f(O.target.value)})]}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",onClick:()=>{M()},disabled:j,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:j?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&t.jsx("button",{type:"button",onClick:()=>{P()},disabled:j,className:"rounded-lg border border-red-500/30 bg-red-500/10 text-red-300 px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Disable password"})]})]})}),t.jsx(Tt,{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(O=>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 ${O.running?"bg-green-400":"bg-text-muted/30"}`}),t.jsx("span",{className:"text-sm font-medium",children:O.name})]}),t.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:O.type})]},O.type))})}),t.jsx(Tt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(Um,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),t.jsx(Tt,{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(Gm,{})]}),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(tp,{})]}),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(rp,{})]})]})}),t.jsx(Tt,{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(Wm,{}),t.jsx(os,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(rd,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:L,onChange:K})]})}),t.jsx(Tt,{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(Wl,{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:O=>c(O.target.value),onBlur:N,onKeyDown:O=>{O.key==="Enter"&&O.currentTarget.blur()}})]})})})]})}Bm();Zm();const ux=ii({baseUrl:"",getToken:Wa});function mx({children:e}){const[s,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,u]=o.useState(""),[p,m]=o.useState(!1),h=async()=>{a(!0),u("");try{const A=await(await Xt("/auth/session")).json();r(A)}catch(k){u(k instanceof Error?k.message:String(k))}finally{a(!1)}};o.useEffect(()=>{h()},[]);const y=async k=>{k.preventDefault(),m(!0),u("");try{const A=await Xt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),d=await A.json();if(!A.ok)throw new Error((d==null?void 0:d.error)||"Login failed");r(d),c(""),Gc()}catch(A){u(A instanceof Error?A.message:String(A))}finally{m(!1)}};return n?t.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):s?!s.required||s.authenticated?t.jsx(t.Fragment,{children:e}):t.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:t.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),t.jsx("p",{className:"text-sm text-text-muted mt-1",children:s.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),s.hasPasswordAuth?t.jsxs("form",{className:"flex flex-col gap-3",onSubmit:y,children:[t.jsx("input",{type:"password",value:i,onChange:k=>c(k.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),t.jsx("button",{type:"submit",disabled:p||!i,className:"rounded-lg bg-accent text-white px-3 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:p?"Signing in…":"Unlock dashboard"})]}):t.jsx("div",{className:"rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-300",children:"Password login is not enabled on this server."}),l&&t.jsx("div",{className:"rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:l})]})}):t.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",l||"unknown error"]})}function si(){const{ides:e,initialLoaded:s}=xs();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(zn,{to:`/machines/${r.id}`,replace:!0}):t.jsx(zn,{to:"/dashboard",replace:!0})}function px(){const e=o.useMemo(()=>({sendCommand:Br,sendData:na}),[]);return t.jsx(kl,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(Dl,{client:ux,children:t.jsx(mx,{children:t.jsx(rx,{children:t.jsx($l,{value:e,children:t.jsx(ax,{children:t.jsxs(Sl,{children:[t.jsx(rs,{path:"/dashboard",element:t.jsx(kh,{})}),t.jsx(rs,{path:"/machine",element:t.jsx(si,{})}),t.jsx(rs,{path:"/machines/:id",element:t.jsx(Gh,{})}),t.jsx(rs,{path:"/machines",element:t.jsx(si,{})}),t.jsx(rs,{path:"/about",element:t.jsx(lx,{})}),t.jsx(rs,{path:"/settings",element:t.jsx(dx,{})}),t.jsx(rs,{path:"*",element:t.jsx(zn,{to:"/dashboard",replace:!0})})]})})})})})})})}Zu({connectionManager:Ht});Nl(document.getElementById("root")).render(t.jsx(px,{}));
|
|
72
|
+
`})]})}function Wa(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function qh(e){if(typeof window>"u")return e;const s=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),r=Wa();return r&&!s.searchParams.has("token")&&s.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?s.toString():`${s.pathname}${s.search}${s.hash}`}async function Xt(e,s){return await fetch(qh(e),{credentials:"same-origin",...s})}function Gc(){if(typeof window>"u")return;const e=new URL(window.location.href);e.searchParams.has("token")&&(e.searchParams.delete("token"),window.history.replaceState({},"",`${e.pathname}${e.search}${e.hash}`))}class Yh{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}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 Xt(`/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 Ht=new Yh;function Xh(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=Wa();return r?`${s}?token=${encodeURIComponent(r)}`:s}const Lr=Xh(),ei=3e3,Qh=3e4;let Wt=null,Jh=0;const Xr=new Map;let as=null,nr=null;function ti(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function Qs(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function Zh(e){return e==="connected"?"connected":e}async function Br(e,s,r){const n=Im(e,r||{}),a=Wt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++Jh}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{Xr.delete(i),l(new Error(`WS command timeout: ${s}`))},3e4);Xr.set(i,{resolve:p=>{clearTimeout(u),c(p)},reject:p=>{clearTimeout(u),l(p)}}),a.send(JSON.stringify({type:"command",requestId:i,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function na(e,s){const r=Wt;if(!r||r.readyState!==WebSocket.OPEN||!s||s.type!=="subscribe"&&s.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class ex{constructor(s){qe(this,"daemonId");qe(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Wt==null?void 0:Wt.readyState)===WebSocket.OPEN}get connectionState(){return(Wt==null?void 0:Wt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return Br(this.daemonId,s,r)}async sendInput(s,r){return Br(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,as&&(clearInterval(as),as=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Br(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());Ht.emitScreenshot(this.daemonId,a)}}catch{}};r(),as=setInterval(r,2e3)}stopScreenshots(s){as&&(clearInterval(as),as=null)}}let Pt=null;function tx(e){return(!Pt||Pt.daemonId!==e)&&(Pt=new ex(e)),Pt}function sx({children:e}){const s=o.useRef(Wr()),r=Wr();s.current=r;const{setUserName:n}=xs(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),u=o.useCallback((d,b)=>{l(d),nr==null||nr(d,b)},[]),p=o.useRef(null),m=o.useRef(),h=o.useRef(ei),y=o.useRef(!0),k=o.useRef(!1),A=o.useRef("initial_connect");return o.useEffect(()=>{y.current=!0,k.current=!1;function d(){var f,C;if(!y.current||((f=p.current)==null?void 0:f.readyState)===WebSocket.OPEN||((C=p.current)==null?void 0:C.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${Lr}...`),Qs("connect_attempt",{url:Lr,reason:A.current,delayMs:h.current});let v;try{v=new WebSocket(Lr)}catch(_){console.error("[Standalone WS] Failed to create WebSocket:",_),b();return}p.current=v,v.onopen=()=>{if(!y.current){v.close();return}u("connected"),h.current=ei,Qs("open",{url:Lr,reason:A.current}),es.resubscribeAll({sendData:na}),console.log("[Standalone WS] Connected")},Wt=v,v.onmessage=_=>{var g,I;try{const j=JSON.parse(_.data);if((j.type==="command_result"||j.type==="error")&&j.requestId){const w=Xr.get(j.requestId);w&&(Xr.delete(j.requestId),j.type==="error"?w.reject(new Error(((g=j.data)==null?void 0:g.message)||"Command failed")):w.resolve(j.data));return}if(j.type==="session_output"){const w=j.sessionId||j.cliId||j.cliType;w&&Ht.emitSessionOutput(w,typeof j.data=="string"?j.data:"",typeof j.seq=="number"?j.seq:void 0);return}if(j.type==="runtime_snapshot"){Ht.emitRuntimeSnapshot(j.sessionId,typeof j.text=="string"?j.text:"",typeof j.seq=="number"?j.seq:0,!!j.truncated);return}if(j.type==="topic_update"){const w=j.update;w&&es.publish(w);return}if(j.type==="status"||j.type==="initial_state"){const w=j.data;if(!w)return;const{injectEntries:x,markLoaded:$,getIdes:N}=s.current,L=w.instanceId||"standalone",T=N().find(M=>M.id===L),K=tx(L);Ht.register(L,K),Ht.setState(L,"connected"),u("connected",L),Ht.emitStatus(L,w);const F=Fr(w,{daemonId:L,existingDaemon:T,existingEntries:N()});ti("ws_status",{type:j.type,daemonId:L,sessions:(w.sessions||[]).map(M=>({id:M.id,parentId:M.parentId,providerType:M.providerType,kind:M.kind,transport:M.transport,unread:M.unread,inboxBucket:M.inboxBucket,lastSeenAt:M.lastSeenAt,lastUpdated:M.lastUpdated,title:M.title})),recentLaunches:(w.recentLaunches||[]).map(M=>({id:M.id,providerType:M.providerType,kind:M.kind,workspace:M.workspace,lastLaunchedAt:M.lastLaunchedAt}))}),ti("entries",{daemonId:L,entries:F.filter(M=>M.type!=="adhdev-daemon").map(M=>({id:M.id,type:M.type,unread:M.unread,inboxBucket:M.inboxBucket,lastSeenAt:M.lastSeenAt,lastUpdated:M.lastUpdated,sessionId:M.sessionId}))}),F.length>0&&x(F,{authoritativeDaemonIds:[L]}),$(),c.current!==L&&((I=i.current)==null||I.call(i),c.current=L,i.current=es.subscribe({sendData:na},L,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${L}`,params:{includeSessions:!0}},M=>{if(M.topic!=="daemon.metadata")return;const P=s.current.getIdes(),O=P.find(D=>D.id===L),S=Fr(M.status,{daemonId:L,existingDaemon:O,existingEntries:P,timestamp:M.timestamp});S.length>0&&s.current.injectEntries(S),M.userName&&a.current&&a.current(M.userName)}))}}catch(j){console.error("[Standalone WS] Parse error:",j)}},v.onclose=_=>{y.current&&(Pt==null||Pt.stopScreenshots(),Pt&&Ht.setState(Pt.daemonId,"disconnected"),u("disconnected"),p.current=null,A.current=`close:${_.code}${_.wasClean?":clean":":unclean"}`,Qs("close",{code:_.code,reason:_.reason||"",wasClean:_.wasClean}),b())},v.onerror=_=>{k.current||!y.current||(A.current="error",Qs("error",{message:_ instanceof Event?"event":String(_),readyState:v.readyState}),console.warn("[Standalone WS] Error, will reconnect:",_))}}function b(){if(!y.current)return;clearTimeout(m.current);const v=h.current;console.log(`[Standalone WS] Reconnecting in ${v}ms...`),Qs("schedule_reconnect",{reason:A.current,delayMs:v}),m.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,Qh),d()},v)}return d(),()=>{var v;y.current=!1,k.current=!0,(v=i.current)==null||v.call(i),i.current=null,c.current=null,clearTimeout(m.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,Wt=null),Pt&&(Pt.stopScreenshots(),Ht.unregister(Pt.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function rx({children:e}){const[s,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(nr=(c,l)=>{r(c),l&&a(l)},()=>{nr=null}),[]);const i=o.useMemo(()=>{const c=s==="connected",l=Zh(s),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:s,isConnected:c,connectionStates:u}},[s,n]);return t.jsx(_l,{connectionOverrides:i,children:t.jsx(sx,{children:e})})}const nx=[{id:"dashboard",path:"/dashboard",icon:t.jsx(di,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(zt,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx(Qr,{}),label:"Settings"}];function ax({children:e}){const s=Os(),r=ia(),[n,a]=o.useState(!1),[i,c]=o.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),l=m=>{s(m),a(!1)},u=()=>{c(m=>{const h=!m;try{localStorage.setItem("sidebar-collapsed",h?"1":"0")}catch{}return h})},p=m=>`nav-item${r.pathname.startsWith(m)?" active":""} cursor-pointer ${i?"justify-center py-2.5 px-0":""}`;return t.jsxs("div",{className:`app-layout${n?" mobile-menu-open":""}${i?" sidebar-collapsed":""}`,children:[t.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:()=>a(!0),children:[t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"})]}),n&&t.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:()=>a(!1),onKeyDown:m=>m.key==="Escape"&&a(!1)}),t.jsxs("aside",{className:`sidebar ${n?"sidebar-open":""}`,children:[t.jsxs("div",{className:"sidebar-header",children:[t.jsxs("div",{className:`sidebar-logo ${i?"justify-center gap-0":""}`,children:[t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&t.jsx("span",{children:"ADHDev"})]}),t.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:()=>a(!1),children:t.jsx(Nt,{size:16})})]}),t.jsx("nav",{className:"sidebar-nav",children:nx.map(m=>t.jsxs("div",{className:p(m.path),id:`nav-${m.id}`,onClick:()=>l(m.path),title:i?m.label:void 0,children:[t.jsx("span",{className:"nav-icon",children:m.icon}),!i&&m.label]},m.id))}),t.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":""}`,id:"nav-docs",onClick:()=>window.open("https://docs.adhf.dev","_blank"),title:i?"Docs":void 0,children:[t.jsx("span",{className:"nav-icon",children:t.jsx(ui,{})}),!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(mi,{})}),!i&&"About"]}),!i&&t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.79"]}),t.jsx(Km,{collapsed:i}),t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:u,title:i?"Expand sidebar":"Collapse sidebar",children:[t.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&t.jsx("span",{className:"text-xs",children:"Collapse"})]})]})]}),t.jsx("main",{className:"main-content relative",children:t.jsx("div",{className:"main-content-inner",children:e})})]})}const ox=[{icon:t.jsx(zt,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(Vt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(ua,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(Lt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(or,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(ui,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],ix=[{icon:t.jsx(ql,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(di,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(Zr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(Ol,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(la,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(Ul,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],cx=[{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 lx(){return t.jsxs(ic,{icon:t.jsx(mi,{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.79"]}),children:[t.jsx(Tt,{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(Tt,{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:ox.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(Tt,{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:nc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:oc.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:ac.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(Tt,{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:ix.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(Tt,{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:cx.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(cc,{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(nd,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function dx(){const{ides:e}=xs(),s=e.find(O=>O.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=Dt(),{userName:a}=xs(),[i,c]=o.useState(a||""),[l,u]=o.useState(null),[p,m]=o.useState(null),[h,y]=o.useState("127.0.0.1"),[k,A]=o.useState(""),[d,b]=o.useState(""),[v,f]=o.useState(""),[C,_]=o.useState(""),[g,I]=o.useState(""),[j,w]=o.useState(!1),x=async()=>{const S=await(await Xt("/auth/session")).json();u(S)},$=async()=>{const S=await(await Xt("/api/v1/standalone/preferences")).json();m(S),y(S.standaloneBindHost)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([x(),$()]).catch(O=>{_(O instanceof Error?O.message:String(O))})},[]);const N=O=>{const S=O.target.value.trim();s!=null&&s.id&&S!==a&&n(s.id,"set_user_name",{userName:S}).catch(console.error)},[L,T]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),K=O=>{T(O);try{localStorage.setItem("adhdev_sound",O?"1":"0")}catch{}},F=async()=>{_(""),I(""),w(!0);try{const O=await Xt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:h})}),S=await O.json();if(!O.ok)throw new Error((S==null?void 0:S.error)||"Failed to save standalone network preference");m(S),y(S.standaloneBindHost),I(S.standaloneBindHost==="0.0.0.0"?"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.":"Default standalone network mode set to localhost only. Restart standalone to apply it.")}catch(O){_(O instanceof Error?O.message:String(O))}finally{w(!1)}},M=async()=>{if(_(""),I(""),d.trim().length<4){_("Password must be at least 4 characters.");return}if(d!==v){_("New password and confirmation do not match.");return}w(!0);try{const O=await Xt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:k,newPassword:d})}),S=await O.json();if(!O.ok)throw new Error((S==null?void 0:S.error)||"Failed to save password");u(S),await $(),A(""),b(""),f(""),I(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Gc()}catch(O){_(O instanceof Error?O.message:String(O))}finally{w(!1)}},P=async()=>{_(""),I(""),w(!0);try{const O=await Xt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:k,clear:!0})}),S=await O.json();if(!O.ok)throw new Error((S==null?void 0:S.error)||"Failed to clear password");u(S),await $(),A(""),b(""),f(""),I("Standalone password disabled.")}catch(O){_(O instanceof Error?O.message:String(O))}finally{w(!1)}};return t.jsxs(ic,{icon:t.jsx(Qr,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(wr,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint."}),(l==null?void 0:l.publicHostWarning)&&t.jsx(wr,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),t.jsx(Tt,{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.79"]}),t.jsx("span",{className:"text-text-muted",children:"Status"}),t.jsx("span",{className:s?"text-green-400":"text-yellow-400",children:s?"● Running":"○ Not connected"}),t.jsx("span",{className:"text-text-muted",children:"Current bind"}),t.jsx("span",{className:"font-mono text-xs",children:(p==null?void 0:p.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Default bind"}),t.jsx("span",{className:"font-mono text-xs",children:(p==null?void 0:p.standaloneBindHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Auth"}),t.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),t.jsx(Tt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[t.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[t.jsx("input",{type:"radio",name:"standalone-bind-host",checked:h==="127.0.0.1",onChange:()=>y("127.0.0.1")}),t.jsxs("span",{children:[t.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),t.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 127.0.0.1. Best when only this machine should open the dashboard."})]})]}),t.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[t.jsx("input",{type:"radio",name:"standalone-bind-host",checked:h==="0.0.0.0",onChange:()=>y("0.0.0.0")}),t.jsxs("span",{children:[t.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),t.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points."})]})]})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",onClick:()=>{F()},disabled:j,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:j?"Saving…":"Save default network mode"}),t.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(p==null?void 0:p.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),t.jsx(Tt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:l!=null&&l.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),C&&t.jsx(wr,{variant:"error",children:C}),g&&t.jsx(wr,{variant:"success",children:g}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[t.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:k,onChange:O=>A(O.target.value)}),t.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"New password":"New standalone password",value:d,onChange:O=>b(O.target.value)}),t.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors md:col-span-2",placeholder:"Confirm new password",value:v,onChange:O=>f(O.target.value)})]}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",onClick:()=>{M()},disabled:j,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:j?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&t.jsx("button",{type:"button",onClick:()=>{P()},disabled:j,className:"rounded-lg border border-red-500/30 bg-red-500/10 text-red-300 px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Disable password"})]})]})}),t.jsx(Tt,{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(O=>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 ${O.running?"bg-green-400":"bg-text-muted/30"}`}),t.jsx("span",{className:"text-sm font-medium",children:O.name})]}),t.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:O.type})]},O.type))})}),t.jsx(Tt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(Um,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),t.jsx(Tt,{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(Gm,{})]}),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(tp,{})]}),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(rp,{})]})]})}),t.jsx(Tt,{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(Wm,{}),t.jsx(os,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(rd,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:L,onChange:K})]})}),t.jsx(Tt,{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(Wl,{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:O=>c(O.target.value),onBlur:N,onKeyDown:O=>{O.key==="Enter"&&O.currentTarget.blur()}})]})})})]})}Bm();Zm();const ux=ii({baseUrl:"",getToken:Wa});function mx({children:e}){const[s,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,u]=o.useState(""),[p,m]=o.useState(!1),h=async()=>{a(!0),u("");try{const A=await(await Xt("/auth/session")).json();r(A)}catch(k){u(k instanceof Error?k.message:String(k))}finally{a(!1)}};o.useEffect(()=>{h()},[]);const y=async k=>{k.preventDefault(),m(!0),u("");try{const A=await Xt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),d=await A.json();if(!A.ok)throw new Error((d==null?void 0:d.error)||"Login failed");r(d),c(""),Gc()}catch(A){u(A instanceof Error?A.message:String(A))}finally{m(!1)}};return n?t.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):s?!s.required||s.authenticated?t.jsx(t.Fragment,{children:e}):t.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:t.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),t.jsx("p",{className:"text-sm text-text-muted mt-1",children:s.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),s.hasPasswordAuth?t.jsxs("form",{className:"flex flex-col gap-3",onSubmit:y,children:[t.jsx("input",{type:"password",value:i,onChange:k=>c(k.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),t.jsx("button",{type:"submit",disabled:p||!i,className:"rounded-lg bg-accent text-white px-3 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:p?"Signing in…":"Unlock dashboard"})]}):t.jsx("div",{className:"rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-300",children:"Password login is not enabled on this server."}),l&&t.jsx("div",{className:"rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:l})]})}):t.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",l||"unknown error"]})}function si(){const{ides:e,initialLoaded:s}=xs();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(zn,{to:`/machines/${r.id}`,replace:!0}):t.jsx(zn,{to:"/dashboard",replace:!0})}function px(){const e=o.useMemo(()=>({sendCommand:Br,sendData:na}),[]);return t.jsx(kl,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(Dl,{client:ux,children:t.jsx(mx,{children:t.jsx(rx,{children:t.jsx($l,{value:e,children:t.jsx(ax,{children:t.jsxs(Sl,{children:[t.jsx(rs,{path:"/dashboard",element:t.jsx(kh,{})}),t.jsx(rs,{path:"/machine",element:t.jsx(si,{})}),t.jsx(rs,{path:"/machines/:id",element:t.jsx(Gh,{})}),t.jsx(rs,{path:"/machines",element:t.jsx(si,{})}),t.jsx(rs,{path:"/about",element:t.jsx(lx,{})}),t.jsx(rs,{path:"/settings",element:t.jsx(dx,{})}),t.jsx(rs,{path:"*",element:t.jsx(zn,{to:"/dashboard",replace:!0})})]})})})})})})})}Zu({connectionManager:Ht});Nl(document.getElementById("root")).render(t.jsx(px,{}));
|