@adhdev/daemon-standalone 0.9.60 → 0.9.61
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.
|
@@ -37,7 +37,7 @@ ${JSON.stringify(t.bundle,null,2)}
|
|
|
37
37
|
${JSON.stringify(t,null,2)}
|
|
38
38
|
\`\`\``}function vt(e){return(typeof e=="string"?e.trim():"")||void 0}function Ft(e,t){const r=vt(t);return r?`${e}:${r}`:void 0}function Gt(e,t,r){const n=Ft(t,r),a=vt(r);n&&e.push(n),a&&e.push(a)}function ws(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function Tc(e){return vt(e.providerSessionId)||vt(e.sessionId)||vt(e.tabKey)||vt(e.routeId)}function Ga(e){return ws([vt(e.providerSessionId),vt(e.sessionId)])}function Ss(e){const t=[];return Gt(t,"provider",e.providerSessionId),Gt(t,"session",e.sessionId),Gt(t,"tab",e.tabKey),Gt(t,"route",e.routeId),ws(t)}function am(e){const t=[];return vt(e.providerSessionId)?(Gt(t,"provider",e.providerSessionId),ws(t)):vt(e.sessionId)?(Gt(t,"session",e.sessionId),ws(t)):vt(e.tabKey)?(Gt(t,"tab",e.tabKey),ws(t)):vt(e.routeId)?(Gt(t,"route",e.routeId),ws(t)):[]}function qa(e){return Ft("provider",e.providerSessionId)||Ft("session",e.sessionId)||Ft("tab",e.tabKey)||Ft("route",e.routeId)||"unknown:"}function ur(e){return Ga(e)[0]}function om(e){const t=vt(e.providerSessionId),r=vt(e.sessionId),n=vt(e.tabKey),a=vt(e.routeId),o=[Ft("provider",t),Ft("session",r),Ft("tab",n),Ft("route",a)].filter(d=>typeof d=="string"),c=Ss({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),l=qa({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:Tc({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:ur({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:o,lookupKeys:c}}function ha(e,t){const r=om(e);return am(t).some(n=>r.lookupKeys.includes(n))}function Ho(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function ss(e){const t=[...e.messages].reverse().find(a=>!(a!=null&&a._localId))||e.messages[e.messages.length-1],r=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,n=Ho(t==null?void 0:t.receivedAt)||Ho(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function xa(e,t=0){return ss(e)||e.lastUpdated||t||0}function Mc(e){return ss(e)||e.lastUpdated||0}function Ac(e,t,r=Mc){const n=r(t)-r(e);if(n!==0)return n;const a=(e.machineName||"").localeCompare(t.machineName||"");if(a!==0)return a;const o=e.displayPrimary.localeCompare(t.displayPrimary);if(o!==0)return o;const c=e.displaySecondary.localeCompare(t.displaySecondary);return c!==0?c:e.tabKey.localeCompare(t.tabKey)}function ba(e){var r;const t=yt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function im(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!ba(e)&&!e.title.trim()}function cm(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(ba(r))-Number(ba(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:Ac(t,r)})[0]||null}function Pt(e,t){const r=e.filter(c=>c.routeId===t);if(r.length===0)return null;const n=r.find(c=>c.streamSource==="native")||null,a=r.filter(c=>c.streamSource==="agent-stream"),o=cm(a);return n?o&&im(n)?o:n:o||r[0]||null}function Yt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Ya(e){return ur(e)||e.tabKey||e.routeId||null}function Ic(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"";if(t)return t;const r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"";if(r)return r;const n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"";if(!n)return null;const a=Pt(e.conversations,n)||e.conversations.find(o=>o.routeId===n);return a?Ya(a):null}function Lc({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const o=Ps(),c=xs(e),l=bc(e),d=e.transport==="cdp-page"||e.transport==="cdp-webview",f=e.streamSource==="agent-stream"&&!!e.agentName,u=!f&&(e.transport==="pty"||e.transport==="acp"),p=Ts(e),m=Vf(e),y=i.useCallback(()=>{if(n){n();return}c&&o("/dashboard",{state:{openMachineId:c}})},[c,o,n]),N=i.useCallback(()=>{if(r){r();return}const h=Ya(e);h&&o(Yt(h))},[e,o,r]);return s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[d&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:N,title:m,children:[s.jsx(Tt,{size:12}),s.jsx("span",{children:m})]}):s.jsxs("span",{className:"conversation-meta-chip",title:m,children:[s.jsx(Tt,{size:12}),s.jsx("span",{children:m})]})),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:p,children:[s.jsx(ar,{size:12}),s.jsx("span",{children:p})]}),u&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:p,children:[s.jsx(ar,{size:12}),s.jsx("span",{children:p})]}),l&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:y,title:l,children:[s.jsx(us,{size:12}),s.jsx("span",{children:l})]}):s.jsxs("span",{className:"conversation-meta-chip",title:l,children:[s.jsx(us,{size:12}),s.jsx("span",{children:l})]}))]})}function Tn(e,t){return`${e}:${t}`}function lm(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Fs(e,t){lm()&&console.debug(`[subscription-manager] ${e}`,t)}class dm{constructor(){Ye(this,"active",new Map);Ye(this,"retryTimers",new Map)}subscribe(t,r,n,a,o){var u;const c=Tn(n.topic,n.key),l=this.active.get(c);let d=!0;if(l)l.handlers.add(a),l.lastUpdate&&a(l.lastUpdate);else{const p={daemonId:r,request:n,handlers:new Set([a])};this.active.set(c,p),Fs("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((u=t.sendData)==null?void 0:u.call(t,r,n))??!1,!d&&(o!=null&&o.retryIntervalMs)&&this.scheduleRetry(c,t,o.retryIntervalMs)}const f=()=>{var y;this.clearRetry(c);const p=this.active.get(c);if(!p||(p.handlers.delete(a),p.handlers.size>0))return;this.active.delete(c);const m={type:"unsubscribe",topic:n.topic,key:n.key};Fs("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(y=t.sendData)==null||y.call(t,r,m)};return f.initialSendAccepted=d,f}publish(t){const r=Tn(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,Ns.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.publish",topic:t.topic,payload:{key:t.key}}),n.handlers.forEach(a=>{a(t),Ns.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.handler_invoked",topic:t.topic,payload:{key:t.key}})}))}updateParams(t,r,n){const a=Tn(t,r),o=this.active.get(a);o&&(o.request={...o.request,params:{...o.request.params,...n}})}resubscribeAll(t){var r;Fs("resubscribe_all",{count:this.active.size,subscriptions:Array.from(this.active.values()).map(n=>({daemonId:n.daemonId,topic:n.request.topic,key:n.request.key}))});for(const n of this.active.values())(r=t.sendData)==null||r.call(t,n.daemonId,n.request)}resubscribeForDaemon(t,r){var a;const n=Array.from(this.active.values()).filter(o=>o.daemonId===t);Fs("resubscribe_daemon",{daemonId:t,count:n.length,subscriptions:n.map(o=>({topic:o.request.topic,key:o.request.key}))});for(const o of n)(a=r.sendData)==null||a.call(r,o.daemonId,o.request)}scheduleRetry(t,r,n){if(this.retryTimers.has(t))return;const a=setTimeout(()=>{var l;this.retryTimers.delete(t);const o=this.active.get(t);if(!o)return;const c=((l=r.sendData)==null?void 0:l.call(r,o.daemonId,o.request))??!1;Fs("subscribe_retry",{id:t,accepted:c,topic:o.request.topic,key:o.request.key}),c||this.scheduleRetry(t,r,n)},n);this.retryTimers.set(t,a)}clearRetry(t){const r=this.retryTimers.get(t);r!==void 0&&(clearTimeout(r),this.retryTimers.delete(t))}}const Ht=new dm;function um(e,t){const r=new Map;for(const n of e||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===t&&n.sessionId){r.set(n.sessionId,{parentSessionId:n.parentSessionId,providerSessionId:n.providerSessionId,workspace:n.workspace??null,sessionCapabilities:n.sessionCapabilities,cdpConnected:n.cdpConnected,activeChat:n.activeChat,controlValues:n.controlValues,providerControls:n.providerControls,summaryMetadata:n.summaryMetadata,runtimeWriteOwner:n.runtimeWriteOwner,runtimeAttachedClients:n.runtimeAttachedClients,cliName:n.cliName,type:n.type,mode:n.mode,status:n.status,lastMessagePreview:n.lastMessagePreview,lastMessageRole:n.lastMessageRole,lastMessageAt:n.lastMessageAt,lastMessageHash:n.lastMessageHash,completionMarker:n.completionMarker,seenCompletionMarker:n.seenCompletionMarker});for(const o of n.childSessions||[]){if(!(o!=null&&o.id))continue;const c=r.get(o.id)||{};r.set(o.id,{...c,...o})}}return r}function fm(e){const t=[],r=new Map;for(const n of e)if(n.parentId){const a=r.get(n.parentId)||[];a.push(n),r.set(n.parentId,a)}else t.push(n);return{topLevel:t,childrenByParent:r}}function Zr(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:o,timestamp:c}=t,l=c||e.timestamp||Date.now(),d=e.sessions||[],{topLevel:f,childrenByParent:u}=fm(d),p=um(o,n),m=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,y=f.filter(j=>j.kind==="workspace"&&j.transport==="cdp-page"),N=f.filter(j=>j.kind==="agent"&&j.transport==="pty"),h=f.filter(j=>j.kind==="agent"&&j.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...m&&{machine:m,platform:m.platform},...e.instanceId&&{instanceId:e.instanceId},...e.machineNickname!==void 0&&{machineNickname:e.machineNickname},...e.p2p&&{p2p:e.p2p},...e.workspaces&&{workspaces:e.workspaces},...e.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:e.defaultWorkspaceId},...e.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:e.defaultWorkspacePath},...e.terminalSizingMode!==void 0&&{terminalSizingMode:e.terminalSizingMode},...e.recentLaunches&&{recentLaunches:e.recentLaunches},...e.terminalBackend&&{terminalBackend:e.terminalBackend},...e.detectedIdes&&{detectedIdes:e.detectedIdes},...e.availableProviders&&{availableProviders:e.availableProviders},_sessionListAuthoritative:Array.isArray(e.sessions),cdpConnected:y.some(j=>!!j.cdpConnected)});for(const j of y){const x=p.get(j.id),b=qs(j,x),v=(u.get(j.id)||[]).map(A=>qs(A,p.get(A.id)));r.push({id:`${n}:ide:${j.id}`,sessionId:j.id,providerSessionId:j.providerSessionId??(x==null?void 0:x.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,status:b.cdpConnected?"online":"detected",daemonId:n,instanceId:j.id,workspace:b.workspace,terminals:0,childSessions:v,agents:v.map(A=>({id:A.id,name:A.providerName||A.providerType,type:A.providerType,status:A.status})),activeChat:b.activeChat,chats:[],cdpConnected:b.cdpConnected,...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l})}for(const j of N){const x=p.get(j.id),b=qs(j,x);r.push({id:`${n}:cli:${j.id}`,sessionId:j.id,providerSessionId:j.providerSessionId??(x==null?void 0:x.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,agentType:b.providerType,status:b.status||"running",daemonId:n,instanceId:j.id,cliName:b.providerName||b.providerType,mode:b.mode||(x==null?void 0:x.mode)||"terminal",workspace:b.workspace||"",activeChat:b.activeChat,...b.resume!==void 0&&{resume:b.resume},...b.runtimeKey!==void 0&&{runtimeKey:b.runtimeKey},...b.runtimeDisplayName!==void 0&&{runtimeDisplayName:b.runtimeDisplayName},...b.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:b.runtimeWorkspaceLabel},...b.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:b.runtimeWriteOwner},...b.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:b.runtimeAttachedClients},...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l,_isCli:!0})}for(const j of h){const x=p.get(j.id),b=qs(j,x);r.push({id:`${n}:acp:${j.id}`,sessionId:j.id,providerSessionId:j.providerSessionId??(x==null?void 0:x.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,agentType:b.providerType,status:b.status||"running",daemonId:n,instanceId:j.id,cliName:b.providerName||b.providerType,mode:"chat",workspace:b.workspace||"",activeChat:b.activeChat,...b.runtimeKey!==void 0&&{runtimeKey:b.runtimeKey},...b.runtimeDisplayName!==void 0&&{runtimeDisplayName:b.runtimeDisplayName},...b.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:b.runtimeWorkspaceLabel},...b.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:b.runtimeWriteOwner},...b.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:b.runtimeAttachedClients},...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l,_isAcp:!0})}return r}const mm=15e3,pm=15e3,hm=6e4,xm=1200,Uo=12,bm=8e3,gm=4e3,Mn=new Map,An=new Map,Sr=new Set,Qs=new Map;function ym(e){if(!e||typeof e!="object")return null;const t=e,r=t.status;if(r&&typeof r=="object")return r;const n=t.result;if(n&&typeof n=="object"&&"status"in n){const a=n.status;if(a&&typeof a=="object")return a}return t}function zo(e,t){const r=Qs.get(e);!r||r.size===0||(Qs.delete(e),r.forEach(n=>n(t)))}function vm(e,t){return new Promise(r=>{const n=Qs.get(e)||new Set;Qs.set(e,n);const a=c=>{clearTimeout(o),n.delete(a),n.size===0&&Qs.delete(e),r(c)},o=setTimeout(()=>a(!1),t);n.add(a)})}function fr(){const{sendCommand:e,sendData:t}=mt(),{injectEntries:r,getIdes:n}=rr();return i.useCallback(async(a,o)=>{if(!a)return;const c=(o==null?void 0:o.minFreshMs)??hm,l=An.get(a)||0;if(!(o!=null&&o.force)&&Sr.has(a)&&l>0||!(o!=null&&o.force)&&l>0&&Date.now()-l<c)return;const d=Mn.get(a);if(d)return d;const f=(async()=>{if(t&&!Sr.has(a)){const h=Ht.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},j=>{const x=n(),b=x.find(A=>A.id===a),v=Zr(j.status,{daemonId:a,existingDaemon:b,existingEntries:x,timestamp:j.timestamp});v.length>0&&r(v),An.set(a,Date.now()),zo(a,!0)});if(h.initialSendAccepted?Sr.add(a):Sr.delete(a),!(o!=null&&o.force)&&h.initialSendAccepted&&await vm(a,xm))return}const u=await e(a,"get_status_metadata"),p=ym(u);if(!p)return;const m=n(),y=m.find(h=>h.id===a),N=Zr(p,{daemonId:a,existingDaemon:y,existingEntries:m,timestamp:p.timestamp||Date.now()});N.length>0&&r(N,{authoritativeDaemonIds:[a]}),An.set(a,Date.now()),zo(a,!0)})().finally(()=>{Mn.delete(a)});return Mn.set(a,f),f},[n,r,e,t])}function ir(e){if(!e||typeof e!="object")return[];const t=String(e.role||"");return[typeof e.providerUnitKey=="string"&&e.providerUnitKey.trim()?`${t}:providerUnitKey:${e.providerUnitKey.trim()}`:"",typeof e.bubbleId=="string"&&e.bubbleId.trim()?`${t}:bubbleId:${e.bubbleId.trim()}`:"",typeof e.id=="string"&&e.id.trim()?`${t}:id:${e.id.trim()}`:"",typeof e._localId=="string"&&e._localId.trim()?`${t}:localId:${e._localId.trim()}`:""].filter(Boolean)}function zt(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}function wm(e,t){if(!e||!t)return!1;if(e===t||e.id&&t.id&&String(e.id)===String(t.id)||e._localId&&t._localId&&String(e._localId)===String(t._localId))return!0;const r=String(e.role||"").toLowerCase(),n=String(t.role||"").toLowerCase();if(r!==n)return!1;const a=Kt(e.content),o=Kt(t.content);if(!a||!o||!(a===o||ya(a,o)||ya(o,a)))return!1;const l=zt(e),d=zt(t);return l&&d?Math.abs(l-d)<=15e3:!!e._localId!=!!t._localId}function ga(e){return Kt(e==null?void 0:e.content)}function ya(e,t){if(!e||!t||e.length<=t.length)return!1;const r=Math.max(12,Math.min(80,Math.floor(e.length*.4)));return t.length<r?!1:e.startsWith(t)||e.includes(t)}function Vo(e){if(!e)return[];const t=[],r=l=>{l&&t.push(l)};e.id&&r(`id:${String(e.id)}`),e._localId&&r(`local:${String(e._localId)}`),e._turnKey&&r(`turn:${String(e._turnKey)}`);const n=String(e.role||"").toLowerCase(),a=ga(e),o=zt(e),c=o?Math.round(o/15e3):0;return n&&a&&(r(`content:${n}:${a}`),r(`preview:${n}:${a.slice(0,120)}:${c}`)),t}function jm(e,t,r=wm){const n=new Map,a=o=>{for(const c of Vo(o)){const l=n.get(c);l?l.push(o):n.set(c,[o])}};return t.forEach(a),e.filter(o=>{const c=ga(o),l=String((o==null?void 0:o.role)||"").toLowerCase(),d=zt(o),f=new Set;for(const p of Vo(o)){const m=n.get(p);m&&m.forEach(y=>f.add(y))}return!(f.size>0?Array.from(f):t).some(p=>{if(r(o,p))return!0;const m=String((p==null?void 0:p.role)||"").toLowerCase();if(!c||!l||l!==m)return!1;const y=ga(p);if(!ya(y,c)&&y!==c)return!1;const N=zt(p);return d&&N?Math.abs(d-N)<=15e3:!0})})}const km=60,Sm=1e3;function Rc(e={}){return e.isCliLike?Sm:km}function Nm(e={}){return Rc(e)}const mr=60,Cm=1e3,Xa=12e4,Tm=new Set(["generating","waiting_approval","starting","streaming","working"]),Go=new Map;function Ja(e,t){return`${e}::${t}`}function va(e=mr){return{liveMessages:[],cursor:_c([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function $r(e){return Vi(e)}function _c(e,t=mr){return{knownMessageCount:e.length,lastMessageSignature:$r(e[e.length-1]),tailLimit:t}}function Nr(e,t){const r=e[e.length-1];if(!r)return"empty:";let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return["",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function qo(e){let t=0;for(const r of e){const n=zt(r);n>t&&(t=n)}return t}function Mm(e,t){if(t.length===0)return!1;if(e.length===0)return!0;const r=qo(e),n=qo(t);return!(r>0&&n<=0||r>0&&n>0&&n<r||r>0&&n===r&&t.length<e.length)}function Am(e,t){if(t.length===0)return e;const r=[...e],n=new Map,a=(o,c)=>{for(const l of ir(o))n.set(l,c)};r.forEach(a);for(const o of t){const l=ir(o).map(d=>n.get(d)).find(d=>d!==void 0);if(l!==void 0){r[l]=o,a(o,l);continue}r.push(o),a(o,r.length-1)}return r}function Im(e,t){const r=Array.isArray(t.messages)?t.messages:[];switch(t.syncMode){case"noop":return e;case"append":return Am(e,r);case"replace_tail":{const n=Math.max(0,Math.min(Number(t.replaceFrom??e.length),e.length));return[...e.slice(0,n),...r]}case"full":return r;default:return r}}class Lm{constructor(t){Ye(this,"manager");Ye(this,"sendData");Ye(this,"daemonId");Ye(this,"sessionId");Ye(this,"historySessionId");Ye(this,"subscriptionKey");Ye(this,"snapshot");Ye(this,"transportSubscription",null);Ye(this,"listeners",new Set);Ye(this,"retainCount",0);Ye(this,"loadHistoryPromise",null);Ye(this,"pendingDisconnectTimer",null);this.manager=t.manager||Ht,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.snapshot=va(Math.max(0,t.tailLimit??mr))}updateOptions(t){if(t.manager&&(this.manager=t.manager),t.sendData&&(this.sendData=t.sendData),t.historySessionId&&(this.historySessionId=t.historySessionId),t.tailLimit!==void 0){const r=Math.max(0,t.tailLimit);if(r!==this.snapshot.cursor.tailLimit){const n=r>this.snapshot.cursor.tailLimit,a=n?0:Math.min(this.snapshot.cursor.knownMessageCount,this.snapshot.liveMessages.length),o=n?"":this.snapshot.cursor.lastMessageSignature;this.snapshot={...this.snapshot,cursor:{knownMessageCount:a,lastMessageSignature:o,tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect())}}}getSnapshot(){return this.snapshot}hydrateLiveMessages(t){const r=Array.isArray(t)?t:[];if(!Mm(this.snapshot.liveMessages,r))return;const n=r,a=_c(n,this.snapshot.cursor.tailLimit);Nr(this.snapshot.liveMessages)===Nr(n)&&this.snapshot.cursor.knownMessageCount===a.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===a.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:n,cursor:a},this.emit())}subscribe(t){return this.listeners.add(t),t(this.snapshot),()=>{this.listeners.delete(t)}}retain(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),!(this.retainCount!==0||this.pendingDisconnectTimer)&&(this.pendingDisconnectTimer=setTimeout(()=>{this.pendingDisconnectTimer=null,this.retainCount===0&&this.disconnect()},0))}async loadHistoryPage(t){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=await t({offset:this.snapshot.historyOffset,excludeRecentCount:this.snapshot.liveMessages.length}),a=Array.isArray(n.messages)?n.messages:[],o=jm(a,this.snapshot.liveMessages);this.snapshot={...this.snapshot,historyMessages:[...o,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+a.length,hasMoreHistory:n.hasMore===!0,historyError:null}}catch(n){this.snapshot={...this.snapshot,historyError:n instanceof Error?n.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=r,r}buildSubscribeRequest(){return{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},knownMessageCount:this.snapshot.cursor.knownMessageCount,lastMessageSignature:this.snapshot.cursor.lastMessageSignature,...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{}}}}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,this.buildSubscribeRequest(),t=>{this.handleUpdate(t)},{retryIntervalMs:Cm}))}disconnect(){var t;(t=this.transportSubscription)==null||t.call(this),this.transportSubscription=null}dispose(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null}emit(){this.listeners.forEach(t=>t(this.snapshot))}handleUpdate(t){if(t.error)return;const r=typeof t.lastMessageSignature=="string"?t.lastMessageSignature:"",n=$r(this.snapshot.liveMessages[this.snapshot.liveMessages.length-1]),a=Array.isArray(t.messages)?t.messages:[];if(t.syncMode!=="full"&&r&&n===r&&a.length===0){const m={knownMessageCount:Math.max(this.snapshot.cursor.knownMessageCount,Number(t.totalMessages||0)),lastMessageSignature:r,tailLimit:this.snapshot.cursor.tailLimit};this.snapshot.cursor.knownMessageCount===m.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===m.lastMessageSignature||(this.snapshot={...this.snapshot,cursor:m},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:m.knownMessageCount,lastMessageSignature:m.lastMessageSignature}));return}const o=Im(this.snapshot.liveMessages,t),c=r||$r(o[o.length-1]),l=!!r&&$r(o[o.length-1])===r,f={knownMessageCount:t.syncMode!=="full"&&l&&Number(t.totalMessages||0)>o.length?Math.max(o.length,Number(t.totalMessages||0)):o.length,lastMessageSignature:c,tailLimit:this.snapshot.cursor.tailLimit};Nr(this.snapshot.liveMessages)===Nr(o)&&this.snapshot.cursor.knownMessageCount===f.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===f.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:o,cursor:f},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:f.knownMessageCount,lastMessageSignature:f.lastMessageSignature}),this.emit())}}function Pc(e){const t=Ja(e.daemonId,e.sessionId),r=Go.get(t);if(r)return r.updateOptions(e),r;const n=new Lm(e);return Go.set(t,n),n}function Rm(e,t){return{...e,loadHistoryPage:t}}function _m(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function Pm(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(Tm.has(r)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const n=t.now??Date.now(),a=Math.max(0,Number(t.recentActivityMs??Xa)),o=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return o>0?n-o<=a:Array.isArray(e.messages)&&e.messages.length>0}function Dm(e=Xa){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Em(e,t={}){const r=new Set,n=[];for(const a of e){if(!Pm(a,t))continue;const o=$s(a),c=a.sessionId||"";if(!o||!c)continue;const l=Ja(o,c);if(r.has(l))continue;r.add(l);const d=ur(a);n.push({daemonId:o,sessionId:c,historySessionId:d||c,subscriptionKey:`daemon:${o}:session:${c}`})}return n.sort(_m),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function $m(e,t){const{sendData:r,sendCommand:n}=mt(),a=(t==null?void 0:t.enabled)!==!1,o=$s(e),c=e.sessionId||"",l=ur(e)||c,d=`daemon:${o}:session:${c}`,f=Math.max(0,(t==null?void 0:t.tailLimit)??mr),u=i.useMemo(()=>!a||!o||!c?null:Pc({daemonId:o,sessionId:c,historySessionId:l,subscriptionKey:d,sendData:r,tailLimit:f}),[o,a,l,r,c,d,f]),[p,m]=i.useState(()=>(u==null?void 0:u.getSnapshot())||va(f));i.useEffect(()=>{if(!u){m(va(f));return}u.retain(),m(u.getSnapshot());const N=u.subscribe(h=>{m(h)});return()=>{N(),u.release()}},[u,f]),i.useEffect(()=>{u&&(u.hydrateLiveMessages(e.messages),m(u.getSnapshot()))},[e.messages,u]);const y=i.useCallback(async()=>{!u||!o||!c||await u.loadHistoryPage(async({offset:N,excludeRecentCount:h})=>{const j=e.agentType,x=await n(o,"chat_history",{agentType:j,offset:N,limit:30,targetSessionId:c,historySessionId:l,excludeRecentCount:h}),b=x&&typeof x=="object"&&"result"in x?x.result||{}:x||{};return{messages:Array.isArray(b.messages)?b.messages:[],hasMore:b.hasMore===!0}})},[e.agentType,u,o,l,n,c]);return i.useMemo(()=>Rm(p,y),[y,p])}function Bm(e,t){const{sendData:r}=mt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??mr),o=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Xa)),c=Dm(o),[l,d]=i.useState(0),[f,u]=i.useState(()=>new Map);i.useEffect(()=>{if(!n||e.length===0)return;const m=setInterval(()=>{d(y=>y+1)},c);return()=>{clearInterval(m)}},[e.length,n,c]);const p=i.useMemo(()=>Em(e,{recentActivityMs:o}),[e,o,l]);return i.useEffect(()=>{if(!n||!r||p.descriptors.length===0){u(j=>j.size===0?j:new Map);return}const m=p.descriptors.map(j=>({key:Ja(j.daemonId,j.sessionId),controller:Pc({...j,sendData:r,tailLimit:a})})),y=new Set(m.map(({key:j})=>j)),N=(j,x)=>{u(b=>{const v=new Map(b);for(const A of v.keys())y.has(A)||v.delete(A);return v.set(j,x),v})},h=m.map(({key:j,controller:x})=>(x.retain(),N(j,x.getSnapshot()),x.subscribe(b=>N(j,b))));return()=>{h.forEach(j=>j()),m.forEach(({controller:j})=>j.release())}},[p.signature,n,r,a]),f}function Yo(e,t){const r=e[e.length-1];if(!r)return`empty:${t||""}`;let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return[t||"",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function en(e){for(let t=e.length-1;t>=0;t-=1){const r=zt(e[t]);if(r>0)return r}return 0}function Km(e){const t=$s(e),r=e.sessionId||"";return t&&r?`${t}::${r}`:""}function Om(e){const t=new Set;for(const r of e)for(const n of ir(r)){if(t.has(n))return!0;t.add(n)}return!1}function Wm(e,t){const r=new Set(ir(e));return r.size===0?!1:ir(t).some(n=>r.has(n))}function Dc(e,t){return t.length===0||e.length<=t.length||!Om(e)?!1:Wm(e[e.length-1],t[t.length-1])}function Fm(e,t){if(t.length===0)return!1;const r=Array.isArray(e.messages)?e.messages:[];if(r.length===0)return!0;const n=en(r),a=en(t);if(n>0&&a===n&&Dc(r,t))return!0;if(n<=0||a<=n)return!1;const o=Yo(r,e.status),c=Yo(t,e.status);return o!==c}function Hm(e,t){const r=t[t.length-1],n=zt(r),a=Kt(r==null?void 0:r.content);return{...e,messages:t,...a?{lastMessagePreview:a}:{},...n>0?{lastMessageAt:n}:{}}}function Um(e,t){const r=Array.isArray(e.messages)?e.messages:[],n=(t==null?void 0:t.liveMessages)||[];if(n.length===0)return r;if(r.length===0)return n;const a=en(r),o=en(n);if(a>0&&(o<=0||a>o))return r;if(a>0&&a===o){if(Dc(r,n))return n;if(r.length>=n.length)return r}return n}function zm(e){const{historyMessages:t,liveMessages:r,visibleLiveCount:n}=e,o=Math.max(0,r.length-n)>0?r.slice(-n):r;return t.length===0?o:[...t,...o]}function Xo(e,t){if(t.size===0||e.length===0)return e;let r=!1;const n=e.map(a=>{var l;const o=Km(a);if(!o)return a;const c=((l=t.get(o))==null?void 0:l.liveMessages)||[];return Fm(a,c)?(r=!0,Hm(a,c)):a});return r?n:e}function Vm(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function Gm(e){return Vm(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}function qm(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function Ym(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function Xm(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function Ec(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function $c(e){const t=typeof e.completionMarker=="string"?e.completionMarker.trim():"";return t||(e.lastMessageHash?e.lastMessageHash:e.lastMessageAt?String(e.lastMessageAt):e.lastUpdated?String(e.lastUpdated):"")}function Jm(e){return Ec(e)?!1:e.inboxBucket==="task_complete"&&$c(e).length>0}function Jo(e){return e.branch||"detached HEAD"}function Qm(e){if(e.error)return`${Jo(e)} · Git error: ${e.error}`;const t=[Jo(e)];return e.changedFiles>0?t.push(qm(e.changedFiles,"file")+" changed"):e.dirty||t.push("clean"),e.ahead>0&&t.push(`ahead ${e.ahead}`),e.behind>0&&t.push(`behind ${e.behind}`),e.hasConflicts&&t.push("conflicts"),t.join(" · ")}function Zm(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${Qm(t)}`}function ep(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function tp(e,t={}){if(t.enabled===!1)return[];if(!Xm(e))return[];const r=Ec(e)?"working":Jm(e)?"complete":null;if(!r)return[];const n=r==="complete"?$c(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${Ym(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:Zm(r,e.git),timestamp:ep(e,e.git),meta:{source:"git-system-bubble",phase:r,workspace:e.workspacePath,repoRoot:e.git.repoRoot,branch:e.git.branch,changedFiles:e.git.changedFiles,hasConflicts:e.git.hasConflicts}}]}const sp=60;function wa({activeConv:e,ideEntry:t,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:o,isFocusingAgent:c,actionLogs:l,userName:d,showMetaChips:f=!1,scrollToBottomRequestNonce:u,isInputActive:p=!0,isVisible:m=!0}){var ge,ee,de,we,ue,xe,se;const y=i.useRef(new Map),N=i.useRef(void 0),h=fr(),{sendCommand:j}=mt(),{isVisible:x}=Oa();dr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const b=kt.useMemo(()=>Ds(e),[e.status,e.connectionState]),v=i.useMemo(()=>Yf(e,t),[e,t]),A=i.useMemo(()=>{var ie;return Ha((ie=v.targetEntry)==null?void 0:ie.providerControls,{hostIdeType:e.hostIdeType,providerType:v.providerType})},[e.hostIdeType,v.providerType,(ge=v.targetEntry)==null?void 0:ge.providerControls]),g=Rc({isCliLike:v.isCli||v.isAcp}),M=Nm({isCliLike:v.isCli||v.isAcp}),T=$m(e,{enabled:m&&!!e.sessionId,tailLimit:M}),[k,w]=i.useState(g),K=e.tabKey,R=T.historyMessages,S=T.hasMoreHistory,O=T.historyError,H=Um(e,T);i.useEffect(()=>{w(g)},[g,K]);const P=Math.max(0,H.length-k),C=Ua(e),I=$s(e),W=Gm(e),E=za(e),$=a||E,z=!!E,[J,he]=i.useState(!1);i.useEffect(()=>{const ie=v.targetEntry;I&&(!ie||ie.providerControls===void 0||ie.controlValues===void 0)&&h(I,{minFreshMs:3e4}).catch(()=>{})},[I,v.isAcp,(ee=v.targetEntry)==null?void 0:ee.providerControls,(de=v.targetEntry)==null?void 0:de.controlValues,h]);const ce=i.useCallback(async()=>{if(!J){if(H.length>k){w(ie=>Math.min(H.length,ie+sp));return}he(!0);try{await T.loadHistoryPage()}finally{he(!1)}}},[T,J,H.length,k]),{allMessages:te,receivedAtMap:ye}=i.useMemo(()=>{const ie=zm({historyMessages:R,liveMessages:H,visibleLiveCount:k}),re=tp(e),q=re.length>0?[...ie,...re]:ie,Y={};return q.forEach((le,ke)=>{const Z=`${e.tabKey}:${qr(le,ke)}`;let Ce=zt(le)||y.current.get(Z)||0;Ce||(Ce=Date.now(),y.current.set(Z,Ce)),Y[qr(le,ke)]=Ce}),{allMessages:q,receivedAtMap:Y}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,P,R,H,k]),fe=i.useMemo(()=>l.filter(ie=>ie.routeId===e.tabKey).sort((ie,re)=>ie.timestamp-re.timestamp),[l,e.tabKey]),be=i.useCallback(async()=>{var ke,Z;if(!I)return;const ie=kc({activeConv:e,visibleMessages:te,actionLogs:l,controls:(ke=v.targetEntry)==null?void 0:ke.providerControls,controlValues:(Z=v.targetEntry)==null?void 0:Z.controlValues,visibleBarControlCount:A.length,chatTailState:{hasMoreHistory:S,historyError:O,historyMessages:R},ui:{controlsVisible:x,visibleLiveCount:k,hiddenLiveCount:P,isInputActive:p,isVisible:m}}),re=await j(I,"get_chat_debug_bundle",{agentType:v.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:ie}),q=Qr(re),Y=Cc(q),le=await Nc(Y);le==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),rt.showToast(Sc(q,{locatorCopyStatus:le}),le==="failed"?"warning":"success")},[e,l,te,x,v.providerType,(we=v.targetEntry)==null?void 0:we.controlValues,(ue=v.targetEntry)==null?void 0:ue.providerControls,I,S,P,R,p,m,O,j,A.length,k]),X=i.useCallback(()=>{const ie=nm(N.current);N.current=ie.state,ie.shouldCollect&&be().catch(re=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",re),rt.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[be]),ae=i.useMemo(()=>{if(H.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[s.jsx("div",{className:"connecting-logo-float",children:s.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),s.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[s.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",s.jsx("span",{className:"connecting-dots"})]}),s.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((b.isGenerating||e.status==="streaming")&&he(!1),e.status==="not_monitored"&&W)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(ar,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),s.jsx("button",{onClick:o,disabled:c,className:"btn btn-primary",children:c?"⌛ Switching...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Cs,{size:14})," Open ",C," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&W)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(Ji,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),s.jsx("button",{onClick:o,disabled:c,className:"btn btn-primary",children:c?"⌛ Opening...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Cs,{size:14})," Open ",C," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Open the agent panel or chat view in the app you are using to start viewing messages"})]});if(e.status==="idle"&&!J)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,W,o,c,J,H.length,C,b.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[f&&s.jsx(Lc,{conversation:e,className:"chat-pane-meta-row"}),s.jsx($u,{messages:te,actionLogs:fe,agentName:Ts(e)||C||"Agent",userName:d,isCliMode:v.isCli||v.isAcp,isWorking:b.isGenerating,contextKey:e.tabKey,receivedAtMap:ye,lastMessageHash:e.lastMessageHash,onLoadMore:ce,isLoadingMore:J,hasMoreHistory:S,hiddenLiveCount:P,loadError:O??void 0,emptyState:ae,scrollToBottomRequestNonce:u,isVisible:m}),s.jsx(Of,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:v.providerType,displayLabel:v.displayLabel,controls:(xe=v.targetEntry)==null?void 0:xe.providerControls,controlValues:(se=v.targetEntry)==null?void 0:se.controlValues,isActive:p,isCliTerminal:v.isCliTerminal}),!v.isCliTerminal&&s.jsx(hc,{contextKey:e.tabKey,panelLabel:C,isSending:n,isBusy:z,statusMessage:$,onSend:r,isActive:p,showControlsToggle:A.length>0,onControlsToggle:X})]})}let Bc=ds;function Kc(){return Bc()}class rp{constructor(){Ye(this,"listeners",new Map)}send(t){}isConnected(){return!1}on(t,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{var n;(n=this.listeners.get(t))==null||n.delete(r)}}emit(t,...r){var n;(n=this.listeners.get(t))==null||n.forEach(a=>a(...r))}}let Oc=new rp;class np{sendPtyInput(t,r,n){return!1}retryConnection(t){}getState(t){return"disconnected"}sendData(t,r){return!1}get(t){}onScreenshot(t,r){return()=>{}}onRuntimeEvent(t,r,n){return()=>{}}requestRuntimeSnapshot(t,r,n){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let ot=new np;function ap(e){e.dashboardWS&&(Oc=e.dashboardWS),e.connectionManager&&(ot=e.connectionManager),e.useDaemonsHook&&(Bc=e.useDaemonsHook)}const op=.5,ip=1.25;function it(e){return Ua(e)}function As(e){return vc(e).join(" · ")}function Wc(e){const t=yc(e);return t||(e.title?e.title:As(e)||"No messages yet")}function Fc(e,t){const{isReconnecting:r,isConnecting:n}=Ds(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function cp(e,t){const r=["Chat",...vc(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function rs(e){return Fc(e)||As(e)}function lp(e){return`${it(e)} · ${Wc(e)}`}function dp(e){const t=Jr(e),r=t?at(t):Ts(e);return`${it(e)} — ${r||"Agent"}`}function up(e){return Ts(e)||"CLI"}function Hc(e){return gc(e)}function Uc(e){return e?`Remote · ${it(e)||e.workspaceName||"Session"}`:"Remote"}function fp({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:c=!0,isInputActive:l=!0}){var G;ds();const{sendPtyInput:d}=mt(),[f,u]=i.useState(!1),p=i.useRef(!1);p.current=f;const[m,y]=i.useState("Runtime terminal unavailable"),[N,h]=i.useState(!1),[j,x]=i.useState(null),[b,v]=i.useState(!1),[A,g]=i.useState(!1),[M,T]=i.useState(1),[k,w]=i.useState(!1),[K,R]=i.useState({width:0,height:0}),[S,O]=i.useState({width:0,height:0}),[H,P]=i.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[C,I]=i.useState(null),W=i.useRef(null),E=i.useRef(null),$=i.useRef(!1),z=i.useRef(!1),J=i.useRef(c),he=i.useRef(0),ce=i.useRef(!1),te=i.useRef(""),ye=i.useRef(null),fe=i.useRef(!1),be=i.useRef(!1),X=i.useRef(null),ae=i.useRef(null),ge=i.useRef(null),ee=32*1024,de=()=>{var _,U,Q,ne;return((U=(_=W.current)==null?void 0:_.ownerDocument)==null?void 0:U.defaultView)||((ne=(Q=E.current)==null?void 0:Q.ownerDocument)==null?void 0:ne.defaultView)||window},we=_=>{const U=de();return{ownerWindow:U,frameId:U.requestAnimationFrame(_)}},ue=()=>{const _=X.current;if(_){try{_.ownerWindow.cancelAnimationFrame(_.frameId)}catch{}X.current=null}},xe=()=>{const _=ae.current;if(_){try{_.ownerWindow.clearTimeout(_.timeoutId)}catch{}ae.current=null}},se=()=>{const _=ge.current;if(_){try{_.ownerWindow.clearTimeout(_.timeoutId)}catch{}ge.current=null}},ie=()=>{c&&X.current===null&&(X.current=we(()=>{Qe()}))},re=e.tabKey,q=e.sessionId||"",Y=e.daemonId||((G=e.routeId)==null?void 0:G.split(":")[0])||e.routeId||"",le=za(e),ke=f?o||le:m,Z=op,Ce=ip,Ee=.05,We=()=>{const _=S.width,U=S.height;if(!Number.isFinite(K.width)||K.width<=0||!Number.isFinite(K.height)||K.height<=0||!Number.isFinite(_)||_<=0||!Number.isFinite(U)||U<=0)return 1;const Q=K.width/_,ne=K.height/U;return Number(Math.min(Ce,Math.max(Z,Math.min(Q,ne))).toFixed(2))},Fe=We(),D=$.current&&M>Fe,Se=Number.isFinite(S.width)&&S.width>0?Math.max(K.width,Math.round(S.width*M)):K.width,Ae=Number.isFinite(S.height)&&S.height>0?Math.max(K.height,Math.round(S.height*M)):K.height,Le=()=>{we(()=>{const _=E.current;_&&(_.scrollLeft=0,_.scrollTop=_.scrollHeight-_.clientHeight)})},Pe=()=>{var _,U;he.current=0,ce.current=!1,te.current="",ye.current=null,fe.current=!1,be.current=!1,$.current||(z.current=!1,T(1)),X.current!==null&&ue(),u(!1),y("Runtime terminal unavailable"),se(),xe(),x(null),I(null),w(!1),h(!1),v(!1),g(!1),(U=(_=r.current)==null?void 0:_.reset)==null||U.call(_)},He=()=>{var _,U;he.current=0,ce.current=!1,te.current="",ye.current=null,fe.current=!1,be.current=!1,X.current!==null&&ue(),u(!0),y(""),se(),xe(),x(null),I(null),w(!1),h(!1),v(!1),g(!1),(U=(_=r.current)==null?void 0:_.reset)==null||U.call(_)},Ue=()=>{be.current&&(be.current=!1,we(()=>{var _,U;(U=(_=r.current)==null?void 0:_.scrollToTop)==null||U.call(_)}))},Qe=()=>{if(X.current=null,!c)return;const _=te.current;if(!_)return;const U=_.slice(0,ee);te.current=_.slice(U.length);const Q=r.current;if(!Q){te.current=U+te.current,ie();return}Q.write(U,()=>{if(te.current.length>0){ie();return}Ue()})},lt=_=>{_&&(te.current+=_,ie())},dt=(_,U=0,Q,ne,ve={})=>{var _e,Ne,De,Be;const Me=!!ve.force;!Me&&U>0&&he.current>=U||!Me&&U===0&&ce.current||(he.current=U,U>0&&v(!0),u(!0),y(""),typeof Q=="number"&&typeof ne=="number"&&Q>0&&ne>0&&((Ne=(_e=r.current)==null?void 0:_e.resize)==null||Ne.call(_e,Q,ne)),te.current="",(Be=(De=r.current)==null?void 0:De.reset)==null||Be.call(De),_?lt(_):Ue())};i.useEffect(()=>{Pe()},[q]),i.useEffect(()=>{var U;if(!q)return;const _=((U=ot.onRuntimeEvent)==null?void 0:U.call(ot,q,Q=>{if(!(!Q||Q.sessionId!==q)){if(Q.type==="runtime_snapshot"){if(!c){ye.current={text:Q.text||"",seq:Q.seq||0,cols:Q.cols,rows:Q.rows,force:!!Q.force};return}dt(Q.text||"",Q.seq||0,Q.cols,Q.rows,{force:!!Q.force});return}if(Q.type==="session_output"){ce.current=!0,typeof Q.seq=="number"&&(he.current=Math.max(he.current,Q.seq),Q.seq>0&&v(!0)),p.current||u(!0),p.current||y(""),typeof Q.data=="string"&<(Q.data);return}if(Q.type==="session_cleared"){if(!c){fe.current=!0,te.current="",ye.current=null;return}He();return}if(Q.type==="session_io_error"){const ne=typeof Q.error=="string"&&Q.error?Q.error:typeof Q.reason=="string"&&Q.reason?Q.reason:"unknown error";u(!1),y(`Runtime input failed: ${ne}`);return}}},Y))||(()=>{});return()=>{_()}},[Y,q,r,c]);const ut=async(_={})=>{var U;if(!Y||!q)return{success:!1,error:"daemonId and sessionId are required"};_.preserveStatus||y(_.loadingMessage||"Loading runtime terminal...");try{const Q=await((U=ot.requestRuntimeSnapshot)==null?void 0:U.call(ot,Y,q,{sinceSeq:_.sinceSeq,force:_.force}));return Q&&Q.success===!1?(_.preserveStatus||(u(!1),y(`Runtime terminal unavailable: ${Q.error}`)),Q):Q||{success:!0}}catch(Q){const ne=(Q==null?void 0:Q.message)||String(Q);return _.preserveStatus||(u(!1),y(`Runtime terminal unavailable: ${ne}`)),{success:!1,error:ne}}},Te=async _=>{var Me,_e;const U=((Me=W.current)==null?void 0:Me.ownerDocument)||document,Q=U.defaultView||window,ne=(_e=Q.navigator)==null?void 0:_e.clipboard;if(ne!=null&&ne.writeText&&Q.isSecureContext)try{return await ne.writeText(_),!0}catch{}let ve=null;try{return ve=U.createElement("textarea"),ve.value=_,ve.setAttribute("readonly","true"),ve.style.position="fixed",ve.style.left="-9999px",ve.style.top="0",U.body.appendChild(ve),ve.focus(),ve.select(),U.execCommand("copy")}catch{return!1}finally{ve==null||ve.remove()}},Ge=_=>{xe(),I(_);const U=de();ae.current={ownerWindow:U,timeoutId:U.setTimeout(()=>{ae.current=null,I(Q=>Q===_?null:Q)},2200)}},Ze=_=>{se(),x(_);const U=de();ge.current={ownerWindow:U,timeoutId:U.setTimeout(()=>{ge.current=null,x(Q=>Q===_?null:Q)},2200)}},qe=async()=>{var ve,Me,_e,Ne;const _=((Me=(ve=r.current)==null?void 0:ve.getSelection)==null?void 0:Me.call(ve))||"",U=((Ne=(_e=r.current)==null?void 0:_e.getVisibleText)==null?void 0:Ne.call(_e))||"",Q=_.trimEnd()||U.trimEnd();if(!Q){Ge("Nothing to copy");return}if(!await Te(Q)){Ge("Copy failed");return}Ge(_.trimEnd()?"Copied selection":"Copied visible terminal")},tt=_=>{if(!f||!c)return;((d==null?void 0:d(Y,q,_))??!1)||Ge("Terminal input failed")},F=async()=>{if(N)return;h(!0),x("Loading older terminal output..."),be.current=!0;const _=await ut({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:f});if(h(!1),(_==null?void 0:_.success)===!1){be.current=!1,x(`Older terminal output unavailable: ${_.error}`);return}g(!0),Ze("Older terminal output loaded"),we(()=>{var U;(U=r.current)==null||U.bumpResize()})};i.useEffect(()=>{var U,Q;if(!q)return;Y&&((U=ot.getState)==null?void 0:U.call(ot,Y))==="connected"&&ut();const _=(Q=ot.onStateChange)==null?void 0:Q.call(ot,(ne,ve)=>{ne!==Y||ve!=="connected"||ut()});return()=>{_==null||_()}},[Y,q,r]),i.useEffect(()=>{t&&Pe()},[t,re,r]),i.useEffect(()=>{var ne,ve;const _=W.current,U=(ve=(ne=_==null?void 0:_.ownerDocument)==null?void 0:ne.defaultView)==null?void 0:ve.ResizeObserver;if(!_||!U)return;const Q=new U(Me=>{const _e=Me[0];if(!_e)return;const{width:Ne,height:De}=_e.contentRect;R(Be=>{const Re=Math.round(Ne),ze=Math.round(De);return Be.width===Re&&Be.height===ze?Be:{width:Re,height:ze}})});return Q.observe(_),()=>Q.disconnect()},[]),i.useEffect(()=>{if($.current)return;const _=We();!Number.isFinite(_)||_<=0||T(U=>z.current?_<U-Ee?_:U:(z.current=!0,_))},[S.height,S.width,K.height,K.width]),i.useEffect(()=>{D&&Le()},[D,Ae,Se]),i.useEffect(()=>{var Q;const _=J.current;if(J.current=c,!c)return;_||g(!1),fe.current&&(fe.current=!1,He());const U=ye.current;U&&(ye.current=null,dt(U.text,U.seq,U.cols,U.rows,{force:!!U.force})),Y&&q&&((Q=ot.getState)==null?void 0:Q.call(ot,Y))==="connected"&&ut(),te.current&&X.current===null&&ie(),we(()=>{var ne;(ne=r.current)==null||ne.bumpResize()})},[Y,c,q]),i.useEffect(()=>()=>{X.current!==null&&ue(),xe(),se()},[]),i.useEffect(()=>{const _=ne=>{var Me;const ve=ne.detail;ve!=null&&ve.sessionId&&ve.sessionId!==q||f&&((Me=r.current)==null||Me.bumpResize())},U=de(),Q=U===window?[window]:[window,U];for(const ne of Q)ne.addEventListener("adhdev:fit-cli-terminal",_);return()=>{for(const ne of Q)ne.removeEventListener("adhdev:fit-cli-terminal",_)}},[f,q,r]);const L=f&&b&&!A&&(H.atTop||!H.canScroll)||N||!!j;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:W,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[L&&s.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-medium text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{F()},disabled:!q||N,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:N?"Loading older...":"Load older terminal output"}),j&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:j})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[C&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:C}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{qe()},disabled:!f,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:"Copy"}),s.jsxs("div",{className:"relative",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>w(_=>!_),disabled:!f,"aria-label":"Open terminal control keys","aria-expanded":k,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),k&&s.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":"Terminal control keys",className:"absolute right-0 top-10 w-56 rounded-2xl border border-white/10 bg-[#0b0d12]/95 p-3 text-white/85 shadow-2xl shadow-black/40 backdrop-blur-md",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),s.jsx("button",{type:"button",className:"rounded-full px-2 py-0.5 text-[11px] text-white/55 transition-colors hover:bg-white/10 hover:text-white/85",onClick:()=>w(!1),"aria-label":"Close terminal control keys",children:"×"})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt("\x1B"),children:"Esc"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt(" "),children:"Tab"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt("\r"),children:"Enter"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt("\x1B[A"),"aria-label":"Arrow up",children:"↑"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt("\x1B[D"),"aria-label":"Arrow left",children:"←"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt("\x1B[B"),"aria-label":"Arrow down",children:"↓"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt("\x1B[C"),"aria-label":"Arrow right",children:"→"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt(""),children:"Ctrl-C"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt(""),children:"Ctrl-D"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt(""),children:"Bksp"})]})]})]}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{$.current=!0,T(_=>{const U=Math.max(Fe,Number((_-.1).toFixed(2)));return U>Fe&&Le(),U})},title:"Shrink terminal viewport",children:"-"}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{$.current=!0,T(_=>{const U=Math.min(Ce,Number((_+.1).toFixed(2)));return U>Fe&&Le(),U})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:E,className:D?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:s.jsx("div",{style:{width:Se>0?`${Se}px`:"100%",height:Ae>0?`${Ae}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:S.width>0?`${S.width}px`:"100%",height:S.height>0?`${S.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:M},children:s.jsx(nc,{ref:r,readOnly:!f||!c,sizingMode:"measured",onViewportMetrics:O,onScrollMetrics:P,onInput:_=>{!f||(d==null||d(Y,q,_))}})})})}),!f&&s.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:m})]}),s.jsx(hc,{contextKey:e.tabKey,panelLabel:it(e),isSending:a,isBusy:!!le,statusMessage:ke,onSend:async _=>le?!1:n(_),isActive:l&&c,showControlsToggle:!1,animateVisibility:!1})]})}const mp=5e3,pp=12e3;function hp(e){return e==="disconnected"||e==="reconnecting"}function xp({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=mp,reconnectActionDelayMs:o=pp}){const c=hp(e),[l,d]=i.useState(()=>!c||a<=0),[f,u]=i.useState(()=>!c||o<=0),p=i.useRef(!1);i.useEffect(()=>{if(!c){d(!1);return}if(p.current=!1,a<=0){p.current=!0,d(!0);return}d(!1);const g=setTimeout(()=>{p.current=!0,d(!0)},a);return()=>clearTimeout(g)},[a,c]),i.useEffect(()=>{if(!c){u(!1);return}if(o<=0){u(!0);return}u(!1);const g=setTimeout(()=>{u(!0)},o);return()=>clearTimeout(g)},[o,c]);const m=c?l:e==="offline"||e==="auth_failed",y=!!(n&&e!=="auth_failed"&&(!c||f)),N=i.useMemo(()=>!t||e!=="connected"?!1:a<=0||p.current,[a,t,e]),h=e==="auth_failed"?"red":e==="offline"?"orange":"accent",j={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))"},x={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)"},b={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},v="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",A={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[m&&s.jsx("div",{className:v,style:A,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-3 py-2.5 sm:px-4 sm:py-3 text-[13px] font-semibold flex flex-wrap items-center gap-x-2.5 gap-y-2 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:j[h],border:x[h],color:b[h]},children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),s.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&"Network offline",e==="disconnected"&&"Reconnecting",e==="reconnecting"&&"Reconnecting",e==="auth_failed"&&(r?s.jsxs(s.Fragment,{children:["Session expired."," ",s.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — refresh the page or try again shortly.")]}),y&&s.jsx("button",{type:"button",className:"basis-full sm:basis-auto mx-auto sm:mx-0 sm:ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>n==null?void 0:n(),disabled:e==="offline",children:"Reconnect now"})]})}),N&&s.jsx("div",{className:v,style:A,children:s.jsxs("div",{className:"pointer-events-none rounded-2xl border px-4 py-2 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-green-500/15 shadow-[0_18px_40px_rgba(2,6,23,0.2)] backdrop-blur-xl animate-[fadeIn_0.3s_ease]",children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})})]})}function bp({terminalBackend:e,isStandalone:t=!1,machineLabel:r,machineKey:n}){const a=i.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[o,c]=i.useState(!1);if(i.useEffect(()=>{if(!a){c(!1);return}try{c(localStorage.getItem(a)==="1")}catch{c(!1)}},[a]),!t||!e||e.backend!=="xterm"||o)return null;const l=(r==null?void 0:r.trim())||"This machine",d=()=>{if(a)try{localStorage.setItem(a,"1")}catch{}c(!0)};return s.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5",style:{background:"linear-gradient(90deg, rgba(245,158,11,0.12), rgba(245,158,11,0.04))",borderBottom:"1px solid rgba(245,158,11,0.2)",color:"#d97706"},children:[s.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[s.jsxs("span",{children:[l," is using `xterm` fallback."]}),s.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),s.jsx("button",{type:"button",onClick:d,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 Qa({mode:e,onChange:t,compact:r=!1}){const n=r?14:15;return s.jsx("button",{type:"button",onClick:()=>t(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:e==="chat"?"Switch to Terminal view":"Switch to Chat view",children:e==="chat"?s.jsx(Ea,{size:n}):s.jsx(Ut,{size:n})})}const Et="New session",zc="A connected machine is ready. Start a new session to begin chatting, or open a workspace to launch an IDE, CLI, or ACP session.";function gp(e){if(!e||e.isGitRepo===!1||e.reason==="not_git_repo")return null;if(e.hasConflicts)return`${e.branch||"Git"} · conflicts${e.changedFiles>0?` ${e.changedFiles}`:""}`;const t=[e.branch||"Git"];return e.changedFiles>0&&t.push(`±${e.changedFiles}`),e.ahead>0&&t.push(`↑${e.ahead}`),e.behind>0&&t.push(`↓${e.behind}`),t.length===1&&e.dirty&&t.push("dirty"),t.join(" ")}function yp(e){return!e||e.isGitRepo===!1||e.reason==="not_git_repo"?null:e.hasConflicts?"conflict":e.error?"error":e.dirty||e.changedFiles>0||e.ahead>0||e.behind>0?"dirty":"quiet"}function vp(e){switch(e){case"conflict":return"border-red-500/25 bg-red-500/[0.08] text-red-400";case"error":return"border-yellow-500/25 bg-yellow-500/[0.08] text-yellow-500";case"dirty":return"border-orange-500/25 bg-orange-500/[0.08] text-orange-400";case"quiet":default:return"border-emerald-500/15 bg-emerald-500/[0.06] text-emerald-500"}}function Is({git:e,className:t="",compact:r=!1}){const n=gp(e),a=yp(e);if(!n||!a)return null;const o=[e!=null&&e.branch?`Branch: ${e.branch}`:null,e!=null&&e.changedFiles?`Changed files: ${e.changedFiles}`:null,e!=null&&e.ahead?`Ahead: ${e.ahead}`:null,e!=null&&e.behind?`Behind: ${e.behind}`:null,e!=null&&e.hasConflicts?"Conflicts detected":null,e!=null&&e.error?`Git error: ${e.error}`:null].filter(Boolean);return s.jsxs("span",{className:`inline-flex min-w-0 max-w-[12rem] items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none ${vp(a)} ${t}`.trim(),title:o.join(" · ")||n,"data-git-tone":a,children:[s.jsx("span",{"aria-hidden":"true",children:"⑂"}),s.jsx("span",{className:"truncate",children:n})]})}function wp({wsStatus:e,isConnected:t,daemonCount:r,p2pStates:n={}}){if(e!=="connected")return{tone:"disconnected",title:"Disconnected",subtitle:null};const a=Object.values(n),o=a.filter(l=>l==="connected").length,c=a.filter(l=>l==="connecting"||l==="new"||l==="checking").length;return r>0&&c>0&&o===0?{tone:"limited",title:"Connected to dashboard",subtitle:"Connecting to machine..."}:t?{tone:"connected",title:"Connected",subtitle:null}:{tone:"limited",title:"Connected to dashboard",subtitle:null}}function Qo({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Zo({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:o}){const c=ln(e.updatedAt),l=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${l?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",c].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[l?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),n()},children:"Mark read"}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),a()},children:"Mark unread"}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),o()},children:"Delete"})]})]})}function jp({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:o,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:d,onHideConversation:f,hiddenConversations:u=[],onShowConversation:p,onShowAllHidden:m,onResetPanelsToMain:y,inboxOpen:N,onInboxOpenChange:h,hiddenOpen:j,onHiddenOpenChange:x,onOpenNewSession:b,onOpenDashboardGuide:v,guideNudgeVisible:A=!1,actionShortcuts:g,notifications:M,notificationUnreadCount:T,onOpenNotification:k,onMarkNotificationRead:w,onMarkNotificationUnread:K,onDeleteNotification:R,onOpenGitDialog:S}){const{ides:O,p2pStates:H={}}=ds(),P=!!e&&et(e)&&!Xe(e),C=!!e&&Xe(e),I=l||(e?xc(e)?"terminal":"chat":null),[W,E]=i.useState(!1),$=i.useRef(null),z=i.useRef(null),J=O.filter(ee=>ee.type==="adhdev-daemon"),he=wp({wsStatus:t,isConnected:r,daemonCount:J.length,p2pStates:H}),ce=he.subtitle,te=he.tone==="connected"?"#22c55e":he.tone==="limited"?"#eab308":"#ef4444",ye=he.tone==="connected"?"0 0 4px #22c55e80":he.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",fe=i.useMemo(()=>M.filter(ee=>!ee.readAt),[M]),be=i.useMemo(()=>M.filter(ee=>!!ee.readAt),[M]),X=i.useMemo(()=>fe.slice(0,9),[fe]),ae=T;i.useEffect(()=>{if(!N)return;const ee=de=>{var we;(we=$.current)!=null&&we.contains(de.target)||h(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[N,h]),i.useEffect(()=>{if(!j)return;const ee=de=>{var we;(we=z.current)!=null&&we.contains(de.target)||x(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[j,x]),i.useEffect(()=>{if(!j&&!N)return;const ee=de=>{if(!de.altKey)return;const we=de.code.match(/^Digit([1-9])$/);if(!we)return;const ue=Number(we[1])-1,xe=j?u[ue]:void 0,se=N?X[ue]:void 0;if(!(!xe&&!se)){if(de.preventDefault(),de.stopPropagation(),xe){p==null||p(xe),x(!1);return}se&&(k(se),h(!1))}};return window.addEventListener("keydown",ee,!0),()=>window.removeEventListener("keydown",ee,!0)},[u,j,N,X,x,h,k,p]);const ge=ee=>{if(!ee)return;const de=n.find(we=>we.tabKey===ee);de&&(f==null||f(de))};return s.jsxs("div",{className:"dashboard-header",children:[s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("div",{className:"header-title-block",children:s.jsxs("div",{className:"header-title-row",children:[s.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[s.jsx(Ut,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?it(e):"Dashboard"}),s.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:s.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:te,boxShadow:ye}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[s.jsx("span",{title:he.title,className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:te,boxShadow:ye}}),ce&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",ce]}),b&&s.jsx("button",{type:"button",onClick:b,className:"btn btn-secondary btn-sm ml-2",title:`${Et}${g!=null&&g.openNewSession?` (${g.openNewSession})`:""}`,"aria-label":Et,children:s.jsx(Zi,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[v&&s.jsxs("button",{type:"button",onClick:v,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:"Dashboard guide","aria-label":"Open dashboard guide",children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),A&&s.jsx("span",{children:"Guide"})]}),e&&(P||C||!Xe(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:As(e)||it(e),children:it(e)}),S&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:()=>S(e.daemonId,e.workspacePath),children:s.jsx(Is,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(Is,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(P||C)&&c&&s.jsxs(s.Fragment,{children:[P&&d&&I&&s.jsx(Qa,{mode:I,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>c(e),className:"btn btn-secondary btn-sm",title:C?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(St,{size:14})})]}),!Xe(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(Pa,{size:14})}),!P&&!Xe(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(Tt,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:$,children:[s.jsxs("div",{className:`dashboard-header-hidden${W?" is-drop-target":""}`,ref:z,onDragEnter:ee=>{ee.dataTransfer.types.includes("text/tab-key")&&(ee.preventDefault(),E(!0))},onDragOver:ee=>{ee.dataTransfer.types.includes("text/tab-key")&&(ee.preventDefault(),ee.dataTransfer.dropEffect="move",E(!0))},onDragLeave:ee=>{ee.currentTarget.contains(ee.relatedTarget)||E(!1)},onDrop:ee=>{const de=ee.dataTransfer.getData("text/tab-key");ee.preventDefault(),E(!1),ge(de)},children:[s.jsxs("button",{type:"button",onClick:()=>x(!j),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${g!=null&&g.toggleHiddenTabs?` (${g.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[s.jsx(Da,{size:16}),u.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:u.length})]}),j&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),s.jsx(Qo,{value:g==null?void 0:g.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[y&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:y,children:"Reset panels"}),u.length>0&&m&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{m(),x(!1)},children:"Restore all"})]})]}),e&&f&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>f(e),children:[s.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[s.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),s.jsx(Qo,{value:g==null?void 0:g.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:it(e)})]}),u.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(ee=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{p==null||p(ee),x(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:it(ee)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(ee)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(ee)+1]}):null,As(ee)]})]},ee.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>h(!N),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(cn,{size:16}),ae>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:ae})]}),N&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[fe.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),fe.map(ee=>s.jsx(Zo,{notification:ee,shortcutIndex:X.indexOf(ee)>=0?X.indexOf(ee)+1:void 0,onOpen:()=>k(ee),onMarkRead:()=>w(ee.id),onMarkUnread:()=>K(ee.id),onDelete:()=>R(ee.id)},ee.id))]}),be.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),be.map(ee=>s.jsx(Zo,{notification:ee,onOpen:()=>k(ee),onMarkRead:()=>w(ee.id),onMarkUnread:()=>K(ee.id),onDelete:()=>R(ee.id)},ee.id))]}),M.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function xt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function kp(e,t){return String(e||"")!==String(t||"")}function Sp(e,t={}){const r=String(t.textQuery||"").trim().toLowerCase(),n=String(t.workspaceQuery||"").trim().toLowerCase(),a=String(t.modelQuery||"").trim().toLowerCase(),o=!!t.resumableOnly;return!r&&!n&&!a&&!o?e:e.filter(c=>!(o&&!c.canResume||r&&![c.title,c.preview].map(d=>String(d||"").toLowerCase()).join(`
|
|
39
39
|
`).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!dc(c.summaryMetadata).map(d=>d.toLowerCase()).join(`
|
|
40
|
-
`).includes(a)))}function Np(e,t="recent"){const r=e.slice();return r.sort((n,a)=>{if(t==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(t==="messages"){const o=(Number(a.messageCount)||0)-(Number(n.messageCount)||0);if(o!==0)return o}return(Number(a.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function Vc(e,t={}){return Np(Sp(e,t),t.sortMode||"recent")}function tn(e){return e?"Resume saved history":"Start fresh"}function Za(e){return e?"Resuming saved history…":"Starting fresh…"}function Cp(){return"Start fresh"}function Gc(e,t=!1){return e==="cli"?tn(t):e==="ide"?"Start IDE":"Start ACP session"}function qc(e,t=!1){return e==="cli"?Za(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Tp(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Mp(){return"Open saved history"}function Ap(){return"Saved History"}function eo(){return"Use saved history when you want continuity in the same provider conversation."}function Ip(){return"No saved history found yet."}function Lp(){return"Refresh saved history"}function Rp(){return"Refreshing saved history…"}function ns(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function as(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 Ls(e){return e==="start-fresh"?"Start fresh":"Restart"}function Rs(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function to(e){return`Resume saved history with ${e}?`}function so(){return"Review or change the target workspace before resuming saved history."}function _p(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 ro({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:f,onClose:u,onNewChat:p,onSwitchSession:m,onRefreshHistory:y,onResumeSavedSession:N}){var R;const h=t.find(S=>S.id===e.routeId),j=(h==null?void 0:h.chats)||[],x=(R=h==null?void 0:h.activeChat)==null?void 0:R.id,b=et(e)&&!Xe(e),[v,A]=i.useState(()=>xt()),g=l||v,M=String(d||"").trim(),T=S=>{if(f){f(S);return}A(S)},k=i.useMemo(()=>a.map(S=>{const O=String(S.workspace||"").trim();return S.canResume||O||!M?S:{...S,workspace:M,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[M,a]),w=i.useMemo(()=>Vc(k,{textQuery:g.textQuery,workspaceQuery:g.workspaceQuery,modelQuery:g.modelQuery,resumableOnly:g.resumableOnly,sortMode:g.sortMode}),[k,g.modelQuery,g.resumableOnly,g.sortMode,g.textQuery,g.workspaceQuery]),K=s.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:u,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:b?Ap():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:dp(e)}),b&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:eo()})]}),s.jsx("button",{onClick:u,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(St,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!b&&s.jsx("button",{onClick:p,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"}),b?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:g.textQuery,onChange:S=>T({...g,textQuery:S.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:g.workspaceQuery,onChange:S=>T({...g,workspaceQuery:S.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:g.modelQuery,onChange:S=>T({...g,modelQuery:S.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:g.sortMode,onChange:S=>T({...g,sortMode:S.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:g.resumableOnly,onChange:S=>T({...g,resumableOnly:S.target.checked})}),"Resume-ready only"]})]}),w.map(S=>{const O=e.providerSessionId===S.providerSessionId,H=O||!S.canResume||!!c,P=S.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{H||!N||N(S)},disabled:H,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${O?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${H?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${O?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:S.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:S.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:_p(S.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:S.preview||"No saved preview yet"}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[S.workspace||"Workspace unknown",P?" · selected workspace":"",fs(S.summaryMetadata)?` · ${fs(S.summaryMetadata)}`:"",S.messageCount>0?` · ${S.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:O?"ACTIVE":S.canResume?P?"RESUME IN SELECTED WORKSPACE":c===S.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},S.id)})]}):j.map(S=>s.jsxs("div",{onClick:()=>{m(e.routeId,S.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${x===S.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${x===S.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:S.title||"Untitled Session"}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[S.id.substring(0,12),"..."]}),x===S.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},S.id)),(b&&!o&&w.length===0||!b&&j.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(du,{size:32})}),s.jsx("div",{className:"text-[13px]",children:b?a.length>0?"No saved history matches these filters.":Ip():"No recent chat sessions found."})]}),b&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:Rp()})})]}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:s.jsx("button",{onClick:y,disabled:n||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||o?"⌛ Refreshing...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(lr,{size:13})," ",b?Lp():"Refresh History"]})})})]})]});return typeof document>"u"?K:sr.createPortal(K,document.body)}const ei={success:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Done"},warning:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Attention"},info:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Update"}};function Yc({toasts:e,onDismiss:t,onClickToast:r}){return s.jsx("div",{className:"fixed right-4 z-[9999] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(n=>{const a=ei[n.type]||ei.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var o;(o=n.actions)!=null&&o.length||r&&r(n)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${a.accent}, color-mix(in srgb, ${a.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:o=>{o.stopPropagation(),t(n.id)},"aria-label":"Dismiss",children:s.jsx(St,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:a.chipBg,color:a.chipText,border:`1px solid color-mix(in srgb, ${a.accent} 22%, transparent)`},children:a.label})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((o,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${o.variant==="primary"||o.variant==="danger",""}`,style:o.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)"}:o.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(),o.onClick(),t(n.id)},children:o.label},c))})]})]},n.id)})})}const Pp=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Dp(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function Ep(e){return e.sessionId||e.instanceId||e.agentType}function In(e,t){return e||t}function Xc(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Ct(r,{fallbackId:r.id}));return t}function Jc(e,t={}){var n,a;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((a=t.machineNames)==null?void 0:a[e.daemonId])||void 0,connectionState:t.connectionStates?t.connectionStates[r]||t.defaultConnectionState||"new":t.defaultConnectionState}}function no(e,t={}){return $p(e,Jc(e,t))}function $p(e,t={}){var p,m,y,N,h,j;const r=[],n=t.machineName,a=t.connectionState,o=Dp(e),c=e.workspace||"",l=nf(e.type,{agentName:e.cliName}),d=et(e)||Xe(e)?l:at(e.type),f=Array.isArray(e.childSessions)?e.childSessions.map(x=>{var b,v;return{sessionId:x.id,instanceId:x.id,providerSessionId:x.providerSessionId,transport:x.transport,sessionCapabilities:x.capabilities,agentType:x.providerType,agentName:x.providerName||at(x.providerType),status:x.status,title:x.title,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,messages:((b=x.activeChat)==null?void 0:b.messages)||[],activeModal:((v=x.activeChat)==null?void 0:v.activeModal)||void 0,unread:x.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,surfaceHidden:x.surfaceHidden,git:x.git}}):[],u=Pp(e);if(u){const x=e.sessionId||e.instanceId,b=l,v=(p=e.activeChat)==null?void 0:p.activeModal,A=v&&Array.isArray(v.buttons)&&v.buttons.length>0,g=yt((m=e.activeChat)==null?void 0:m.status,{activeModal:(y=e.activeChat)==null?void 0:y.activeModal})||yt((h=(N=e.agents)==null?void 0:N[0])==null?void 0:h.status)||"idle",M=e.activeChat||{title:"",messages:[]};let T=M.title&&String(M.title).trim()?String(M.title).trim():"";const k=(j=e.activeChat)==null?void 0:j.id,w=e.chats;if(k&&Array.isArray(w)&&w.length>0){const O=w.find(H=>H.id===k||H.id&&String(H.id)===String(k));O!=null&&O.title&&String(O.title).trim()&&(T=String(O.title).trim())}const K=(et(e)||Xe(e),e.type),R=(et(e)||Xe(e))&&Eo(T,b,K)?"":T,S=M.messages||[];r.push({routeId:e.id,sessionId:x,providerSessionId:e.providerSessionId,nativeSessionId:x,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:et(e)?e.mode||"terminal":"chat",agentName:b,agentType:K,status:g,title:R,messages:S,resume:e.resume,hostIdeType:!et(e)&&!Xe(e)?e.type:void 0,workspaceName:o,workspacePath:c,git:e.git,displayPrimary:R||o||(et(e)?e.mode==="chat"?b:"Terminal":b),displaySecondary:d,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:A?v.buttons:void 0,modalMessage:A?v.message:void 0,streamSource:"native",tabKey:In(x,e.id),machineName:n,connectionState:a})}if(u&&(et(e)||Xe(e)))return r;for(const x of f){const b=x.activeModal&&Array.isArray(x.activeModal.buttons)&&x.activeModal.buttons.length>0,v=af(x),A=Ep(x),g=`${e.id}:${A}`,M=x.title&&String(x.title).trim()||"",T=Eo(M,x.agentName,x.agentType)?"":M,k=x.messages||[];(x.transport==="cdp-webview"||x.sessionId||x.providerSessionId||k.length>0||b||T||!["idle","panel_hidden","disconnected","not_monitored"].includes(v))&&r.push({routeId:e.id,sessionId:x.sessionId||x.instanceId,providerSessionId:x.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:x.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:x.sessionCapabilities,mode:"chat",agentName:x.agentName,agentType:x.agentType,status:v,title:T,messages:k,hostIdeType:e.type,workspaceName:o,workspacePath:c,git:x.git||e.git,displayPrimary:T||o||x.agentName||d,displaySecondary:`${d} · ${x.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,lastUpdated:x.lastUpdated||e.lastUpdated,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,modalButtons:b?x.activeModal.buttons:void 0,modalMessage:b?x.activeModal.message:void 0,streamSource:"agent-stream",tabKey:In(x.sessionId||x.instanceId,g),machineName:n,connectionState:a})}return r.length===0&&r.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:l,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:o,workspacePath:c,git:e.git,displayPrimary:o||d,displaySecondary:d,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:In(e.sessionId||e.instanceId,e.id),connectionState:a}),r}function Bp(e){const t=e.split(":");return t.length>=3&&(t[1]==="ide"||t[1]==="cli"||t[1]==="acp")?{daemonId:t[0],targetSessionId:t.slice(2).join(":")||void 0}:{daemonId:e}}function Qc(e,t){const r=Bp(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Zc=[{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:"🏄"}],el=[{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:"🧩"}],tl=[{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:"🟠"}],Kp=Zc,Op=el,Wp=tl;function ms(...e){return Sd(Nd(e))}function Fp({icon:e,title:t,subtitle:r,badge:n,actions:a,className:o}){return s.jsxs("div",{className:ms("dashboard-header",o),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,n&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[n.count!==void 0?n.count:""," ",n.text]})]}),r&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),a&&s.jsx("div",{className:"flex gap-2",children:a})]})}function sl({icon:e,title:t,subtitle:r,badge:n,actions:a,widthClassName:o="max-w-6xl",contentClassName:c,children:l}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(Fp,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:ms("mx-auto flex w-full flex-col gap-4",o,c),children:l})})]})}const ja="adhdev:themechange";function Hp(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function ys(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function vs(e){return e==="system"?Hp():e}function rl(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Br(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(ja,{detail:{preference:e,theme:t}}))}function Up(){const e=ys(),t=vs(e);rl(t),Br(e,t)}function ao(){const[e,t]=i.useState(ys),[r,n]=i.useState(()=>vs(ys()));i.useEffect(()=>{rl(r)},[r]),i.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=d=>{if(e==="system"){const f=d.matches?"light":"dark";n(f),Br("system",f)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),i.useEffect(()=>{const c=d=>{const f=d.detail||{},u=f.preference,p=f.theme;t(u==="dark"||u==="light"||u==="system"?u:ys()),n(p==="dark"||p==="light"?p:vs(ys()))},l=d=>{if(d.key!=="theme")return;const f=ys(),u=vs(f);t(f),n(u)};return window.addEventListener(ja,c),window.addEventListener("storage",l),()=>{window.removeEventListener(ja,c),window.removeEventListener("storage",l)}},[]);const a=i.useCallback(c=>{const l=vs(c);t(c),n(l);try{localStorage.setItem("theme",c)}catch{}Br(c,l)},[]),o=i.useCallback(()=>{t(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",d=vs(l);n(d);try{localStorage.setItem("theme",l)}catch{}return Br(l,d),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const ti={dark:"Dark",light:"Light",system:"System"};function zp({collapsed:e}){const{preference:t,cycleTheme:r}=ao(),n=t==="dark"?s.jsx(fu,{size:16}):t==="light"?s.jsx(uu,{size:16}):s.jsx(mu,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${ti[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:ti[t]})]})}function Ln(e,t){return e?typeof e=="function"?e(t):e:null}function Vp({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:o,footerActions:c,preMainContent:l,collapsedStorageKey:d="sidebar-collapsed"}){const[f,u]=i.useState(!1),[p,m]=i.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),y=()=>u(!0),N=()=>u(!1),h=()=>{m(v=>{const A=!v;try{localStorage.setItem(d,A?"1":"0")}catch{}return A})},j=i.useMemo(()=>({collapsed:p,mobileMenuOpen:f,openMobileMenu:y,closeMobileMenu:N,toggleCollapsed:h}),[p,f]),x=v=>`nav-item${v.active?" active":""} cursor-pointer ${p?"justify-center py-2.5 px-0":""}${v.className?` ${v.className}`:""}`,b=v=>s.jsxs("div",{className:x(v),id:`nav-${v.id}`,onClick:()=>{v.onSelect(),N()},title:p?v.title??(typeof v.label=="string"?v.label:void 0):v.title,children:[s.jsx("span",{className:"nav-icon",children:v.icon}),!p&&v.label]},v.id);return s.jsxs("div",{className:`app-layout${f?" mobile-menu-open":""}${p?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:y,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),f&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:N,onKeyDown:v=>v.key==="Escape"&&N()}),s.jsxs("aside",{className:`sidebar ${f?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${p?"justify-center gap-0":""}`,children:Ln(t,j)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:N,children:s.jsx(St,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(b)}),n.map(v=>s.jsxs("div",{className:v.className??"border-t border-border-subtle pt-2 mt-2",children:[!p&&v.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:v.title}):null,v.items.map(b)]},v.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(b),Ln(o,j),s.jsx(zp,{collapsed:p}),Ln(c,j)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function Nt({title:e,icon:t,description:r,accentColor:n,className:a,children:o}){return s.jsxs("div",{className:ms("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",a),style:n?{borderLeftColor:n}:void 0,children:[(e||r)&&s.jsxs("div",{className:"mb-4",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[t&&s.jsx("span",{className:"mr-1.5",children:t}),e]}),r&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),o]})}function nl({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:ms("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const Gp={error:"bg-red-500/10 border-red-500/30 text-red-400",warning:"bg-yellow-500/10 border-yellow-500/30 text-yellow-400",success:"bg-green-500/10 border-green-500/30 text-green-400",info:"bg-indigo-500/10 border-indigo-500/30 text-indigo-400"},qp={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Cr({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:ms("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Gp[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:qp[e]}),s.jsx("span",{children:t})]}),r&&s.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}const Yp={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"},Xp={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Jp({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:ms("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Yp[e],r),children:[s.jsx("span",{className:ms("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Xp[e])}),n]})}function Zt({label:e,description:t,checked:r,disabled:n,onChange:a,extra:o}){return s.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[o,s.jsxs("button",{type:"button",role:"switch","aria-checked":r,"aria-disabled":n,disabled:n,onClick:()=>a(!r),className:`relative inline-flex items-center ${n?"cursor-not-allowed":"cursor-pointer"}`,children:[s.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:r?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),s.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${r?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function Qp({onPrefChange:e}){const[t,r]=xf(),[n,a]=i.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);i.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 o=(c,l)=>{r({[c]:l}),e==null||e(c,l)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(cn,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:c=>o("globalEnabled",c)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Tt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:c=>o("browserNotifications",c)}),t.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:"Browser alerts only fire while this dashboard tab stays open in the background. If you close it, standalone cannot deliver hosted push notifications for you."}),n==="default"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[s.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),s.jsx("button",{onClick:()=>{mc().then(a)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:"Allow notifications"})]}),n==="denied"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),n==="unsupported"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),t.globalEnabled&&t.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(pu,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:c=>o("completionAlert",c)}),s.jsx(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(hu,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:c=>o("approvalAlert",c)}),s.jsx(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ar,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:c=>o("disconnectAlert",c)})]}),!t.globalEnabled&&s.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function sn(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function Zp(e,t){const r=sn(e),n=sn(t);if(!r||!n)return e.localeCompare(t);for(let a=0;a<3;a+=1){if(r[a]<n[a])return-1;if(r[a]>n[a])return 1}return 0}function al(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function Zs(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||Zp(r,t)>=0)return!1;const n=sn(r),a=sn(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function eh(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Rn(e,t){return e instanceof Error?e.message:t}function th({ides:e,emptyMessage:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const o=e.filter(c=>c.type==="adhdev-daemon");return o.length===0?s.jsx(nl,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:"No machines connected",description:t||"Install ADHDev on a machine and sign in to connect it here."}):s.jsx("div",{className:"flex flex-col gap-2",children:o.map(c=>s.jsx(rh,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function si({title:e,message:t,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:o}){const c=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return sr.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:o,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:l=>l.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:o,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:"Cancel"}),s.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:n==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:r})]})]})}),document.body)}function sh(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Kp,...Op,...Wp].find(a=>a.id===t||t.includes(a.id)||a.id.includes(t));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function rh({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var H,P;const[o,c]=i.useState("idle"),[l,d]=i.useState(""),[f,u]=i.useState(null),[p,m]=i.useState("idle"),[y,N]=i.useState(""),h=e.version||null,j=((H=e.machine)==null?void 0:H.platform)||((P=e.system)==null?void 0:P.platform)||"",x=Ct(e,{fallbackId:e.id}),b=j==="win32"?"🪟":j==="darwin"?"🍎":"🐧",v=t.filter(C=>C.daemonId===e.id&&C.transport==="cdp-page"),A=t.filter(C=>C.daemonId===e.id&&C.transport==="pty"),g=t.filter(C=>C.daemonId===e.id&&C.transport==="acp"),M=e.p2p,T=async()=>{if(r){c("upgrading"),d("Starting upgrade...");try{const C=eh(await r(e.id,"daemon_upgrade",{}));C.alreadyLatest?(c("done"),d(`Already on v${C.version||"latest"}.`)):C.upgraded||C.success?(c("done"),d(`Upgrade to v${C.version||"latest"} started. Daemon is restarting...`)):(c("error"),d(C.error||"Upgrade failed"))}catch(C){c("error"),d(Rn(C,"Connection lost during upgrade"))}}},k=async()=>{if(u(null),!!n){m("loading");try{await n(e.id),m("done"),N("Machine disconnected.")}catch(C){m("error"),N(Rn(C,"Failed to disconnect"))}}},w=async()=>{if(u(null),!!a){m("loading");try{await a(e.id),m("done"),N("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(C){m("error"),N(Rn(C,"Failed to revoke token"))}}},K="0.9.60",R=al(e,K),S=Zs(e,K),O=v.length+A.length+g.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:b}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:x}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),h&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${R?"":"bg-bg-secondary"}`,style:R?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",h,!R&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&R&&s.jsx("button",{onClick:T,disabled:o==="upgrading"||o==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${K}`,children:o==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):o==="done"?"✓ Updated":`${S?"↑ Update now":`↑ Update${` to v${K}`}`}`}),n&&s.jsx("button",{onClick:()=>u("disconnect"),disabled:p==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>u("revoke"),disabled:p==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(Jp,{status:e.status==="online"?"online":"error"})]})]}),s.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[M&&s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${M.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${M.state==="connecting"||M.state==="new"?"animate-pulse":""}`,style:M.state==="connecting"||M.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",M.state==="connected"?"connected":M.state==="connecting"||M.state==="new"?"connecting...":M.state||"off"]}),M.peers!==void 0&&M.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",M.peers," peer",M.peers!==1?"s":"",")"]})]}),M&&O>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),O>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[v.map(C=>{const I=sh(C.type),W=C.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:I.icon}),s.jsx("span",{children:I.name}),W!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${W?"bg-green-400":"animate-pulse"}`,style:W?void 0:{background:"var(--status-warning)"},title:W?"CDP connected":"CDP connecting..."})]},C.id)}),A.map(C=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:C.cliName||"CLI"})]},C.id)),g.map(C=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"🔗"}),s.jsx("span",{children:C.cliName||"ACP"})]},C.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||y)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||p==="error"?"text-red-400":o==="done"||p==="done"?"text-green-400":"text-text-muted"}`,children:y||l})]}),f==="disconnect"&&s.jsx(si,{title:"🔌 Disconnect Machine",message:`Disconnect "${x}" from ADHDev?
|
|
40
|
+
`).includes(a)))}function Np(e,t="recent"){const r=e.slice();return r.sort((n,a)=>{if(t==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(t==="messages"){const o=(Number(a.messageCount)||0)-(Number(n.messageCount)||0);if(o!==0)return o}return(Number(a.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function Vc(e,t={}){return Np(Sp(e,t),t.sortMode||"recent")}function tn(e){return e?"Resume saved history":"Start fresh"}function Za(e){return e?"Resuming saved history…":"Starting fresh…"}function Cp(){return"Start fresh"}function Gc(e,t=!1){return e==="cli"?tn(t):e==="ide"?"Start IDE":"Start ACP session"}function qc(e,t=!1){return e==="cli"?Za(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Tp(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Mp(){return"Open saved history"}function Ap(){return"Saved History"}function eo(){return"Use saved history when you want continuity in the same provider conversation."}function Ip(){return"No saved history found yet."}function Lp(){return"Refresh saved history"}function Rp(){return"Refreshing saved history…"}function ns(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function as(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 Ls(e){return e==="start-fresh"?"Start fresh":"Restart"}function Rs(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function to(e){return`Resume saved history with ${e}?`}function so(){return"Review or change the target workspace before resuming saved history."}function _p(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 ro({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:f,onClose:u,onNewChat:p,onSwitchSession:m,onRefreshHistory:y,onResumeSavedSession:N}){var R;const h=t.find(S=>S.id===e.routeId),j=(h==null?void 0:h.chats)||[],x=(R=h==null?void 0:h.activeChat)==null?void 0:R.id,b=et(e)&&!Xe(e),[v,A]=i.useState(()=>xt()),g=l||v,M=String(d||"").trim(),T=S=>{if(f){f(S);return}A(S)},k=i.useMemo(()=>a.map(S=>{const O=String(S.workspace||"").trim();return S.canResume||O||!M?S:{...S,workspace:M,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[M,a]),w=i.useMemo(()=>Vc(k,{textQuery:g.textQuery,workspaceQuery:g.workspaceQuery,modelQuery:g.modelQuery,resumableOnly:g.resumableOnly,sortMode:g.sortMode}),[k,g.modelQuery,g.resumableOnly,g.sortMode,g.textQuery,g.workspaceQuery]),K=s.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:u,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:b?Ap():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:dp(e)}),b&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:eo()})]}),s.jsx("button",{onClick:u,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(St,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!b&&s.jsx("button",{onClick:p,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"}),b?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:g.textQuery,onChange:S=>T({...g,textQuery:S.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:g.workspaceQuery,onChange:S=>T({...g,workspaceQuery:S.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:g.modelQuery,onChange:S=>T({...g,modelQuery:S.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:g.sortMode,onChange:S=>T({...g,sortMode:S.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:g.resumableOnly,onChange:S=>T({...g,resumableOnly:S.target.checked})}),"Resume-ready only"]})]}),w.map(S=>{const O=e.providerSessionId===S.providerSessionId,H=O||!S.canResume||!!c,P=S.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{H||!N||N(S)},disabled:H,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${O?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${H?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${O?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:S.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:S.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:_p(S.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:S.preview||"No saved preview yet"}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[S.workspace||"Workspace unknown",P?" · selected workspace":"",fs(S.summaryMetadata)?` · ${fs(S.summaryMetadata)}`:"",S.messageCount>0?` · ${S.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:O?"ACTIVE":S.canResume?P?"RESUME IN SELECTED WORKSPACE":c===S.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},S.id)})]}):j.map(S=>s.jsxs("div",{onClick:()=>{m(e.routeId,S.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${x===S.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${x===S.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:S.title||"Untitled Session"}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[S.id.substring(0,12),"..."]}),x===S.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},S.id)),(b&&!o&&w.length===0||!b&&j.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(du,{size:32})}),s.jsx("div",{className:"text-[13px]",children:b?a.length>0?"No saved history matches these filters.":Ip():"No recent chat sessions found."})]}),b&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:Rp()})})]}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:s.jsx("button",{onClick:y,disabled:n||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||o?"⌛ Refreshing...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(lr,{size:13})," ",b?Lp():"Refresh History"]})})})]})]});return typeof document>"u"?K:sr.createPortal(K,document.body)}const ei={success:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Done"},warning:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Attention"},info:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Update"}};function Yc({toasts:e,onDismiss:t,onClickToast:r}){return s.jsx("div",{className:"fixed right-4 z-[9999] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(n=>{const a=ei[n.type]||ei.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var o;(o=n.actions)!=null&&o.length||r&&r(n)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${a.accent}, color-mix(in srgb, ${a.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:o=>{o.stopPropagation(),t(n.id)},"aria-label":"Dismiss",children:s.jsx(St,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:a.chipBg,color:a.chipText,border:`1px solid color-mix(in srgb, ${a.accent} 22%, transparent)`},children:a.label})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((o,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${o.variant==="primary"||o.variant==="danger",""}`,style:o.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)"}:o.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(),o.onClick(),t(n.id)},children:o.label},c))})]})]},n.id)})})}const Pp=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Dp(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function Ep(e){return e.sessionId||e.instanceId||e.agentType}function In(e,t){return e||t}function Xc(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Ct(r,{fallbackId:r.id}));return t}function Jc(e,t={}){var n,a;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((a=t.machineNames)==null?void 0:a[e.daemonId])||void 0,connectionState:t.connectionStates?t.connectionStates[r]||t.defaultConnectionState||"new":t.defaultConnectionState}}function no(e,t={}){return $p(e,Jc(e,t))}function $p(e,t={}){var p,m,y,N,h,j;const r=[],n=t.machineName,a=t.connectionState,o=Dp(e),c=e.workspace||"",l=nf(e.type,{agentName:e.cliName}),d=et(e)||Xe(e)?l:at(e.type),f=Array.isArray(e.childSessions)?e.childSessions.map(x=>{var b,v;return{sessionId:x.id,instanceId:x.id,providerSessionId:x.providerSessionId,transport:x.transport,sessionCapabilities:x.capabilities,agentType:x.providerType,agentName:x.providerName||at(x.providerType),status:x.status,title:x.title,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,messages:((b=x.activeChat)==null?void 0:b.messages)||[],activeModal:((v=x.activeChat)==null?void 0:v.activeModal)||void 0,unread:x.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,surfaceHidden:x.surfaceHidden,git:x.git}}):[],u=Pp(e);if(u){const x=e.sessionId||e.instanceId,b=l,v=(p=e.activeChat)==null?void 0:p.activeModal,A=v&&Array.isArray(v.buttons)&&v.buttons.length>0,g=yt((m=e.activeChat)==null?void 0:m.status,{activeModal:(y=e.activeChat)==null?void 0:y.activeModal})||yt((h=(N=e.agents)==null?void 0:N[0])==null?void 0:h.status)||"idle",M=e.activeChat||{title:"",messages:[]};let T=M.title&&String(M.title).trim()?String(M.title).trim():"";const k=(j=e.activeChat)==null?void 0:j.id,w=e.chats;if(k&&Array.isArray(w)&&w.length>0){const O=w.find(H=>H.id===k||H.id&&String(H.id)===String(k));O!=null&&O.title&&String(O.title).trim()&&(T=String(O.title).trim())}const K=(et(e)||Xe(e),e.type),R=(et(e)||Xe(e))&&Eo(T,b,K)?"":T,S=M.messages||[];r.push({routeId:e.id,sessionId:x,providerSessionId:e.providerSessionId,nativeSessionId:x,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:et(e)?e.mode||"terminal":"chat",agentName:b,agentType:K,status:g,title:R,messages:S,resume:e.resume,hostIdeType:!et(e)&&!Xe(e)?e.type:void 0,workspaceName:o,workspacePath:c,git:e.git,displayPrimary:R||o||(et(e)?e.mode==="chat"?b:"Terminal":b),displaySecondary:d,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:A?v.buttons:void 0,modalMessage:A?v.message:void 0,streamSource:"native",tabKey:In(x,e.id),machineName:n,connectionState:a})}if(u&&(et(e)||Xe(e)))return r;for(const x of f){const b=x.activeModal&&Array.isArray(x.activeModal.buttons)&&x.activeModal.buttons.length>0,v=af(x),A=Ep(x),g=`${e.id}:${A}`,M=x.title&&String(x.title).trim()||"",T=Eo(M,x.agentName,x.agentType)?"":M,k=x.messages||[];(x.transport==="cdp-webview"||x.sessionId||x.providerSessionId||k.length>0||b||T||!["idle","panel_hidden","disconnected","not_monitored"].includes(v))&&r.push({routeId:e.id,sessionId:x.sessionId||x.instanceId,providerSessionId:x.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:x.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:x.sessionCapabilities,mode:"chat",agentName:x.agentName,agentType:x.agentType,status:v,title:T,messages:k,hostIdeType:e.type,workspaceName:o,workspacePath:c,git:x.git||e.git,displayPrimary:T||o||x.agentName||d,displaySecondary:`${d} · ${x.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,lastUpdated:x.lastUpdated||e.lastUpdated,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,modalButtons:b?x.activeModal.buttons:void 0,modalMessage:b?x.activeModal.message:void 0,streamSource:"agent-stream",tabKey:In(x.sessionId||x.instanceId,g),machineName:n,connectionState:a})}return r.length===0&&r.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:l,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:o,workspacePath:c,git:e.git,displayPrimary:o||d,displaySecondary:d,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:In(e.sessionId||e.instanceId,e.id),connectionState:a}),r}function Bp(e){const t=e.split(":");return t.length>=3&&(t[1]==="ide"||t[1]==="cli"||t[1]==="acp")?{daemonId:t[0],targetSessionId:t.slice(2).join(":")||void 0}:{daemonId:e}}function Qc(e,t){const r=Bp(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Zc=[{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:"🏄"}],el=[{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:"🧩"}],tl=[{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:"🟠"}],Kp=Zc,Op=el,Wp=tl;function ms(...e){return Sd(Nd(e))}function Fp({icon:e,title:t,subtitle:r,badge:n,actions:a,className:o}){return s.jsxs("div",{className:ms("dashboard-header",o),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,n&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[n.count!==void 0?n.count:""," ",n.text]})]}),r&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),a&&s.jsx("div",{className:"flex gap-2",children:a})]})}function sl({icon:e,title:t,subtitle:r,badge:n,actions:a,widthClassName:o="max-w-6xl",contentClassName:c,children:l}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(Fp,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:ms("mx-auto flex w-full flex-col gap-4",o,c),children:l})})]})}const ja="adhdev:themechange";function Hp(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function ys(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function vs(e){return e==="system"?Hp():e}function rl(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Br(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(ja,{detail:{preference:e,theme:t}}))}function Up(){const e=ys(),t=vs(e);rl(t),Br(e,t)}function ao(){const[e,t]=i.useState(ys),[r,n]=i.useState(()=>vs(ys()));i.useEffect(()=>{rl(r)},[r]),i.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=d=>{if(e==="system"){const f=d.matches?"light":"dark";n(f),Br("system",f)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),i.useEffect(()=>{const c=d=>{const f=d.detail||{},u=f.preference,p=f.theme;t(u==="dark"||u==="light"||u==="system"?u:ys()),n(p==="dark"||p==="light"?p:vs(ys()))},l=d=>{if(d.key!=="theme")return;const f=ys(),u=vs(f);t(f),n(u)};return window.addEventListener(ja,c),window.addEventListener("storage",l),()=>{window.removeEventListener(ja,c),window.removeEventListener("storage",l)}},[]);const a=i.useCallback(c=>{const l=vs(c);t(c),n(l);try{localStorage.setItem("theme",c)}catch{}Br(c,l)},[]),o=i.useCallback(()=>{t(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",d=vs(l);n(d);try{localStorage.setItem("theme",l)}catch{}return Br(l,d),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const ti={dark:"Dark",light:"Light",system:"System"};function zp({collapsed:e}){const{preference:t,cycleTheme:r}=ao(),n=t==="dark"?s.jsx(fu,{size:16}):t==="light"?s.jsx(uu,{size:16}):s.jsx(mu,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${ti[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:ti[t]})]})}function Ln(e,t){return e?typeof e=="function"?e(t):e:null}function Vp({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:o,footerActions:c,preMainContent:l,collapsedStorageKey:d="sidebar-collapsed"}){const[f,u]=i.useState(!1),[p,m]=i.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),y=()=>u(!0),N=()=>u(!1),h=()=>{m(v=>{const A=!v;try{localStorage.setItem(d,A?"1":"0")}catch{}return A})},j=i.useMemo(()=>({collapsed:p,mobileMenuOpen:f,openMobileMenu:y,closeMobileMenu:N,toggleCollapsed:h}),[p,f]),x=v=>`nav-item${v.active?" active":""} cursor-pointer ${p?"justify-center py-2.5 px-0":""}${v.className?` ${v.className}`:""}`,b=v=>s.jsxs("div",{className:x(v),id:`nav-${v.id}`,onClick:()=>{v.onSelect(),N()},title:p?v.title??(typeof v.label=="string"?v.label:void 0):v.title,children:[s.jsx("span",{className:"nav-icon",children:v.icon}),!p&&v.label]},v.id);return s.jsxs("div",{className:`app-layout${f?" mobile-menu-open":""}${p?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:y,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),f&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:N,onKeyDown:v=>v.key==="Escape"&&N()}),s.jsxs("aside",{className:`sidebar ${f?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${p?"justify-center gap-0":""}`,children:Ln(t,j)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:N,children:s.jsx(St,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(b)}),n.map(v=>s.jsxs("div",{className:v.className??"border-t border-border-subtle pt-2 mt-2",children:[!p&&v.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:v.title}):null,v.items.map(b)]},v.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(b),Ln(o,j),s.jsx(zp,{collapsed:p}),Ln(c,j)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function Nt({title:e,icon:t,description:r,accentColor:n,className:a,children:o}){return s.jsxs("div",{className:ms("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",a),style:n?{borderLeftColor:n}:void 0,children:[(e||r)&&s.jsxs("div",{className:"mb-4",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[t&&s.jsx("span",{className:"mr-1.5",children:t}),e]}),r&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),o]})}function nl({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:ms("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const Gp={error:"bg-red-500/10 border-red-500/30 text-red-400",warning:"bg-yellow-500/10 border-yellow-500/30 text-yellow-400",success:"bg-green-500/10 border-green-500/30 text-green-400",info:"bg-indigo-500/10 border-indigo-500/30 text-indigo-400"},qp={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Cr({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:ms("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Gp[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:qp[e]}),s.jsx("span",{children:t})]}),r&&s.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}const Yp={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"},Xp={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Jp({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:ms("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Yp[e],r),children:[s.jsx("span",{className:ms("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Xp[e])}),n]})}function Zt({label:e,description:t,checked:r,disabled:n,onChange:a,extra:o}){return s.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[o,s.jsxs("button",{type:"button",role:"switch","aria-checked":r,"aria-disabled":n,disabled:n,onClick:()=>a(!r),className:`relative inline-flex items-center ${n?"cursor-not-allowed":"cursor-pointer"}`,children:[s.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:r?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),s.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${r?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function Qp({onPrefChange:e}){const[t,r]=xf(),[n,a]=i.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);i.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 o=(c,l)=>{r({[c]:l}),e==null||e(c,l)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(cn,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:c=>o("globalEnabled",c)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Tt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:c=>o("browserNotifications",c)}),t.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:"Browser alerts only fire while this dashboard tab stays open in the background. If you close it, standalone cannot deliver hosted push notifications for you."}),n==="default"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[s.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),s.jsx("button",{onClick:()=>{mc().then(a)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:"Allow notifications"})]}),n==="denied"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),n==="unsupported"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),t.globalEnabled&&t.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(pu,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:c=>o("completionAlert",c)}),s.jsx(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(hu,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:c=>o("approvalAlert",c)}),s.jsx(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ar,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:c=>o("disconnectAlert",c)})]}),!t.globalEnabled&&s.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function sn(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function Zp(e,t){const r=sn(e),n=sn(t);if(!r||!n)return e.localeCompare(t);for(let a=0;a<3;a+=1){if(r[a]<n[a])return-1;if(r[a]>n[a])return 1}return 0}function al(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function Zs(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||Zp(r,t)>=0)return!1;const n=sn(r),a=sn(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function eh(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Rn(e,t){return e instanceof Error?e.message:t}function th({ides:e,emptyMessage:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const o=e.filter(c=>c.type==="adhdev-daemon");return o.length===0?s.jsx(nl,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:"No machines connected",description:t||"Install ADHDev on a machine and sign in to connect it here."}):s.jsx("div",{className:"flex flex-col gap-2",children:o.map(c=>s.jsx(rh,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function si({title:e,message:t,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:o}){const c=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return sr.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:o,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:l=>l.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:o,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:"Cancel"}),s.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:n==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:r})]})]})}),document.body)}function sh(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Kp,...Op,...Wp].find(a=>a.id===t||t.includes(a.id)||a.id.includes(t));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function rh({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var H,P;const[o,c]=i.useState("idle"),[l,d]=i.useState(""),[f,u]=i.useState(null),[p,m]=i.useState("idle"),[y,N]=i.useState(""),h=e.version||null,j=((H=e.machine)==null?void 0:H.platform)||((P=e.system)==null?void 0:P.platform)||"",x=Ct(e,{fallbackId:e.id}),b=j==="win32"?"🪟":j==="darwin"?"🍎":"🐧",v=t.filter(C=>C.daemonId===e.id&&C.transport==="cdp-page"),A=t.filter(C=>C.daemonId===e.id&&C.transport==="pty"),g=t.filter(C=>C.daemonId===e.id&&C.transport==="acp"),M=e.p2p,T=async()=>{if(r){c("upgrading"),d("Starting upgrade...");try{const C=eh(await r(e.id,"daemon_upgrade",{}));C.alreadyLatest?(c("done"),d(`Already on v${C.version||"latest"}.`)):C.upgraded||C.success?(c("done"),d(`Upgrade to v${C.version||"latest"} started. Daemon is restarting...`)):(c("error"),d(C.error||"Upgrade failed"))}catch(C){c("error"),d(Rn(C,"Connection lost during upgrade"))}}},k=async()=>{if(u(null),!!n){m("loading");try{await n(e.id),m("done"),N("Machine disconnected.")}catch(C){m("error"),N(Rn(C,"Failed to disconnect"))}}},w=async()=>{if(u(null),!!a){m("loading");try{await a(e.id),m("done"),N("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(C){m("error"),N(Rn(C,"Failed to revoke token"))}}},K="0.9.61",R=al(e,K),S=Zs(e,K),O=v.length+A.length+g.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:b}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:x}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),h&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${R?"":"bg-bg-secondary"}`,style:R?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",h,!R&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&R&&s.jsx("button",{onClick:T,disabled:o==="upgrading"||o==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${K}`,children:o==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):o==="done"?"✓ Updated":`${S?"↑ Update now":`↑ Update${` to v${K}`}`}`}),n&&s.jsx("button",{onClick:()=>u("disconnect"),disabled:p==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>u("revoke"),disabled:p==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(Jp,{status:e.status==="online"?"online":"error"})]})]}),s.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[M&&s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${M.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${M.state==="connecting"||M.state==="new"?"animate-pulse":""}`,style:M.state==="connecting"||M.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",M.state==="connected"?"connected":M.state==="connecting"||M.state==="new"?"connecting...":M.state||"off"]}),M.peers!==void 0&&M.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",M.peers," peer",M.peers!==1?"s":"",")"]})]}),M&&O>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),O>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[v.map(C=>{const I=sh(C.type),W=C.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:I.icon}),s.jsx("span",{children:I.name}),W!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${W?"bg-green-400":"animate-pulse"}`,style:W?void 0:{background:"var(--status-warning)"},title:W?"CDP connected":"CDP connecting..."})]},C.id)}),A.map(C=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:C.cliName||"CLI"})]},C.id)),g.map(C=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"🔗"}),s.jsx("span",{children:C.cliName||"ACP"})]},C.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||y)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||p==="error"?"text-red-400":o==="done"||p==="done"?"text-green-400":"text-text-muted"}`,children:y||l})]}),f==="disconnect"&&s.jsx(si,{title:"🔌 Disconnect Machine",message:`Disconnect "${x}" from ADHDev?
|
|
41
41
|
|
|
42
42
|
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
43
43
|
|
|
@@ -48,7 +48,7 @@ This will:
|
|
|
48
48
|
• Delete the machine registration
|
|
49
49
|
• Require restarting ADHDev on that machine
|
|
50
50
|
|
|
51
|
-
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:w,onCancel:()=>u(null)})]})}const nh=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function ah(){const{preference:e,setPreference:t}=ao();return s.jsx("div",{className:"flex gap-2",children:nh.map(r=>s.jsxs("button",{onClick:()=>t(r.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===r.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===r.id?{color:"var(--accent-on-primary)"}:void 0,children:[s.jsx("span",{children:r.icon}),r.label]},r.id))})}function oh(e){const t=e.trim();return/^#[0-9a-fA-F]{6}$/.test(t)?t:/^#[0-9a-fA-F]{3}$/.test(t)?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:null}function ih(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function _n(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function ri(e){const{r:t,g:r,b:n}=ih(e);return .2126*_n(t)+.7152*_n(r)+.0722*_n(n)}function ni(e,t){const r=ri(e),n=ri(t),a=Math.max(r,n),o=Math.min(r,n);return(a+.05)/(o+.05)}function ol(e){const t=oh(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return ni(t,r)>=ni(t,n)?r:n}const ka={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},Sa={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},ch=[{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"}}}],il="adhdev-chat-theme",cl="adhdev-chat-theme-custom";function Kr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(il)||"ember"}catch{return"ember"}}function _t(e){try{const t=localStorage.getItem(cl);if(t){const r=JSON.parse(t);return{...e==="dark"?ka:Sa,...r[e]}}}catch{}return e==="dark"?ka:Sa}function Tr(e,t){try{localStorage.setItem(cl,JSON.stringify({dark:e,light:t}))}catch{}}function Mt(e,t){const r=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${r}, ${n}, ${a}, ${t})`}function rn(e,t){const r=Math.min(255,parseInt(e.slice(1,3),16)+t),n=Math.min(255,parseInt(e.slice(3,5),16)+t),a=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const lh={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function er(e,t){var a;const r=(a=lh[e])==null?void 0:a[t];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",rn(r,24)),n.style.setProperty("--accent-on-primary",ol(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${rn(r,18)})`),n.style.setProperty("--border-accent",Mt(r,.35)),n.style.setProperty("--nav-active-bg",Mt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Mt(r,.06)}`)}function os(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Mt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Mt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Mt(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",Mt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Mt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",rn(e.accentColor,30)),t.style.setProperty("--accent-on-primary",ol(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${rn(e.accentColor,40)})`),t.style.setProperty("--border-accent",Mt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Mt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Mt(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${Mt(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function oo(){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 dh(e){try{localStorage.setItem(il,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=is()?"dark":"light";os(_t(t))}else oo(),er(e,is()?"dark":"light")}function uh(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Kr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=is()?"dark":"light";os(_t(t))}else oo(),er(e,is()?"dark":"light")}function is(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function gt({label:e,value:t,onChange:r}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,onChange:n=>{/^#[0-9a-fA-F]{0,6}$/.test(n.target.value)&&r(n.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function Hs({title:e,children:t}){return s.jsxs("div",{style:{marginBottom:14},children:[s.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:t})]})}function fh({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=i.useState(()=>_t(r));i.useEffect(()=>{a(_t(r))},[r]);const o=i.useCallback((c,l)=>{a(d=>{const f={...d,[c]:l},p=_t(r==="dark"?"light":"dark");return r==="dark"?Tr(f,p):Tr(p,f),os(f),t(f),f})},[r,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",s.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(Hs,{title:"App Background",children:[s.jsx(gt,{label:"Background",value:n.bgPrimary,onChange:c=>o("bgPrimary",c)}),s.jsx(gt,{label:"Surface",value:n.bgSecondary,onChange:c=>o("bgSecondary",c)}),s.jsx(gt,{label:"Card",value:n.surfacePrimary,onChange:c=>o("surfacePrimary",c)})]}),s.jsxs(Hs,{title:"App Text",children:[s.jsx(gt,{label:"Primary",value:n.textPrimary,onChange:c=>o("textPrimary",c)}),s.jsx(gt,{label:"Secondary",value:n.textSecondary,onChange:c=>o("textSecondary",c)}),s.jsx(gt,{label:"Muted",value:n.textMuted,onChange:c=>o("textMuted",c)})]}),s.jsxs(Hs,{title:"Borders & Accent",children:[s.jsx(gt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>o("borderSubtle",c)}),s.jsx(gt,{label:"Border default",value:n.borderDefault,onChange:c=>o("borderDefault",c)}),s.jsx(gt,{label:"Accent",value:n.accentColor,onChange:c=>o("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Hs,{title:"Chat Bubbles",children:[s.jsx(gt,{label:"User bubble",value:n.userBubble,onChange:c=>o("userBubble",c)}),s.jsx(gt,{label:"User text",value:n.userText,onChange:c=>o("userText",c)}),s.jsx(gt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>o("assistantBubble",c)}),s.jsx(gt,{label:"Agent text",value:n.assistantText,onChange:c=>o("assistantText",c)})]}),s.jsxs(Hs,{title:"Chat Layout",children:[s.jsx(gt,{label:"Chat BG",value:n.containerBg,onChange:c=>o("containerBg",c)}),s.jsx(gt,{label:"Send button",value:n.sendButton,onChange:c=>o("sendButton",c)}),s.jsx(gt,{label:"Input border",value:n.inputBorder,onChange:c=>o("inputBorder",c)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.jsx("input",{type:"range",min:4,max:24,value:n.bubbleRadius,onChange:c=>o("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?ka:Sa,d=_t(e?"light":"dark");e?Tr(c,d):Tr(d,c),a(c),os(c),t(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:"Reset to defaults"})]})}function mh(){const[e,t]=i.useState(Kr),[r,n]=i.useState(!0),[a,o]=i.useState(()=>_t("dark"));i.useEffect(()=>{n(is());const d=new MutationObserver(()=>{const p=is();n(p);const m=Kr();m==="custom"?os(_t(p?"dark":"light")):er(m,p?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const f=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const p=is();n(p);const m=Kr();m==="custom"?os(_t(p?"dark":"light")):er(m,p?"dark":"light")};return f.addEventListener("change",u),()=>{d.disconnect(),f.removeEventListener("change",u)}},[]),i.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?os(_t(r?"dark":"light")):(oo(),er(e,r?"dark":"light"))},[e,r]),i.useEffect(()=>{o(_t(r?"dark":"light"))},[r]);const c=d=>{t(d),dh(d)},l=[...ch,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:l.map(d=>{const f=e===d.id,u=r?d.preview.dark:d.preview.light,p=d.id==="honey"||d.id==="ember"?"#1a1a1a":d.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>c(d.id),className:"text-left rounded-xl p-3 transition-all",style:{background:f?"var(--bg-glass-hover)":"var(--bg-glass)",border:f?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:f?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:u.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"Hello! How can I help?"}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.userBubble,color:p},children:"Fix the bug please"}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"On it! ✨"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[f&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:d.id==="custom"?"🎨 Custom":d.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:d.description})]})]})]},d.id)})}),e==="custom"&&s.jsx(fh,{dark:r,onColorsChange:d=>o(d)})]})}const io="adhdev_mobileDashboardMode_v1",Na="adhdev:mobile-dashboard-mode-change";function co(){try{return localStorage.getItem(io)==="workspace"?"workspace":"chat"}catch{return"chat"}}function ph(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??co())},r=a=>{const o=a.detail;t(o)},n=a=>{a.key&&a.key!==io||t()};return window.addEventListener(Na,r),window.addEventListener("storage",n),()=>{window.removeEventListener(Na,r),window.removeEventListener("storage",n)}}function hh(e){try{localStorage.setItem(io,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Na,{detail:e}))}function xh(){const[e,t]=i.useState(!0);return i.useEffect(()=>{t(co()==="chat")},[]),s.jsx(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ut,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:r=>{t(r),hh(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const Pn=new Map,ai=new Map;function bh(e){if(!e||typeof e!="object")return null;const t=e,r=t.result&&typeof t.result=="object"?t.result:t,n=r.machine;return!n||typeof n!="object"?null:{machine:n,timestamp:typeof r.timestamp=="number"?r.timestamp:void 0}}function gh(e,t,r,n){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:n,platform:r.platform,machine:r}}function ll(){const{sendCommand:e}=mt(),{injectEntries:t,getIdes:r}=rr();return i.useCallback(async(n,a)=>{if(!n)return;const o=(a==null?void 0:a.minFreshMs)??pm,c=ai.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<o)return;const l=Pn.get(n);if(l)return l;const d=(async()=>{const f=await e(n,"get_machine_runtime_stats"),u=bh(f);if(!u)return;const p=r().find(y=>y.id===n),m=gh(p,n,u.machine,u.timestamp||Date.now());t([m]),ai.set(n,Date.now())})().finally(()=>{Pn.delete(n)});return Pn.set(n,d),d},[r,t,e])}function yh(e,t,r){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:r.timestamp,platform:r.machine.platform,machine:{...(e==null?void 0:e.machine)||{},...r.machine}}}function vh(e,t){const{sendData:r}=mt(),{injectEntries:n,getIdes:a}=rr(),o=Array.from(new Set(e.filter(Boolean))).join("|");i.useEffect(()=>{if(!(t!=null&&t.enabled)||!r)return;const c=o?o.split("|"):[];if(c.length===0)return;const l=c.map(d=>Ht.subscribe({sendData:r},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const p=a().find(y=>y.id===d),m=yh(p,d,u);n([m])}));return()=>{l.forEach(d=>d())}},[o,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function wh(e,t){const{sendData:r}=mt(),[n,a]=i.useState(null),[o,c]=i.useState(!1);return i.useEffect(()=>{if(!e){a(null),c(!1);return}if(!(t!=null&&t.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const d=Ht.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},f=>{l&&(clearTimeout(l),l=null),a(f.diagnostics),c(!1)});return d.initialSendAccepted?l=setTimeout(()=>{c(!1)},gm):c(!1),()=>{l&&clearTimeout(l),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,r]),{diagnostics:n,loading:o,applyDiagnostics:a}}function jh(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function dl(e){const{sendData:t}=mt(),[r,n]=i.useState({});return i.useEffect(()=>{const a=jh(e);if(!a||!e.sessionId||!t){n({});return}const o=Ht.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),Ns.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 o.initialSendAccepted||n({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),r}const ul="adhdev_hiddenTabs";function kh(){try{const e=localStorage.getItem(ul);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function bs(e){try{localStorage.setItem(ul,JSON.stringify([...e]))}catch{}}function Dn(e){return qa(e)}function lo(e,t){return Ss(t).some(r=>e.has(r))}function Sh(){const[e,t]=i.useState(kh),r=i.useCallback(f=>{const u=Dn(f);t(p=>{const m=new Set(p);return m.has(u)?m.delete(u):m.add(u),bs(m),m})},[]),n=i.useCallback(f=>{const u=Dn(f);t(p=>{if(p.has(u))return p;const m=new Set(p);return m.add(u),bs(m),m})},[]),a=i.useCallback(f=>{const u=Dn(f);t(p=>{if(!p.has(u))return p;const m=new Set(p);return m.delete(u),bs(m),m})},[]),o=i.useCallback(()=>{t(f=>{if(f.size===0)return f;const u=new Set;return bs(u),u})},[]),c=i.useCallback((f,u)=>{t(p=>{const m=new Set(p);for(const y of u)m.add(y);return bs(m),m})},[]),l=i.useCallback((f,u)=>{t(p=>{const m=new Set(p);for(const y of u)m.delete(y);return bs(m),m})},[]),d=i.useCallback(f=>lo(e,f),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:o,hideAllForDaemon:c,showAllForDaemon:l,isHidden:d}}function fl(e){return e instanceof Error?e.message:String(e||"")}function ml(e){const t=fl(e);return t.includes("P2P command timeout")||t.includes("P2P not connected")||t.includes("P2P channel not open")||t.includes("P2P not available")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}function pl(e){const t=fl(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function hl({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!et(e)||Xe(e))return;const o=Es(e);if(o===t)return;const c=e.sessionId;c&&a(l=>({...l,[c]:t}));try{await n(xs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Bt(e),mode:t})}catch(l){const d=pl(l);c&&!d&&a(f=>{const u={...f};return o===xl(r,c)?delete u[c]:u[c]=o,u}),ml(l)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",l instanceof Error?l.message:String(l)):console.error("Failed to switch CLI view mode:",l)}}function oi(e,t){const r=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!r||e.transport!=="pty")return e;const n=t[r];return!n||e.mode===n?e:{...e,mode:n}}function Nh(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let r=!1;const n=e.map(a=>{const o=oi(a,t),c=Array.isArray(a.childSessions)?a.childSessions.map(d=>oi(d,t)):a.childSessions,l=c!==a.childSessions;return o!==a||l?(r=!0,{...o,...l?{childSessions:c}:{}}):a});return r?n:e}function xl(e,t){if(!t)return null;for(const r of e){if(r.sessionId===t&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal";for(const n of r.childSessions||[])if(n.id===t&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal"}return null}function Ch(e,t){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,o]of Object.entries(e))xl(t,a)===o&&(delete n[a],r=!0);return r?n:e}function Th({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){i.useEffect(()=>{mc()},[]);const a=i.useMemo(()=>e.map(o=>({id:o.tabKey,name:Hc(o),status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null})),[e]);return vf(a),i.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{r(l=>{const d=Date.now(),f={};for(const[u,p]of Object.entries(l))d-p<5e3&&(f[u]=p);return Object.keys(f).length===Object.keys(l).length?l:f})},5500);return()=>clearTimeout(c)},[t,r]),i.useEffect(()=>{const o=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const d=l.filter(f=>f.timestamp>c).slice(-100);return d.length===l.length?l:d})},6e4);return()=>clearInterval(o)},[n]),null}function Mh(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=r.get(n.id);if(!a){r.set(n.id,n);continue}const o=(a.workspace?1:0)+(a.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>o||(n.timestamp||0)>(a.timestamp||0))&&r.set(n.id,n)}return Array.from(r.values())}function En(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function Ah(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function ii(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?Ah(Kt(r.content)):"";return[e.id||"",e.title||"",e.status||"",t.length,String((r==null?void 0:r.id)||""),String((r==null?void 0:r.index)??""),String((r==null?void 0:r.receivedAt)??(r==null?void 0:r.timestamp)??""),n].join(":")}function Ih(e){const t=Array.isArray(e.childSessions)?e.childSessions:[];return[e.id,e.sessionId||"",e.providerSessionId||"",e.transport||"",e.mode||"",e.status||"",e.workspace||"",e.lastMessageHash||"",String(e.lastMessageAt||""),e.lastMessagePreview||"",e.lastMessageRole||"",String(e.lastUpdated||""),ii(e.activeChat),...t.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastMessageAt||""),r.lastMessagePreview||"",r.lastMessageRole||"",String(r.lastUpdated||""),ii(r.activeChat)].join(":"))].join("|")}function Lh(e,t){const r=Date.now();return e.map(n=>{const a=t[n.tabKey];return a&&r-a<5e3?{...n,messages:[],title:""}:n})}function Rh(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const o of Ss({routeId:n.routeId}))r.set(o,a);for(const o of Ss({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(o,n.streamSource==="native"?a:n);for(const o of Ss({tabKey:n.tabKey}))r.set(o,n)}return r}function _h(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Ph(e){const t=_h(e);if(!t)return`empty:${e.messages.length}`;if(t.id)return`id:${String(t.id)}`;if(t._localId)return`local:${String(t._localId)}`;const r=String(t.role||""),n=Kt(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Dh({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=i.useMemo(()=>Mh(e),[e]),o=i.useMemo(()=>Xc(e),[e]),c=i.useRef([]),l=i.useRef([]),d=i.useRef([]),f=i.useRef(new Map),u=i.useRef(new Map),p=i.useMemo(()=>{const A=new Map,g=[];for(const w of a){const{connectionState:K="new",machineName:R}=Jc(w,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),S=Ih(w),O=f.current.get(w.id);if(O&&O.ide===w&&O.sourceSignature===S&&O.connectionState===K&&O.machineName===R){A.set(w.id,O),g.push(...O.conversations);continue}const H=no(w,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),P={ide:w,sourceSignature:S,connectionState:K,machineName:R,conversations:H};A.set(w.id,P),g.push(...H)}f.current=A;const M=new Map,T=w=>{const K=Ph(w),R=u.current.get(w.tabKey);if(R&&R.signature===K)return M.set(w.tabKey,R),R.timestamp;const S={signature:K,timestamp:Mc(w)||(R==null?void 0:R.timestamp)||0};return M.set(w.tabKey,S),S.timestamp},k=[...g].sort((w,K)=>Ac(w,K,T));return u.current=M,k},[a,t,o]),m=i.useMemo(()=>{const A=Lh(p,r);return En(c.current,A)?c.current:(c.current=A,A)},[p,r]),y=i.useMemo(()=>{const A=new Map,g=Array.from(new Set(m.map(M=>M.routeId)));for(const M of g){const T=Pt(m,M);T&&A.set(M,T)}return A},[m]),N=i.useMemo(()=>{const A=new Map;for(const g of m){const M=y.get(g.routeId),T=g.streamSource==="native"&&M?M:g;for(const k of Ss({providerSessionId:g.providerSessionId,sessionId:g.sessionId}))A.set(k,T)}return A},[m,y]),h=i.useMemo(()=>Rh(m,y),[m,y]),j=i.useCallback(A=>{if(A)return N.get(A)},[N]),x=i.useCallback(A=>{if(A)return h.get(A)},[h]),b=i.useMemo(()=>{const A=m.filter(g=>!lo(n,g));return En(l.current,A)?l.current:(l.current=A,A)},[m,n]),v=i.useMemo(()=>{const A=b.map(g=>g.tabKey);return En(d.current,A)?d.current:(d.current=A,A)},[b]);return{chatIdes:a,conversations:m,visibleConversations:b,visibleTabKeys:v,resolveConversationBySessionId:j,resolveConversationByTarget:x}}function Eh({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:r,setSearchParams:n}){const a=i.useMemo(()=>{var l;return e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),o=i.useMemo(()=>{var l;return!e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),c=i.useCallback(()=>{t&&n(l=>{const d=new URLSearchParams(l);return d.delete("activeTab"),d},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:o,consumeRequestedActiveTab:c}}function $h({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){i.useEffect(()=>{rt.setIdes(e)},[e]),i.useEffect(()=>{rt.setResolveAction((a,o,c)=>{t(a,o,c).catch(()=>{})})},[t]),i.useEffect(()=>{const a=rt.onToast(o=>{r(l=>l.some(f=>f.message===o.message&&o.timestamp-f.timestamp<3e3)?l:[...l.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const c=o.duration||5e3;setTimeout(()=>r(l=>l.filter(d=>d.id!==o.id)),c)});return()=>{a()}},[r]),i.useEffect(()=>{const a=Oc.on("status_event",o=>{rt.handleRawEvent(o,"ws")});return()=>{a()}},[]),i.useEffect(()=>{var o;const a=c=>{var h;const l=c.data;if((l==null?void 0:l.type)!=="notification_action"||typeof l.action!="string"||!l.action.startsWith("approval_")||!(l.daemonId||l.targetSessionId||l.targetKey))return;const d=l.targetSessionId||l.targetKey||l.daemonId,f=n(d),u=(f==null?void 0:f.routeId)||l.daemonId;if(!u)return;const p=Number(l.buttonIndex),m=l.button||((h=f==null?void 0:f.modalButtons)==null?void 0:h[p])||"Approve",y=String(m).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),N=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(y);t(u,"resolve_action",{action:N?"approve":"reject",button:m,...Number.isFinite(p)&&{buttonIndex:p},...(f==null?void 0:f.sessionId)&&{targetSessionId:f.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(j=>console.error("[SW Action] approval failed:",j))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",a),()=>{var c;return(c=navigator.serviceWorker)==null?void 0:c.removeEventListener("message",a)}},[n,t])}const Bh="adhdev_dashboardLayout_v1",Kh="adhdev_dashboardDockview_v1",Oh="adhdev_dashboardDockviewHiddenRestore_v1",Us={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function uo(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function Wh(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function bl(e){return`${Bh}:${e}`}function Fh(e){const t=bl(e);return uo(t,null)}function Hh(e,t){try{const r=t.groupAssignments.length===0&&t.focusedGroup===0&&Object.keys(t.groupActiveTabIds).length===0&&Object.keys(t.groupTabOrders).length===0&&t.groupSizes.length===0,n=bl(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function gl(e){return`${Kh}:${e}`}function Uh(e){const t=gl(e);return uo(t,null)}function zh(e,t){try{const r=gl(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function yl(e){return`${Oh}:${e}`}function Vh(e){const t=yl(e);return uo(t,{})}function Gh(e,t){try{const r=yl(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function qh(){return{groupAssignments:[...Us.groupAssignments],focusedGroup:Us.focusedGroup,groupActiveTabIds:{...Us.groupActiveTabIds},groupTabOrders:{...Us.groupTabOrders},groupSizes:[...Us.groupSizes]}}function Yh(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function Xh(){const[e]=i.useState(()=>Wh(typeof window<"u"?window.innerWidth:1280)),[t,r]=i.useState(()=>new Map),[n,a]=i.useState(0),[o,c]=i.useState({}),[l,d]=i.useState({}),[f,u]=i.useState([]),[p,m]=i.useState(()=>typeof window<"u"&&window.innerWidth<768),[y,N]=i.useState(!1),h=i.useCallback(()=>{if(y)return;const w=Fh(e)??qh();r(new Map(w.groupAssignments)),a(w.focusedGroup),c(w.groupActiveTabIds),d(w.groupTabOrders),u(w.groupSizes),N(!0)},[y,e]);i.useEffect(()=>{y&&Hh(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:l,groupSizes:f})},[y,e,t,n,o,l,f]),i.useEffect(()=>{const w=window.matchMedia("(max-width: 767px)"),K=R=>m(R.matches);return w.addEventListener("change",K),()=>w.removeEventListener("change",K)},[]);const j=i.useCallback(w=>{r(w)},[]),x=i.useCallback(w=>{a(w)},[]),b=i.useCallback(w=>{c(w)},[]),v=i.useCallback(w=>{d(w)},[]),A=i.useCallback(w=>{u(w)},[]),g=i.useCallback(w=>{x(w)},[x]),M=i.useCallback((w,K)=>{c(R=>(R[w]??null)===(K??null)?R:{...R,[w]:K})},[]),T=i.useCallback((w,K)=>{d(R=>{const S=R[w];return Yh(S,K)?R:{...R,[w]:K}})},[]),k=i.useCallback((w,K)=>{const R=K.get(w)??0;return M(R,w),g(R),R},[g,M]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:j,focusedGroup:n,updateFocusedGroup:x,focusGroup:g,groupActiveTabIds:o,updateGroupActiveTabIds:b,setGroupActiveTab:M,groupTabOrders:l,updateGroupTabOrders:v,setGroupTabOrder:T,groupSizes:f,updateGroupSizes:A,isMobile:p,hasHydratedStoredLayout:y,hydrateStoredLayout:h,focusConversationTab:k}}function Jh(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=Ga(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Qh({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:c,setSearchParams:l,historyModalOpen:d,activeConv:f,isRefreshingHistory:u,ides:p,handleRefreshHistory:m}){const y=i.useRef(!1),N=i.useRef(!1),h=i.useRef(null),j=i.useRef(!1);i.useEffect(()=>{if(!e||y.current||t.length===0)return;if(!a){o();return}const x=r(e);x&&(c(x.tabKey,n),y.current=!0,N.current=!0,h.current!=null&&(window.clearTimeout(h.current),h.current=null),l(b=>{const v=new URLSearchParams(b);return v.delete("activeTab"),v},{replace:!0}))},[e,t,r,n,a,o,c,l]),i.useEffect(()=>{if(!(N.current||a)&&t.length!==0){if(!e){o(),N.current=!0;return}if(y.current){N.current=!0;return}if(h.current==null)return h.current=window.setTimeout(()=>{h.current=null,!(N.current||a)&&(o(),N.current=!0)},1500),()=>{h.current!=null&&(window.clearTimeout(h.current),h.current=null)}}},[e,t.length,a,o]),i.useEffect(()=>{if(!d){j.current=!1;return}if(!f||j.current||u)return;const x=p.find(b=>b.id===f.routeId);x&&(!x.chats||x.chats.length===0||Jh(x.chats,f))&&(j.current=!0,m())},[d,f,u,p,m])}function $n(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0];if((r==null?void 0:r.active)===!0)return!0;const n=Ga(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function vl({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:o}){const[c,l]=i.useState(!1),[d,f]=i.useState(!1),u=i.useCallback(async N=>{try{await e("standalone","launch_ide",{ideType:N,enableCdp:!0})}catch(h){console.error("Launch failed",h)}},[e]),p=i.useCallback(async(N,h)=>{try{const j=N||(t==null?void 0:t.daemonId)||"",x=await e(j,"switch_chat",{id:h,sessionId:h,...ts(t)}),b=x==null?void 0:x.result;if((x==null?void 0:x.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?Ws(a,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?Ws(a,`⚠️ Switch error: ${b}`):Ws(a,"⚠️ Session switch failed")}catch(j){console.error("Switch failed",j),Ws(a,`❌ Switch failed: ${j.message||"connection error"}`)}},[t,e,a]),m=i.useCallback(async()=>{if(!(!t||c)){l(!0);try{const N=Ms(t);await e(N,"new_chat",{...ts(t)}),o(h=>({...h,[t.tabKey]:Date.now()}))}catch(N){console.error("New chat failed",N)}finally{l(!1)}}},[t,c,e,o]),y=i.useCallback(async()=>{var N,h;if(!(!t||d)){f(!0);try{const j=Ms(t),x=async()=>e(j,"list_chats",{forceExpand:!0,...ts(t)});let b=await x(),v=(b==null?void 0:b.chats)||((N=b==null?void 0:b.result)==null?void 0:N.chats);$n(v,t)&&(await new Promise(A=>setTimeout(A,450)),b=await x(),v=(b==null?void 0:b.chats)||((h=b==null?void 0:b.result)==null?void 0:h.chats)),b!=null&&b.success&&Array.isArray(v)&&(n(t.routeId,v),$n(v,t)&&!$n(r,t)&&Ws(a,"⚠️ History dialog did not fully open — try once more"))}catch(j){console.error("Refresh history failed",j)}finally{f(!1)}}},[t,r,d,e,n,a]);return{isCreatingChat:c,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:p,handleNewChat:m,handleRefreshHistory:y}}function Zh(e,t){if(e.size!==t.size)return!1;for(const[r,n]of e)if(t.get(r)!==n)return!1;return!0}function ex(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function ci(e,t){const r=Object.keys(e),n=Object.keys(t);return r.length!==n.length?!1:r.every(a=>t[Number(a)]===e[Number(a)])}function Mr(e,t){const r=new Set(t),n=t.length>0?[0]:[];for(const[c,l]of e)!r.has(c)||l<=0||n.includes(l)||n.push(l);n.sort((c,l)=>c-l);const a={};n.forEach((c,l)=>{a[c]=l}),n.length===0&&(a[0]=0);const o=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const d=a[l];typeof d=="number"&&d>0&&o.set(c,d)}return{assignments:o,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function li(e,t){const r={};for(const[n,a]of Object.entries(e)){const o=t[Number(n)];typeof o=="number"&&(r[o]=a)}return r}function tx(e,t,r){if(t.length===0)return 0;if(typeof r[e]=="number")return r[e];const n=[...t].reverse().find(a=>a<e)??t[0];return r[n]??0}function sx(e,t,r){if(t.length<=1)return[];const n=t.map(c=>e[c]).filter(c=>Number.isFinite(c)),a=n.length===t.length?n:Array(r).fill(100/r),o=a.reduce((c,l)=>c+l,0);return o>0?a.map(c=>c/o*100):Array(r).fill(100/r)}function di(e,t){const r={};for(const[n,a]of Object.entries(e)){const o=Number(n);r[o>=t?o+1:o]=a}return r}function ui(e){return Array(e).fill(100/e)}function rx({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:c,isMobile:l,visibleConversations:d,visibleTabKeys:f}){const u=i.useRef(null),p=i.useMemo(()=>Mr(e,f),[e,f]),m=p.assignments,y=i.useMemo(()=>l?1:p.groupCount,[p.groupCount,l]),N=y>1,h=i.useCallback((g,M)=>{t(T=>{const k=new Map(Mr(T,f).assignments);return M===0?k.delete(g):k.set(g,M),k}),n(T=>({...T,[M]:g})),r(M)},[t,f,n,r]),j=i.useCallback(g=>{t(M=>{const T=Mr(M,f).assignments,k=new Map;for(const[w,K]of T)K!==g&&(K>g?k.set(w,K-1):k.set(w,K));return k}),c(M=>{if(M.length<=1)return[];const T=[...M];T.splice(g,1);const k=T.reduce((w,K)=>w+K,0);return k>0?T.map(w=>w/k*100):[]}),r(0)},[t,f,c,r]),x=i.useCallback((g,M)=>{M.preventDefault();const T=u.current;if(!T)return;const k=M.clientX,w=T.offsetWidth,K=o.length===y?[...o]:ui(y),R=O=>{const P=(O.clientX-k)/w*100,C=[...K];C[g]=Math.max(15,K[g]+P),C[g+1]=Math.max(15,K[g+1]-P),c(C)},S=()=>{document.removeEventListener("mousemove",R),document.removeEventListener("mouseup",S),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",R),document.addEventListener("mouseup",S)},[o,y,c]),b=i.useCallback((g,M,T)=>{if(y>=4)return;const k=T==="left"?M:M+1;t(w=>{const K=Mr(w,f).assignments,R=new Map;for(const S of d){const O=K.get(S.tabKey)??0,H=O>=k?O+1:O;H>0&&R.set(S.tabKey,H)}return k>0&&R.set(g,k),R}),c(w=>{const K=w.length===y?[...w]:ui(y),R=K[M]??100/y,S=Math.max(15,R/2),O=Math.max(15,R/2),H=[...K];H[M]=S,H.splice(k,0,O);const P=H.reduce((C,I)=>C+I,0);return H.map(C=>C/P*100)}),n(w=>{const K=di(w,k);return K[k]=g,K}),a(w=>{const K=di(w,k);return K[k]=[g],K}),r(k)},[y,t,f,d,c,n,a,r]);i.useEffect(()=>{Zh(e,m)||t(m)},[e,m,t]),i.useEffect(()=>{const{mapping:g,usedGroups:M}=p;n(T=>{const k=li(T,g);return ci(T,k)?T:k}),a(T=>{const k=li(T,g);return ci(T,k)?T:k}),r(T=>{const k=l?0:tx(T,M,g);return T===k?T:k}),c(T=>{const k=l?[]:sx(T,M,p.groupCount);return ex(T,k)?T:k})},[p,l,n,a,r,c]);const v=i.useMemo(()=>{const g=Array.from({length:y},()=>[]);for(const M of d){const T=m.get(M.tabKey)??0,k=Math.min(T,y-1);g[k].push(M)}return g},[d,m,y]),A=i.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:u,normalizedGroupAssignments:m,numGroups:y,isSplitMode:N,groupedConvs:v,moveTabToGroup:h,closeGroup:j,handleResizeStart:x,splitTabRelative:b,clearAllSplits:A}}function nx({ides:e,sendDaemonCommand:t}){const r="0.9.60",n=i.useMemo(()=>e.filter(u=>u.type!=="adhdev-daemon"?!1:al(u,r)).sort((u,p)=>Number(Zs(p,r))-Number(Zs(u,r))),[r,e]),a=i.useMemo(()=>n.some(u=>Zs(u,r)),[r,n]),[o,c]=i.useState(!1),[l,d]=i.useState({}),f=i.useCallback(async u=>{var p,m;d(y=>({...y,[u]:"upgrading"}));try{const y=await t(u,"daemon_upgrade",{});(p=y==null?void 0:y.result)!=null&&p.upgraded||(m=y==null?void 0:y.result)!=null&&m.success?d(N=>({...N,[u]:"done"})):d(N=>({...N,[u]:"error"}))}catch{d(y=>({...y,[u]:"error"}))}},[t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:o,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:f}}const wl=80;function Or(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function ax(e){return{...e,createdAt:Or(e.createdAt),updatedAt:Or(e.updatedAt,e.createdAt),lastEventAt:Or(e.lastEventAt,e.updatedAt||e.createdAt)}}function ox(e){const t=qa(e);return t==="unknown:"?e.id:t}function ix(e){return[e.type,Tc(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function cx(e,t=wl){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=ox(n),o=r.get(a);if(!o){r.set(a,n);continue}(n.updatedAt>o.updatedAt||n.updatedAt===o.updatedAt&&n.createdAt>o.createdAt)&&r.set(a,n)}return Array.from(r.values()).sort((n,a)=>{const o=a.updatedAt-n.updatedAt;return o!==0?o:a.createdAt-n.createdAt}).slice(0,Math.max(0,t))}function lx(e,t){const r=Date.now(),n=[];for(const a of e){const o=a.sessionId?t.get(a.sessionId):void 0;if(o!=null&&o.surfaceHidden)continue;const c=dn(a,t),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const d=Or(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,r),f=ix({type:l,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(o==null?void 0:o.lastUpdated)||a.lastUpdated});n.push(ax({id:f,dedupKey:f,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:gc(a),preview:zf(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return cx(n)}function dx(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function ux(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=wl}=e,a=i.useMemo(()=>lx(t,r).slice(0,Math.max(0,n)),[t,r,n]),o=i.useMemo(()=>dx(a),[a]);return{notifications:a,unreadCount:o}}function fx({notifications:e,sendDaemonCommand:t}){const r=i.useCallback(o=>{const c=e.find(d=>d.id===o),l=Math.max(Date.now(),(c==null?void 0:c.updatedAt)||0);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_session_seen",{sessionId:c.sessionId,seenAt:l}).catch(()=>{})},[e,t]),n=i.useCallback(o=>{const c=e.find(l=>l.id===o);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_notification_unread",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]),a=i.useCallback(o=>{const c=e.find(l=>l.id===o);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"delete_notification",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}function pn(...e){const t=new Set,r=[],n=a=>{const o=typeof a=="string"?a.trim():"";if(!o)return;const c=o.toLowerCase();t.has(c)||(t.add(c),r.push(o))};for(const a of e){if(Array.isArray(a)){for(const o of a)n(o);continue}n(a)}return r}function mx(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const r=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),a=(r[2]||"").replace(/[\\/]+/g,"\\");return a?`${n}:\\${a}`:`${n}:\\`}return null}function hn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=mx(r);if(n)return n}return"C:\\"}for(const r of t){const n=typeof r=="string"?r.trim():"";if(n)return n}return"~"}function px(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const r=t.includes("\\")?"\\":"/",n=t.split(/[\\/]/);return/^[A-Za-z]:$/.test(n[0]||"")?n.length<=2?`${n[0]}\\`:n.slice(0,-1).join("\\"):n.length<=2?r:n.slice(0,-1).join(r)||r}function hx(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function xn(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=hx(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 o=typeof(a==null?void 0:a.path)=="string"?a.path:r,c=o.includes("\\")?"\\":"/",l=(f,u)=>/^[A-Za-z]:\\?$/.test(f)?`${f.replace(/\\?$/,"\\")}${u}`:f==="/"||f==="\\"?`${c}${u}`:`${f.replace(/[\\/]+$/,"")}${c}${u}`,d=Array.isArray(a==null?void 0:a.files)?a.files.filter(f=>(f==null?void 0:f.type)==="directory"&&typeof(f==null?void 0:f.name)=="string").map(f=>({name:f.name,path:typeof(f==null?void 0:f.path)=="string"&&f.path.trim()?f.path:l(o,f.name)})).sort((f,u)=>f.name.localeCompare(u.name)):[];return{path:o,directories:d}}function xx(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function fi(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function bx(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function gx({ides:e,conversations:t,onOpenSession:r}){const[n,a]=i.useState(null),o=i.useCallback(c=>{a(c)},[]);return i.useEffect(()=>{if(!n)return;const c=fi(n.workspacePath),l=e.find(f=>{var N,h,j,x;if(!f||f.type==="adhdev-daemon"||xx(f.daemonId||f.id)!==n.machineId||(or(f)?"cli":js(f)?"acp":"ide")!==n.kind||String(f.agentType||f.type||"")!==n.providerType)return!1;if(n.resumeSessionId)return String(f.providerSessionId||"")===n.resumeSessionId;if(c){const b=fi(f.workspace||f.runtimeWorkspaceLabel);return b?b===c:!1}return Number(f.lastUpdated||f._lastUpdate||f.timestamp||((x=(j=(h=(N=f.activeChat)==null?void 0:N.messages)==null?void 0:h.at)==null?void 0:j.call(h,-1))==null?void 0:x.timestamp)||0)>=n.startedAt-5e3});if(!l)return;const d=Ic({entrySessionId:l.sessionId,entryInstanceId:l.instanceId,entryRouteId:l.id,conversations:t});d&&(a(null),r(d))},[t,e,r,n]),i.useEffect(()=>{if(!n)return;const c=window.setTimeout(()=>{a(l=>!l||l.startedAt!==n.startedAt?l:null)},45e3);return()=>window.clearTimeout(c)},[n]),{trackPendingLaunch:o}}function yx({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:o}){const c=i.useCallback(async(m,y)=>xn(e,m,y),[e]),l=i.useCallback(async(m,y)=>{if(!y.trim())return{ok:!1,error:"Choose a workspace path first."};try{const N=await e(m,"workspace_add",{path:y.trim()});return N!=null&&N.success?{ok:!0}:{ok:!1,error:(N==null?void 0:N.error)||"Could not save workspace"}}catch(N){return{ok:!1,error:N instanceof Error?N.message:"Could not save workspace"}}},[e]),d=i.useCallback(async(m,y,N)=>{var h;try{const j={ideType:y,enableCdp:!0};(h=N==null?void 0:N.workspacePath)!=null&&h.trim()&&(j.workspace=N.workspacePath.trim());const x=await e(m,"launch_ide",j);return!(x!=null&&x.success)&&(x==null?void 0:x.success)!==void 0?{ok:!1,error:(x==null?void 0:x.error)||"Could not launch IDE"}:(t({machineId:m,kind:"ide",providerType:y,workspacePath:(N==null?void 0:N.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(j){return{ok:!1,error:j instanceof Error?j.message:"Could not launch IDE"}}},[e,t]),f=i.useCallback(async(m,y,N,h)=>{var x,b,v;const j=Date.now();try{const A={cliType:N};(x=h==null?void 0:h.workspacePath)!=null&&x.trim()?A.dir=h.workspacePath.trim():h!=null&&h.workspaceId&&(A.workspaceId=h.workspaceId),(b=h==null?void 0:h.resumeSessionId)!=null&&b.trim()&&(A.resumeSessionId=h.resumeSessionId.trim()),Array.isArray(h==null?void 0:h.cliArgs)&&h.cliArgs.length>0&&(A.cliArgs=h.cliArgs),(v=h==null?void 0:h.initialModel)!=null&&v.trim()&&(A.initialModel=h.initialModel.trim());const g=await e(m,"launch_cli",A),M=(g==null?void 0:g.result)||g,T=(M==null?void 0:M.sessionId)||(M==null?void 0:M.id);return g!=null&&g.success&&T?(r(T),{ok:!0}):g!=null&&g.success?(t({machineId:m,kind:y,providerType:N,workspacePath:(h==null?void 0:h.workspacePath)||null,resumeSessionId:(h==null?void 0:h.resumeSessionId)||null,startedAt:j}),{ok:!0}):{ok:!1,error:(g==null?void 0:g.error)||(M==null?void 0:M.error)||`Could not launch ${y.toUpperCase()} session`}}catch(A){return bx(A)?(t({machineId:m,kind:y,providerType:N,workspacePath:(h==null?void 0:h.workspacePath)||null,resumeSessionId:(h==null?void 0:h.resumeSessionId)||null,startedAt:j}),{ok:!0}):{ok:!1,error:A instanceof Error?A.message:`Could not launch ${y.toUpperCase()} session`}}},[r,e,t]),u=i.useCallback(async(m,y)=>{if(!m||!y)return[];try{const N=await e(m,"list_saved_sessions",{providerType:y,kind:"cli",limit:30}),h=(N==null?void 0:N.result)??N;return Array.isArray(h==null?void 0:h.sessions)?h.sessions:[]}catch(N){return console.error("List saved sessions failed",N),[]}},[e]),p=i.useCallback(async m=>{await hl({conversation:n,mode:m,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[n,a,e,o]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:l,handleLaunchMachineIde:d,handleLaunchMachineProvider:f,handleListMachineSavedSessions:u,setActiveCliViewMode:p}}function vx(e){switch(e){case"notification-open":case"toast-open":case"conversation-open":case"requested-tab":return!0;case"dockview-shortcut":case"dockview-focus":case"dockview-move":case"dockview-split":case"stored-layout-restore":case"passive-tab-sync":return!1;default:return!1}}function wx(e,t,r=Date.now()){return!e||!vx(t)?null:{tabKey:e,nonce:r}}function jx({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:o,setSearchParams:c}){const[l,d]=i.useState(null),[f,u]=i.useState(null),p=i.useMemo(()=>{var j,x;if(!e){if(l){const b=t.find(v=>v.tabKey===l);if(b)return b}return r[0]}const h=n[a];if(h){const b=t.find(v=>v.tabKey===h);if(b)return b}return((j=o[a])==null?void 0:j[0])||((x=o[0])==null?void 0:x[0])},[t,l,a,n,o,e,r]),m=i.useCallback(h=>{d(h)},[]),y=i.useCallback(h=>{d(h.tabKey),c(j=>{const x=new URLSearchParams(j),b=Gf(h);return b?x.set("activeTab",b):x.delete("activeTab"),x},{replace:!0})},[c]),N=i.useCallback((h,j)=>{const x=wx(h,j);x&&u(x)},[]);return{activeConv:p,openDesktopConversation:y,requestScrollToBottom:N,scrollToBottomRequest:f,setDesktopActiveTab:m}}function kx(e){const t=e.completedKey||null,r=e.pendingKey||null;return e.shouldMarkSeen?t===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:r===e.autoReadKey?r:null}:r===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:!1,nextPendingKey:r}:{shouldSchedule:!0,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:e.autoReadKey}:{shouldSchedule:!1,shouldCancelPending:!!r,nextPendingKey:null}}function Sx(e){const t=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,o=[e.tabKey,e.historySessionId||"",t,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&t&&t!==r),autoReadKey:o,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function Nx({activeConv:e,isMobile:t,liveSessionInboxState:r,sendDaemonCommand:n}){const a=i.useRef(null),o=i.useRef(null),c=i.useRef(null),l=i.useRef(null),d=i.useRef(null);i.useEffect(()=>{const f=()=>{c.current&&(clearTimeout(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),o.current=null};if(t){f(),a.current=null;return}if(!(e!=null&&e.sessionId)){f(),a.current=null;return}const u=Yr(e,r),p=Sx({tabKey:e.tabKey,historySessionId:ur(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:ss(e),liveState:u}),m=p.autoReadKey,y=kx({autoReadKey:m,shouldMarkSeen:p.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!p.shouldMarkSeen){y.shouldCancelPending&&f(),a.current=m;return}if(!y.shouldSchedule)return;y.shouldCancelPending&&f();const N=()=>{if(document.visibilityState!=="visible"||a.current===m)return;a.current=m,o.current=null,c.current=null,l.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const j=p.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:j,completionMarker:p.completionMarker}).catch(()=>{})};if(o.current=y.nextPendingKey,document.visibilityState==="visible"){c.current=setTimeout(N,1500);const j=()=>{document.visibilityState!=="visible"&&c.current&&(clearTimeout(c.current),c.current=null)};d.current=j,document.addEventListener("visibilitychange",j);return}const h=()=>{document.visibilityState==="visible"&&(l.current&&clearTimeout(l.current),l.current=setTimeout(N,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=h,document.addEventListener("visibilitychange",h)},[e,t,r,n]),i.useEffect(()=>()=>{c.current&&clearTimeout(c.current),l.current&&clearTimeout(l.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function Bn(e){if(!e)return"";const t=String(e.workspacePath||"").trim();if(t)return t;const r=String(e.workspaceName||"").trim();return/^(?:~\/|\/|[A-Za-z]:[\\/])/.test(r)?r:""}function Cx({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:o,setToasts:c,setClearedTabs:l,setSearchParams:d}){var I;const[f,u]=i.useState(!1),[p,m]=i.useState([]),[y,N]=i.useState(()=>xt()),[h,j]=i.useState(!1),[x,b]=i.useState(null),v=i.useRef(null),A=i.useMemo(()=>r||t||e,[e,r,t]),g=!!A&&et(A)&&!Xe(A),M=i.useMemo(()=>{if(!A||!g)return null;const W=A.daemonId||A.routeId||"",E=Bt(A),$=Bn(A);return`${W}:${E}:${A.providerSessionId||""}:${$}`},[A,g]),T=i.useMemo(()=>!A||!g?"":Bn(A),[A,g]),{isCreatingChat:k,isRefreshingHistory:w,handleSwitchSession:K,handleNewChat:R,handleRefreshHistory:S}=vl({sendDaemonCommand:a,activeConv:A,chats:(I=n.find(W=>W.id===(A==null?void 0:A.routeId)))==null?void 0:I.chats,updateRouteChats:o,setToasts:c,setClearedTabs:l}),O=i.useCallback(()=>{u(!0)},[]),H=i.useCallback(()=>{u(!1)},[]),P=i.useCallback(async()=>{if(!(!A||!g||h)){j(!0);try{const W=A.daemonId||A.routeId,E=Bt(A),$=Bn(A),z=await a(W,"list_saved_sessions",{agentType:E,providerType:E,kind:"cli",limit:50,...A.providerSessionId?{providerSessionId:A.providerSessionId}:{},...$?{workspace:$}:{}}),J=(z==null?void 0:z.result)??z;m(Array.isArray(J==null?void 0:J.sessions)?J.sessions:[])}catch(W){console.error("Refresh saved sessions failed",W),m([])}finally{j(!1)}}},[A,h,g,a]);i.useEffect(()=>{if(!f){v.current=null;return}if(!g){v.current=null,m([]),j(!1);return}!M||h||v.current!==M&&(v.current=M,P())},[P,f,h,g,M]);const C=i.useCallback(async W=>{if(!A||!g||!W.providerSessionId||!W.workspace)return;const E=A.daemonId||A.routeId,$=Bt(A);try{b(W.providerSessionId);const z=await a(E,"launch_cli",{cliType:$,dir:W.workspace,resumeSessionId:W.providerSessionId,initialModel:uc(W.summaryMetadata,"model",{preferShortValue:!0})||void 0}),J=(z==null?void 0:z.result)??z,he=typeof(J==null?void 0:J.sessionId)=="string"?J.sessionId:typeof(J==null?void 0:J.id)=="string"?J.id:"";he&&d(ce=>{const te=new URLSearchParams(ce);return te.set("activeTab",he),te},{replace:!0}),H()}catch(z){console.error("Resume saved session failed",z)}finally{b(null)}},[H,A,g,a,d]);return{historyModalOpen:f,openHistoryModal:O,closeHistoryModal:H,historyTargetConv:A,isSavedSessionHistoryTarget:g,isHistoryCreatingChat:k,isHistoryRefreshingHistory:w,handleHistorySwitchSession:K,handleHistoryNewChat:R,handleHistoryRefresh:S,savedHistorySessions:p,savedHistoryFilters:y,setSavedHistoryFilters:N,missingWorkspaceResumePath:T,isSavedHistoryLoading:h,resumingSavedHistorySessionId:x,handleRefreshSavedHistory:P,handleResumeSavedHistorySession:C}}function Tx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l}){const[d,f]=i.useState(null),[u,p]=i.useState(null),m=i.useMemo(()=>{if(e||!n)return null;const x=l(n);return x&&!et(x)&&!Xe(x)?x:null},[e,n,l]),y=i.useMemo(()=>{const x=d==null?void 0:d.routeId;if(!x)return null;const b=d!=null&&d.tabKey?o.find(v=>v.tabKey===d.tabKey):a?o.find(v=>v.tabKey===a):null;return(b==null?void 0:b.routeId)===x?b:Pt(o,x)},[o,d,a]),N=i.useMemo(()=>{if(y)return c.find(x=>x.id===y.routeId)},[c,y]);i.useEffect(()=>{m&&(f({routeId:m.routeId,tabKey:Ko(m)}),p(m),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,m]);const h=i.useCallback(x=>{x&&(f({routeId:x.routeId,tabKey:Ko(x)}),p(x))},[]),j=i.useCallback(()=>{f(null),p(null)},[]);return{remoteDialogConv:y,remoteDialogIdeEntry:N,remoteDialogActiveConv:u,setRemoteDialogActiveConv:p,openRemoteDialog:h,closeRemoteDialog:j}}function Mx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l,activeConv:d,sendDaemonCommand:f}){const{remoteDialogConv:u,remoteDialogIdeEntry:p,remoteDialogActiveConv:m,setRemoteDialogActiveConv:y,openRemoteDialog:N,closeRemoteDialog:h}=Tx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l}),[j,x]=i.useState(!1),[b,v]=i.useState(null),A=i.useCallback(async T=>{const k=T||d;!k||!et(k)&&!Xe(k)||(v(k),x(!0))},[d]),g=i.useCallback(()=>{x(!1),v(null)},[]),M=i.useCallback(async T=>{const k=b||d;if(!k||!et(k)&&!Xe(k)){g();return}x(!1);try{const w=Bt(k),K=k.routeId||k.daemonId||"";await f(K,"stop_cli",{cliType:w,targetSessionId:k.sessionId,mode:T})}catch(w){console.error("Stop CLI failed:",w)}finally{v(null)}},[d,g,b,f]);return{remoteDialogConv:u,remoteDialogIdeEntry:p,remoteDialogActiveConv:m,setRemoteDialogActiveConv:y,openRemoteDialog:N,closeRemoteDialog:h,cliStopDialogOpen:j,cliStopTargetConv:b,requestCliStop:A,cancelCliStop:g,confirmCliStop:M}}function Kn(e,t=!0){return(e??!0)&&t}const fo=i.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:o,handleModalButton:c,handleRelaunch:l,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u=null,handleFocusAgent:p,isFocusingAgent:m,actionLogs:y,userName:N,scrollToBottomRequestNonce:h,isInputActive:j=!0,isVisible:x=!0}){const b=n,v=!n,A=Kn(x,b),g=Kn(x,v),M=Kn(x),T=dl(t),k=T.status||T.modalMessage||T.modalButtons?{...t,...T.status?{status:T.status}:{},...T.modalMessage!==void 0?{modalMessage:T.modalMessage}:{},...T.modalButtons!==void 0?{modalButtons:T.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(ic,{activeConv:k,onModalButton:c}),k.transport!=="pty"&&k.transport!=="acp"&&k.cdpConnected===!1?s.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:s.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[s.jsx("span",{className:"text-sm",children:s.jsx(nr,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:l,children:"Relaunch with CDP"})]})}):null,k.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:b?"visible":"hidden",pointerEvents:b?"auto":"none"},children:s.jsx(fp,{activeConv:k,clearToken:r,terminalRef:o,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u,isVisible:A,isInputActive:j&&A})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:v?"visible":"hidden",pointerEvents:v?"auto":"none"},children:s.jsx(wa,{activeConv:k,ideEntry:a,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u,handleFocusAgent:p,isFocusingAgent:m,actionLogs:y,userName:N,scrollToBottomRequestNonce:h,isInputActive:j&&g,isVisible:g})})]}):s.jsx(wa,{activeConv:k,ideEntry:a,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u,handleFocusAgent:p,isFocusingAgent:m,actionLogs:y,userName:N,scrollToBottomRequestNonce:h,isInputActive:j&&M,isVisible:M})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function Ax({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:o,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:d,onBack:f,onOpenNativeConversation:u,onOpenMachine:p,onOpenHistory:m,onOpenRemote:y,onHideConversation:N,onStopCli:h,cliViewMode:j,onSetCliViewMode:x,handleSendChat:b,handleFocusAgent:v,handleModalButton:A,handleRelaunch:g}){const M=i.useRef(null),T=et(e)&&!t,k=T&&j==="terminal",w=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${w} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:f,type:"button","aria-label":"Back",children:s.jsx(_a,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:it(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(Lc,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>p(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[T&&j&&s.jsx(Qa,{mode:j,onChange:x,compact:!0}),T&&h&&s.jsx("button",{onClick:()=>{h(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(St,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>m(e),type:"button",children:s.jsx(Pa,{size:14})}),!t&&!T&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>y(e),type:"button",children:s.jsx(Tt,{size:14})}),N&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>N(e),type:"button",title:"Close chat",children:s.jsx(St,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(fo,{activeConv:e,clearToken:0,isCliTerminal:k,ideEntry:n,terminalRef:M,handleModalButton:A,handleRelaunch:g,handleSendChat:b,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:v,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const On={unix:{cmd:"curl -fsSL https://adhf.dev/install | sh",shell:"Terminal",prompt:"$ "},powershell:{cmd:"irm https://adhf.dev/install.ps1 | iex",shell:"PowerShell",prompt:"PS> "},cmd:{cmd:"curl -fsSL https://adhf.dev/install.cmd -o %TEMP%\\adhdev.cmd && %TEMP%\\adhdev.cmd",shell:"CMD",prompt:"> "}};function Ix(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function jl(){const[e,t]=i.useState("unix"),[r,n]=i.useState("powershell"),[a,o]=i.useState(!1),c=e==="unix"?"unix":r;i.useEffect(()=>{t(Ix())},[]);const l=i.useCallback(()=>{navigator.clipboard.writeText(On[c].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!1),2e3)},[c]);return s.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("unix"),children:"🍎🐧 macOS / Linux"}),s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("windows"),children:"🪟 Windows"})]}),e==="windows"&&s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("powershell"),children:"⚡ PowerShell"}),s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("cmd"),children:">_ CMD"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:l,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:On[c].prompt}),s.jsx("span",{className:"flex-1 break-all",children:On[c].cmd}),s.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:a?"✓":"📋"})]}),s.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",s.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function kl({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Tt},{key:"chats",label:"Chats",icon:Ut}];return s.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:s.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:n,label:a,icon:o})=>{const c=e===n;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${c?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(n),type:"button","aria-pressed":c,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(o,{size:15})}),s.jsx("span",{children:a})]},n)})})})}function Ar({title:e,className:t=""}){return s.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${t}`,children:s.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function gs({children:e,className:t=""}){return s.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${t}`,children:e})}function zs({icon:e,title:t,subtitle:r,children:n}){return s.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[s.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function Ir({item:e,type:t,getAvatarText:r,onOpenConversation:n,onHideConversation:a,onCollectChatDebugBundle:o}){const c=t==="needs_attention"||t==="task_complete",l=t==="working",d=t==="earlier",f=t==="task_complete",{isReconnecting:u,isConnecting:p}=Ds(e.conversation),m=it(e.conversation),y=As(e.conversation),N=Fc(e.conversation,{requiresAction:t==="needs_attention"}),h=c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":l?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":d?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",j=c?"bg-accent-primary shadow-glow":l?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":d?"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",x=d?"text-text-secondary":"text-text-primary",b=d?"text-text-muted":"text-text-secondary",v=d?"text-text-secondary opacity-80":"text-text-muted",A=d?"text-text-muted opacity-80":"text-text-muted",g=!l&&!f,M="text-[color:var(--status-warning)]",T=k=>{if(!o)return;k.preventDefault(),k.stopPropagation();const w=o==null?void 0:o(e.conversation);Promise.resolve(w).catch(K=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",K)})};return s.jsxs("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${h}`,children:[s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left relative ${a?"pb-2":""}`,onClick:()=>n(e.conversation),onContextMenu:T,type:"button",children:[c||l?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${j}`,style:c?{color:"var(--accent-on-primary)"}:void 0,children:r(m)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${x}`,children:m}),g&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${A}`,children:oc(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${b}`,children:[s.jsx("span",{className:"truncate",children:y}),s.jsx(Is,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),u?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${M} animate-pulse`,children:"Reconnecting…"})]}):p?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):N==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:M,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${v}`,children:e.preview})]}),c&&!f&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),f&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Done"}),l&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Live"})]}),a&&s.jsx("div",{className:"flex justify-end px-4 pb-3 -mt-1",children:s.jsxs("button",{type:"button",className:"mobile-inbox-hide-button inline-flex items-center gap-1.5 rounded-full border border-border-subtle bg-bg-primary/70 px-2.5 py-1 text-[11px] font-semibold text-text-muted hover:border-border-default hover:text-text-primary",onClick:k=>{k.preventDefault(),k.stopPropagation(),a(e.conversation)},"aria-label":`Hide ${m}`,title:"Hide conversation",children:[s.jsx(Da,{size:12}),s.jsx("span",{children:"Hide"})]})})]},e.conversation.tabKey)}function mi({size:e=32}){return s.jsx("div",{className:"flex flex-col items-center gap-2.5",children:s.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}})})}function Lx({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:o,machineCards:c,getAvatarText:l,actionLogs:d,sendDaemonCommand:f,onOpenConversation:u,onShowAllHidden:p,onHideConversation:m,onOpenNewSession:y,onOpenMachine:N,onOpenSettings:h,onSectionChange:j,wsStatus:x="connected",isStandalone:b=!1,onCollectChatDebugBundle:v}){const A=x==="disconnected"||x==="reconnecting"||x==="offline"||x==="auth_failed",g=c.length>0,M=t.length>0||r.length>0||n.length>0||a.length>0,T=e==="machines"?"Machines":"Chats",k=b?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",w=b?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",K=i.useCallback(async S=>{const O=Ms(S);if(!O)return;const H=Array.isArray(S.messages)?S.messages:[],P=kc({activeConv:S,visibleMessages:H,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:H.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),C=await f(O,"get_chat_debug_bundle",{...ts(S),delivery:"daemon_file",frontendSnapshot:P}),I=Qr(C),W=Cc(I),E=await Nc(W);E==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),rt.showToast(Sc(I,{locatorCopyStatus:E}),E==="failed"?"warning":"success")},[d,f]),R=v||K;return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${k}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:T}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||r.length>0)&&s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[s.jsx(cn,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:h,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:s.jsx(on,{size:18})})]})]})}),s.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${w}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:A?s.jsx(zs,{icon:s.jsx(mi,{}),title:x==="offline"?"Network offline":x==="auth_failed"?"Session expired":"Reconnecting",subtitle:x==="offline"?"Waiting for network…":x==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):c.length===0?s.jsx(zs,{icon:s.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&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(jl,{})})}):s.jsx(gs,{children:c.map((S,O)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${O>0?"border-t border-border-subtle/70":""}`,onClick:()=>N(S.id),type:"button",children:[s.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:l(S.label)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:S.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:S.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[S.unread," new"]}):S.total>0?`${S.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:S.subtitle}),S.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[S.total," chat",S.total!==1?"s":"",S.unread>0?` · ${S.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},S.id))})}),e==="chats"&&t.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(Ar,{title:"Needs attention",className:"mb-0"}),s.jsx(gs,{children:t.map((S,O)=>s.jsx("div",{className:O>0?"border-t border-border-subtle/70":"",children:s.jsx(Ir,{item:S,type:"needs_attention",getAvatarText:l,onOpenConversation:u,onHideConversation:m,onCollectChatDebugBundle:R})},S.conversation.tabKey))})]}),e==="chats"&&r.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(Ar,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(gs,{children:r.map((S,O)=>s.jsx("div",{className:O>0?"border-t border-border-subtle/70":"",children:s.jsx(Ir,{item:S,type:"task_complete",getAvatarText:l,onOpenConversation:u,onHideConversation:m,onCollectChatDebugBundle:R})},S.conversation.tabKey))})]}),e==="chats"&&n.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(Ar,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(gs,{children:n.map((S,O)=>s.jsx("div",{className:O>0?"border-t border-border-subtle/70":"",children:s.jsx(Ir,{item:S,type:"working",getAvatarText:l,onOpenConversation:u,onHideConversation:m,onCollectChatDebugBundle:R})},S.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&s.jsx(Ar,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(gs,{children:a.map((S,O)=>s.jsx("div",{className:O>0?"border-t border-border-subtle/70":"",children:s.jsx(Ir,{item:S,type:"earlier",getAvatarText:l,onOpenConversation:u,onHideConversation:m,onCollectChatDebugBundle:R})},S.conversation.tabKey))}):M?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):A?s.jsx(zs,{icon:s.jsx(mi,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):g?s.jsx(zs,{icon:s.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:s.jsx(Ut,{size:20})}),title:"No conversations yet",subtitle:zc,children:y&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:y,"aria-label":Et,title:Et,children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s.jsx("span",{children:Et})]})}):s.jsx(zs,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),e==="chats"&&o.length>0&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(gs,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:"Hidden tabs"}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[o.length," collapsed ",o.length===1?"conversation":"conversations"]})]}),s.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-[12px] font-semibold text-accent-primary hover:border-border-default",onClick:p,children:"Restore all"})]})})})]}),e==="chats"&&y&&M&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:y,"aria-label":Et,title:Et,children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),s.jsx(kl,{section:e,onSectionChange:j})]})}function Rx(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 Sl(e){const t=[e.workspace||"Workspace unknown"],r=fs(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=Rx(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function bn({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:o="",confirmLabel:c="Use this folder",onClose:l,onNavigate:d,onConfirm:f}){const[u,p]=i.useState(r);i.useEffect(()=>{p(r)},[r]);const m=px(r),y=u.trim();return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:l,"aria-label":"Close folder browser",children:s.jsx(St,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!m||a||d(m)},disabled:!m||a,children:[s.jsx(_a,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:N=>p(N.target.value),onKeyDown:N=>{N.key!=="Enter"||!y||a||(N.preventDefault(),d(y))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!y||a||d(y)},disabled:!y||a,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):n.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:n.map(N=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>d(N.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Cs,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:N.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:N.path})]})]},N.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>f(y||r),disabled:!y&&!r||a,children:c})]})]})})}function mo({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:d=!1,showArgsInput:f,argsValue:u,onArgsChange:p,showModelInput:m,modelValue:y,onModelChange:N,historyProviderNode:h,onConfirm:j,onCancel:x}){const b=n==null?void 0:n.find(v=>v.key===a);return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:x,"aria-label":"Close launch confirmation",children:s.jsx(St,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[n&&n.length>0&&o&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),s.jsx("select",{value:a||"",onChange:v=>o(v.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:d,children:n.map(v=>s.jsx("option",{value:v.key,children:v.label},v.key))}),(b==null?void 0:b.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:b.description})]}),h,r.map(v=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:v.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:v.value})]},`${v.label}:${v.value}`)),m&&N&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),s.jsx("input",{type:"text",value:y||"",onChange:v=>N(v.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:d})]}),f&&p&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:u||"",onChange:v=>p(v.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:d})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:x,disabled:d,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:j,disabled:d,children:[s.jsx($a,{size:14}),d?l:c]})]})]})})}function pi(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function cs(e){const{machine:t,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,o=[];a&&o.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const d of t.workspaces||[])o.push({key:`saved:${d.id}`,label:`${d.id===t.defaultWorkspaceId?"⭐ ":""}${pi(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const c=(r==null?void 0:r.trim())||"",l=c?(t.workspaces||[]).find(d=>d.path===c):null;if(c&&!l&&o.push({key:`custom:${c}`,label:pi(c),description:c,workspaceId:null,workspacePath:c}),n){const d=`saved:${n}`;if(o.some(f=>f.key===d))return{options:o,selectedKey:d}}return l?{options:o,selectedKey:`saved:${l.id}`}:c?{options:o,selectedKey:`custom:${c}`}:{options:o,selectedKey:"__home__"}}function _x(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Px(e){return[_x(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Dx(e){return e.lastLaunchedAt?ln(e.lastLaunchedAt):""}function Nl(e){return{metaText:Px(e),updatedLabel:Dx(e)}}function Wn(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function Ex({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:o}){var Qe,lt,dt,ut;const c=fr(),[l,d]=i.useState(!1),f=(((Qe=e.detectedIdes)==null?void 0:Qe.length)||0)>0,u=i.useMemo(()=>(e.workspaces||[]).map(Te=>({id:Te.id,path:Te.path,label:Te.label})),[e]),p=e.defaultWorkspaceId||null,[m,y]=i.useState(p||((lt=u[0])==null?void 0:lt.id)||""),[N,h]=i.useState(""),[j,x]=i.useState(""),[b,v]=i.useState([]),[A,g]=i.useState(!1),[M,T]=i.useState(""),[k,w]=i.useState(!1),[K,R]=i.useState(Wn(f,t.length,r.length)),S=i.useRef(null),[O,H]=i.useState(null),P=i.useRef("__home__"),[C,I]=i.useState("__home__"),[W,E]=i.useState(""),[$,z]=i.useState(""),[J,he]=i.useState(""),[ce,te]=i.useState([]),[ye,fe]=i.useState(()=>xt().textQuery),[be,X]=i.useState(()=>xt().workspaceQuery),[ae,ge]=i.useState(()=>xt().modelQuery),[ee,de]=i.useState(()=>xt().resumableOnly),[we,ue]=i.useState(()=>xt().sortMode),[xe,se]=i.useState(!1),[ie,re]=i.useState(!1),q=i.useRef(null),Y=i.useRef(null);i.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const le=m==="__custom__"?N.trim():((dt=u.find(Te=>Te.id===m))==null?void 0:dt.path)||"",ke=m==="__custom__"&&!!le&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),Z=m!=="__custom__"&&((ut=u.find(Te=>Te.id===m))==null?void 0:ut.path)||"",Ce=i.useMemo(()=>(e.recentLaunches||[]).map(Te=>Te.workspace),[e]),Ee=i.useCallback(async Te=>{g(!0),T("");try{const Ge=await a(Te);x(Ge.path),h(Ge.path),v(Ge.directories)}catch(Ge){T(Ge instanceof Error?Ge.message:"Could not load folder")}finally{g(!1)}},[a]),We=i.useCallback(()=>{var Ge;y("__custom__"),w(!0);const Te=hn(e.platform,pn(N.trim(),Z,Ce,e.defaultWorkspacePath,(Ge=u.find(Ze=>Ze.id===p))==null?void 0:Ge.path,u.map(Ze=>Ze.path)));Ee(Te)},[N,p,Ee,Ce,Z,e.platform,u]),Fe=i.useCallback(Te=>{if(Te!=null&&Te.workspaceId){y(Te.workspaceId),h("");return}if(Te!=null&&Te.workspacePath){y("__custom__"),h(Te.workspacePath);return}y(""),h("")},[]),D=i.useCallback(Te=>{if(y(Te),Te==="__custom__"){We();return}h("")},[We]),Se=i.useCallback(Te=>{y("__custom__"),h(Te)},[]),Ae=i.useCallback((Te,Ge)=>{S.current=Ge,P.current=Te.selectedWorkspaceKey||"__home__",I(Te.selectedWorkspaceKey||"__home__"),E(Te.initialArgs||""),z(Te.initialModel||""),he(""),te([]);const Ze=Te.providerType?`${e.id}:${Te.providerType}`:null;if(kp(Y.current,Ze)){const qe=xt();fe(qe.textQuery),X(qe.workspaceQuery),ge(qe.modelQuery),de(qe.resumableOnly),ue(qe.sortMode)}Y.current=Ze,H(Te),Te.providerType&&o&&(se(!0),o(Te.providerType).then(qe=>te(qe||[])).catch(qe=>console.warn("Failed to load saved sessions",qe)).finally(()=>se(!1)))},[o,e.id]),Le=i.useMemo(()=>Vc(ce,{textQuery:ye,workspaceQuery:be,modelQuery:ae,resumableOnly:ee,sortMode:we}),[ae,ee,ce,we,ye,be]);i.useEffect(()=>{J&&(Le.some(Te=>Te.providerSessionId===J)||he(""))},[Le,J]);const Pe=i.useCallback(()=>{S.current&&(re(!0),S.current().finally(()=>{S.current=null,re(!1),H(null)}))},[]),He=i.useCallback(()=>{S.current=null,H(null)},[]),Ue=i.useCallback(Te=>{P.current=Te,I(Te)},[]);return i.useEffect(()=>{var Te;q.current!==e.id&&(q.current=e.id,y(p||((Te=u[0])==null?void 0:Te.id)||"__custom__"),h(""),x(""),v([]),T(""),w(!1),fe(xt().textQuery),X(xt().workspaceQuery),ge(xt().modelQuery),de(xt().resumableOnly),ue(xt().sortMode),Y.current=null,R(Wn(f,t.length,r.length)))},[r.length,t.length,p,f,e.id,u]),i.useEffect(()=>{var Te;m!=="__custom__"&&(m&&u.some(Ge=>Ge.id===m)||y(p||((Te=u[0])==null?void 0:Te.id)||"__custom__"))},[p,m,u]),i.useEffect(()=>{K==="ide"&&f||K==="cli"&&t.length>0||K==="acp"&&r.length>0||R(Wn(f,t.length,r.length))},[K,r.length,t.length,f]),{showAllRecent:l,setShowAllRecent:d,hasIdeOptions:f,workspaceRows:u,defaultWorkspaceId:p,workspaceChoice:m,customWorkspacePath:N,browseCurrentPath:j,browseDirectories:b,browseBusy:A,browseError:M,browseDialogOpen:k,activeLauncherKind:K,launchConfirm:O,launchConfirmWorkspaceKeyRef:P,launchConfirmWorkspaceKey:C,launchConfirmArgs:W,launchConfirmModel:$,launchConfirmResumeId:J,launchConfirmSavedSessions:ce,launchConfirmTextFilter:ye,launchConfirmWorkspaceFilter:be,launchConfirmModelFilter:ae,launchConfirmResumableOnly:ee,launchConfirmSortMode:we,filteredLaunchConfirmSavedSessions:Le,launchConfirmSessionsLoading:xe,launchConfirmBusy:ie,resolvedWorkspacePath:le,canCreateMissingWorkspace:ke,openBrowseDialog:We,loadBrowsePath:Ee,handleWorkspaceChoiceChange:D,chooseCustomWorkspacePath:Se,setCustomWorkspacePath:h,setBrowseDialogOpen:w,setActiveLauncherKind:R,openLaunchConfirm:Ae,handleConfirmLaunch:Pe,closeLaunchConfirm:He,setWorkspaceSelectionFromOption:Fe,setLaunchConfirmWorkspaceKeyAndSync:Ue,setLaunchConfirmArgs:E,setLaunchConfirmModel:z,setLaunchConfirmResumeId:he,setLaunchConfirmTextFilter:fe,setLaunchConfirmWorkspaceFilter:X,setLaunchConfirmModelFilter:ge,setLaunchConfirmResumableOnly:de,setLaunchConfirmSortMode:ue}}function $x({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:c,machineAction:l,isStandalone:d,section:f,showBottomNav:u,onBack:p,onSectionChange:m,onOpenConversation:y,onOpenRecent:N,onOpenMachineDetails:h,onMachineUpgrade:j,onLaunchDetectedIde:x,onAddWorkspace:b,onBrowseDirectory:v,onLaunchWorkspaceProvider:A,onListSavedSessions:g}){const M=C=>C==="ide"?"IDE":C==="cli"?"CLI":"ACP",T=r.slice(0,4),k=t.slice(0,3),w=Ex({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:v,onListSavedSessions:g}),K=i.useMemo(()=>T.map(C=>{const{metaText:I,updatedLabel:W}=Nl(C);return{key:`recent-launch:${C.id}`,primary:C.label,secondary:I,updatedLabel:W,onClick:()=>{const{options:E,selectedKey:$}=cs({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspacePath:C.workspace});w.openLaunchConfirm({title:C.kind==="ide"?ns("restart-ide",C.label):C.providerSessionId?to(C.label):ns("start-fresh",C.label),description:C.kind==="ide"?as("restart-ide"):C.providerSessionId?so():as("start-fresh"),confirmLabel:C.kind==="ide"?Ls("restart-ide"):C.providerSessionId?tn(!0):Ls("start-fresh"),busyLabel:C.kind==="ide"?Rs("restart-ide"):C.providerSessionId?Za(!0):Rs("start-fresh"),workspaceOptions:E,selectedWorkspaceKey:$,details:[{label:"Mode",value:M(C.kind)},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]},async()=>{const z=E.find(J=>J.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(z),await N({...C,workspace:(z==null?void 0:z.workspacePath)??null})})}}}),[w,N,T]),R=i.useMemo(()=>k.map(C=>({key:`recent-chat:${C.conversation.tabKey}`,primary:it(C.conversation),secondary:cp(C.conversation,{timestampLabel:C.timestamp?oc(C.timestamp):null}),unread:C.unread,onClick:()=>y(C.conversation)})),[y,k]),S=w.showAllRecent?K:K.slice(0,4),O=K.length>0,H=R.length>0,P=d?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${P} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:s.jsx(_a,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:Ct(e,{fallbackId:e.id})}),s.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[H&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:R.map(C=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${C.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:C.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))})]}),O&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:S.map(C=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:C.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:C.primary}),C.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:C.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))}),K.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>w.setShowAllRecent(C=>!C),children:w.showAllRecent?"Show fewer":`Show ${K.length-4} more`})})]}),(w.hasIdeOptions||n.length>0||a.length>0)&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:s.jsxs("div",{className:"flex flex-col gap-2.5 w-full p-3.5 rounded-2xl border border-border-default/80 bg-surface-primary/90",children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),s.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),s.jsx("select",{value:w.workspaceChoice,onChange:C=>w.handleWorkspaceChoiceChange(C.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:w.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[w.workspaceRows.map(C=>s.jsxs("option",{value:C.id,children:[C.id===w.defaultWorkspaceId?"⭐ ":"",un(C.path,C.label)||C.path]},C.id)),s.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):s.jsx("option",{value:"__custom__",children:"Select workspace…"})}),w.workspaceChoice==="__custom__"&&s.jsxs("div",{className:"flex flex-col gap-2.5",children:[s.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Cs,{size:17})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),s.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:w.resolvedWorkspacePath||w.browseCurrentPath||"No folder selected yet."})]})]})}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-secondary text-[12px] font-bold",onClick:w.openBrowseDialog,children:"Select workspace…"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-accent-primary/30 bg-accent-primary/10 text-text-primary text-[12px] font-bold disabled:opacity-40",onClick:()=>{w.resolvedWorkspacePath&&b(w.resolvedWorkspacePath)},disabled:!w.resolvedWorkspacePath||w.browseBusy,children:"Save as workspace"})]})]}),w.resolvedWorkspacePath&&s.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:w.resolvedWorkspacePath})]})}),s.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[w.hasIdeOptions&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${w.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:()=>w.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${w.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:()=>w.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${w.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:()=>w.setActiveLauncherKind("acp"),children:"ACP"})]}),w.activeLauncherKind&&s.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[s.jsx("div",{className:"text-xs font-bold text-text-secondary",children:w.activeLauncherKind==="ide"?"Choose an IDE":w.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),s.jsx("div",{className:"grid grid-cols-1 gap-2",children:w.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(C=>s.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const{options:I,selectedKey:W}=cs({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspaceId:w.workspaceChoice!=="__custom__"?w.workspaceChoice:null,currentWorkspacePath:w.resolvedWorkspacePath});w.openLaunchConfirm({title:`Launch ${C.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:I,selectedWorkspaceKey:W,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:C.name}]},async()=>{const E=I.find($=>$.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(E),x(C.type,{workspacePath:(E==null?void 0:E.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:C.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:w.resolvedWorkspacePath||"Use selected workspace"})]},C.type)):(w.activeLauncherKind==="cli"?n:a).map(C=>s.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const I=w.activeLauncherKind==="cli"?"cli":"acp",{options:W,selectedKey:E}=cs({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspaceId:w.workspaceChoice!=="__custom__"?w.workspaceChoice:null,currentWorkspacePath:w.resolvedWorkspacePath});w.openLaunchConfirm({title:`Launch ${C.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${I.toUpperCase()}`,workspaceOptions:W,selectedWorkspaceKey:E,details:[{label:"Mode",value:I.toUpperCase()},{label:"Provider",value:C.displayName}],showArgsInput:!0,showModelInput:I==="acp",initialArgs:"",initialModel:"",providerType:C.type},async()=>{const $=W.find(z=>z.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption($),A(I,C.type,{workspaceId:($==null?void 0:$.workspaceId)??null,workspacePath:($==null?void 0:$.workspacePath)??null,args:w.launchConfirmArgs,model:w.launchConfirmModel,resumeSessionId:w.launchConfirmResumeId||null})})},children:[s.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[C.icon?`${C.icon} `:"",C.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:w.resolvedWorkspacePath||"Use selected workspace"})]},C.type))})]}),l.message&&s.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${l.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[l.message,w.canCreateMissingWorkspace&&s.jsx("div",{className:"mt-2",children:s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[34px] px-4 rounded-lg bg-surface-primary text-text-primary font-bold text-xs",onClick:()=>b(w.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:j,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:h,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),w.browseDialogOpen&&s.jsx(bn,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:w.browseCurrentPath,directories:w.browseDirectories,busy:w.browseBusy,error:w.browseError,confirmLabel:"Use this folder",onClose:()=>w.setBrowseDialogOpen(!1),onNavigate:C=>{w.loadBrowsePath(C)},onConfirm:C=>{w.chooseCustomWorkspacePath(C),w.setBrowseDialogOpen(!1)}}),w.launchConfirm&&s.jsx(mo,{title:w.launchConfirm.title,description:w.launchConfirm.description,details:w.launchConfirm.details,workspaceOptions:w.launchConfirm.workspaceOptions,selectedWorkspaceKey:w.launchConfirmWorkspaceKey,onWorkspaceChange:w.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:w.launchConfirm.providerType?tn(!!w.launchConfirmResumeId):w.launchConfirm.confirmLabel,busyLabel:w.launchConfirm.providerType?void 0:w.launchConfirm.busyLabel,busy:w.launchConfirmBusy,showArgsInput:w.launchConfirm.showArgsInput,argsValue:w.launchConfirmArgs,onArgsChange:w.setLaunchConfirmArgs,showModelInput:w.launchConfirm.showModelInput,modelValue:w.launchConfirmModel,onModelChange:w.setLaunchConfirmModel,historyProviderNode:w.launchConfirm.providerType&&(w.launchConfirmSessionsLoading||w.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),w.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:eo()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:w.launchConfirmTextFilter,onChange:C=>w.setLaunchConfirmTextFilter(C.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:w.launchConfirmWorkspaceFilter,onChange:C=>w.setLaunchConfirmWorkspaceFilter(C.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:w.launchConfirmModelFilter,onChange:C=>w.setLaunchConfirmModelFilter(C.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),s.jsxs("select",{value:w.launchConfirmSortMode,onChange:C=>w.setLaunchConfirmSortMode(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:w.launchConfirmResumableOnly,onChange:C=>w.setLaunchConfirmResumableOnly(C.target.checked),disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:w.launchConfirmResumeId,onChange:C=>w.setLaunchConfirmResumeId(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Cp()}),w.filteredLaunchConfirmSavedSessions.map(C=>s.jsxs("option",{value:C.providerSessionId,disabled:!C.canResume,children:[C.title||C.providerSessionId," ",C.canResume?"":"(workspace missing)"]},C.providerSessionId))]}),!w.launchConfirmSessionsLoading&&w.launchConfirmSavedSessions.length>0&&w.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),w.launchConfirmResumeId&&(()=>{const C=w.filteredLaunchConfirmSavedSessions.find(W=>W.providerSessionId===w.launchConfirmResumeId);if(!C)return null;const I=Sl(C);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:I.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:I.providerSessionId}),s.jsx("div",{className:"mt-1",children:I.metaLine}),I.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:I.updatedLabel}),I.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:I.preview})]})})()]}),onConfirm:w.handleConfirmLaunch,onCancel:w.closeLaunchConfirm}),u&&s.jsx(kl,{section:f,onSectionChange:m})]})}function Wr(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Bx(e,t=[]){const r=new Map(e.map(a=>[a.conversation.tabKey,a])),n=t.map(a=>r.get(a)).filter(a=>!!a);return n.length===e.length?n:Wr(e)}function Kx(e){var r;const t=((r=e.p2p)==null?void 0:r.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":"Offline"}function Ox(e,t){if(!e)return[];const r=e.recentLaunches||[];return r.length>0?r.map(n=>({id:n.id,label:n.title||n.providerName||n.providerType,kind:n.kind,providerType:n.providerType,providerSessionId:n.providerSessionId,subtitle:fs(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):t.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var c,l,d,f,u;const a=or(n)?"cli":js(n)?"acp":"ide",o=fs(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(or(n)?n.cliName||n.type:js(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:js(n)?o||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((u=(f=(d=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:d.at)==null?void 0:f.call(d,-1))==null?void 0:u.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function Wx(e,t){const r=new Map;for(const n of t){const a=xs(n.conversation),o=r.get(a);o?o.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],o=[...a].sort((p,m)=>m.timestamp-p.timestamp)[0]||null,c=(o==null?void 0:o.conversation)||null,l=fa(n),d=a.filter(p=>p.unread||p.requiresAction).length,f=Kx(n),u=[n.platform||"machine",f].filter(Boolean);return{id:n.id,label:Ct(n,{fallbackId:n.id}),subtitle:u.join(" · "),unread:d,total:a.length,latestConversation:c,latestTimestamp:(o==null?void 0:o.timestamp)||0,fallbackActivityAt:l,preview:c?lp(c):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((n,a)=>{const o=n.latestTimestamp||n.fallbackActivityAt||0,c=a.latestTimestamp||a.fallbackActivityAt||0;return c!==o?c-o:n.label.localeCompare(a.label)})}function Fx(e){return e==="chat"}function Lr(e,t){var r;if(!(typeof window>"u"))try{if(!(!!((r=import.meta.env)!=null&&r.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,t)}catch{}}function Hx({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:o,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:f,requestedMachineId:u,onRequestedMachineConsumed:p,requestedMobileSection:m,onRequestedMobileSectionConsumed:y,setSelectedTabKey:N,setScreen:h,setSelectedMachineId:j,setSection:x,setMachineBackTarget:b,resetMachineAction:v}){const A=i.useRef(null),g=i.useCallback(M=>{if(!(M!=null&&M.sessionId))return;const T=Yr(M,c),k=Math.max(Date.now(),ss(M),T.lastUpdated||0);Lr("mark_read:start",{tabKey:M.tabKey,sessionId:M.sessionId,displayPrimary:it(M),inboxBucket:T.inboxBucket,unread:T.unread,lastSeenAt:T.lastSeenAt,lastUpdated:T.lastUpdated,activityAt:ss(M),readAt:k}),l(xs(M)||M.routeId,"mark_session_seen",{sessionId:M.sessionId,providerSessionId:M.providerSessionId,seenAt:k,completionMarker:T.completionMarker}).then(w=>{Lr("mark_read:result",{tabKey:M.tabKey,sessionId:M.sessionId,result:w})}).catch(w=>{Lr("mark_read:error",{tabKey:M.tabKey,sessionId:M.sessionId,error:w instanceof Error?w.message:String(w)})})},[c,l]);return i.useEffect(()=>{var T;if(!n){Fx(o)&&h("inbox"),N(((T=e[0])==null?void 0:T.tabKey)||null),A.current=null;return}if(o!=="chat"){A.current=null;return}const M=`${n.tabKey}:${n.sessionId||""}`;A.current!==M&&(A.current=M,g(n))},[e,g,o,n,h,N]),i.useEffect(()=>{if(!d)return;const M=e.find(T=>T.tabKey===d);M&&(N(M.tabKey),h("chat"),f==null||f())},[e,f,d,h,N]),i.useEffect(()=>{if(!u)return;const M=t.find(T=>T.id===u);M&&(j(M.id),v(),x("machines"),b("inbox"),h("machine"),p==null||p())},[t,p,u,v,b,h,x,j]),i.useEffect(()=>{m&&(x(m),h("inbox"),y==null||y())},[y,m,h,x]),i.useEffect(()=>{const M=r.filter(T=>T.inboxBucket==="task_complete"||T.unread);M.length!==0&&Lr("inbox_state",{screen:o,selectedTabKey:a,items:M.map(T=>{const k=Yr(T.conversation,c);return{liveState:k,tabKey:T.conversation.tabKey,sessionId:T.conversation.sessionId,displayPrimary:it(T.conversation),serverBucket:k.inboxBucket,computedBucket:T.inboxBucket,serverUnread:k.unread,computedUnread:T.unread,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,activityAt:ss(T.conversation)}})})},[r,c,o,a]),{markConversationRead:g}}function Ux(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function hi(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function zx(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Vx({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const[a,o]=i.useState("idle"),[c,l]=i.useState(""),[d,f]=i.useState(null),u=i.useCallback(()=>{o("idle"),l(""),f(null)},[]),p=i.useCallback(async(b,v,A)=>{var g;try{o("loading"),l(`Launching ${v}…`);const M={ideType:v,enableCdp:!0};(g=A==null?void 0:A.workspacePath)!=null&&g.trim()&&(M.workspace=A.workspacePath.trim()),await e(b,"launch_ide",M),o("done"),l(`${v} launch requested`)}catch(M){o("error"),l(M instanceof Error?M.message:"Launch IDE failed"),console.error("Launch IDE failed",M)}},[e]),m=i.useCallback(async(b,v,A)=>{if(v.trim())try{o("loading"),l(A!=null&&A.createIfMissing?"Creating folder…":"Saving workspace…");const g=await e(b,"workspace_add",{path:v.trim(),createIfMissing:(A==null?void 0:A.createIfMissing)===!0});if(g!=null&&g.success){o("done"),l(A!=null&&A.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}o("error"),l((g==null?void 0:g.error)||"Could not save workspace")}catch(g){o("error"),l(g instanceof Error?g.message:"Could not save workspace")}},[e]),y=i.useCallback(async b=>{var v,A,g,M,T,k;try{o("loading"),l("Starting daemon upgrade…");const w=await e(b,"daemon_upgrade",{});if((v=w==null?void 0:w.result)!=null&&v.alreadyLatest){o("done"),l(`Already on v${((A=w==null?void 0:w.result)==null?void 0:A.version)||"latest"}.`);return}if((g=w==null?void 0:w.result)!=null&&g.upgraded||(M=w==null?void 0:w.result)!=null&&M.success){o("done"),l(`Upgrade to v${((T=w==null?void 0:w.result)==null?void 0:T.version)||"latest"} started. Daemon is restarting…`);return}o("error"),l(((k=w==null?void 0:w.result)==null?void 0:k.error)||"Upgrade failed")}catch(w){o("error"),l(w instanceof Error?w.message:"Upgrade failed")}},[e]),N=i.useCallback(async(b,v,A,g)=>{var k,w,K;const M=Date.now(),T={machineId:b,kind:v,providerType:A,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:M};try{o("loading"),l(`Launching ${A}…`),f(T);const R={cliType:A};(k=g==null?void 0:g.workspacePath)!=null&&k.trim()?R.dir=g.workspacePath.trim():g!=null&&g.workspaceId&&(R.workspaceId=g.workspaceId),g!=null&&g.resumeSessionId&&(R.resumeSessionId=g.resumeSessionId),(w=g==null?void 0:g.args)!=null&&w.trim()&&(R.cliArgs=g.args.trim().split(/\s+/).filter(Boolean)),(K=g==null?void 0:g.model)!=null&&K.trim()&&(R.initialModel=g.model.trim());const S=await e(b,"launch_cli",R),O=(S==null?void 0:S.result)||S,H=(O==null?void 0:O.sessionId)||(O==null?void 0:O.id);if(S!=null&&S.success&&H){f(null),o("done"),l(`${A} launched`),t(Yt(H));return}if(S!=null&&S.success){o("loading"),l(`${A} launch requested — waiting for session…`);return}f(null),o("error"),l((S==null?void 0:S.error)||(O==null?void 0:O.error)||`Could not launch ${v.toUpperCase()} workspace`)}catch(R){if(zx(R)){o("loading"),l(`${A} launch requested — waiting for session…`);return}f(null),o("error"),l(R instanceof Error?R.message:`Could not launch ${v.toUpperCase()} workspace`)}},[t,e]),h=i.useCallback(async(b,v)=>{try{const A=await e(b,"list_saved_sessions",{providerType:v,kind:"cli",limit:30}),g=(A==null?void 0:A.result)??A;return Array.isArray(g==null?void 0:g.sessions)?g.sessions:[]}catch(A){return console.error("Failed to list saved sessions on mobile:",A),[]}},[e]),j=i.useCallback(async(b,v)=>xn(e,b,v),[e]);i.useEffect(()=>{if(!d)return;const b=hi(d.workspacePath),v=r.find(g=>{var R,S,O,H;if(!g||g.type==="adhdev-daemon"||Ux(g.daemonId||g.id)!==d.machineId||(g.transport==="acp"?"acp":g.transport==="pty"?"cli":null)!==d.kind||String(g.agentType||g.type||"")!==d.providerType)return!1;const w=String(g.providerSessionId||"");if(d.resumeSessionId&&w)return w===d.resumeSessionId;if(b){const P=hi(g.workspace||g.runtimeWorkspaceLabel);return P?P===b:!1}return Number(g.lastUpdated||g._lastUpdate||g.timestamp||((H=(O=(S=(R=g.activeChat)==null?void 0:R.messages)==null?void 0:S.at)==null?void 0:O.call(S,-1))==null?void 0:H.timestamp)||0)>=d.startedAt-5e3});if(!v)return;const A=Ic({entrySessionId:v.sessionId,entryInstanceId:v.instanceId,entryRouteId:v.id,conversations:n});A&&(f(null),o("done"),l(`${d.providerType} launched`),t(Yt(A)))},[n,r,t,d]),i.useEffect(()=>{if(!d)return;const b=window.setTimeout(()=>{f(v=>!v||v.startedAt!==d.startedAt?v:(o("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(b)},[d]);const x=i.useCallback(async(b,v)=>{if(v.kind==="ide"&&v.providerType){await p(b,v.providerType,{workspacePath:v.workspace||null});return}(v.kind==="cli"||v.kind==="acp")&&v.providerType&&await N(b,v.kind,v.providerType,{workspacePath:v.workspace||null,resumeSessionId:v.providerSessionId||null})},[p,N]);return{machineAction:{state:a,message:c},resetMachineAction:u,handleLaunchDetectedIde:p,handleAddWorkspace:m,handleMachineUpgrade:y,handleLaunchWorkspaceProvider:N,handleListSavedSessions:h,handleBrowseDirectory:j,handleOpenRecent:x}}function Gx({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:o,setScreen:c,setSelectedMachineId:l,setSection:d,setMachineBackTarget:f}){const u=i.useCallback(x=>{o(x.tabKey),c("chat"),n(x)},[n,c,o]),p=i.useCallback(x=>{const b=e.find(v=>v.routeId===x.routeId&&v.streamSource==="native");b&&(o(b.tabKey),c("chat"),n(b))},[e,n,c,o]),m=i.useCallback(()=>{n(t),c("inbox")},[n,t,c]),y=i.useCallback((x,b="inbox")=>{l(x),a(),d("machines"),f(b),c("machine")},[a,f,c,d,l]),N=i.useCallback(x=>{const b=xs(x);b&&y(b,"chat")},[y]),h=i.useCallback(()=>{a(),c(r)},[r,a,c]),j=i.useCallback(x=>{d(x),c("inbox")},[c,d]);return{openConversation:u,openNativeConversation:p,backFromConversation:m,openMachine:y,openConversationMachine:N,backFromMachine:h,changeMachineSection:j}}function ps(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function qx(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function Yx({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,userName:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:f,requestedMachineId:u,onRequestedMachineConsumed:p,requestedMobileSection:m,onRequestedMobileSectionConsumed:y,onOpenHistory:N,onOpenRemote:h,onStopCli:j,wsStatus:x,isConnected:b,onShowAllHiddenConversations:v,onHideConversation:A,onOpenNewSession:g,liveSessionInboxState:M,setCliViewModeOverrides:T}){const[k,w]=i.useState(()=>{var Z;return((Z=e[0])==null?void 0:Z.tabKey)||null}),[K,R]=i.useState(()=>e[0]?"chat":"inbox"),[S,O]=i.useState("chats"),[H,P]=i.useState(null),[C,I]=i.useState("inbox"),W=i.useRef([]),E=Ps(),$="0.9.60",z=i.useMemo(()=>e.find(Z=>Z.tabKey===k)||e[0]||null,[e,k]),J=i.useMemo(()=>z?r.find(Z=>Z.id===z.routeId):void 0,[r,z]),he=i.useMemo(()=>!z||Xe(z)||!et(z)?null:Es(z),[z]),ce=i.useMemo(()=>r.filter(Z=>Z.type==="adhdev-daemon").sort(Wa),[r]),te=i.useMemo(()=>ce.find(Z=>Z.id===H)||null,[ce,H]),ye=mn({sendDaemonCommand:a,activeConv:z||void 0,setActionLogs:o,isStandalone:c}),fe=Vx({sendDaemonCommand:a,navigate:E,ides:r,conversations:e}),be=i.useMemo(()=>e.map(Z=>{const Ce=K==="chat"&&(z==null?void 0:z.tabKey)===Z.tabKey,Ee=dn(Z,M,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Ce}),We=ss(Z),Fe=Wc(Z);return{conversation:Z,timestamp:We,preview:Fe,unread:Ee.unread,requiresAction:Ee.requiresAction,isWorking:Ee.isWorking,inboxBucket:Ee.inboxBucket}}),[e,M,K,z]),{markConversationRead:X}=Hx({conversations:e,machineEntries:ce,items:be,selectedConversation:z,selectedTabKey:k,screen:K,liveSessionInboxState:M,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:f,requestedMachineId:u,onRequestedMachineConsumed:p,requestedMobileSection:m,onRequestedMobileSectionConsumed:y,setSelectedTabKey:w,setScreen:R,setSelectedMachineId:P,setSection:O,setMachineBackTarget:I,resetMachineAction:fe.resetMachineAction}),ae=Gx({conversations:e,selectedConversation:z,machineBackTarget:C,markConversationRead:X,resetMachineAction:fe.resetMachineAction,setSelectedTabKey:w,setScreen:R,setSelectedMachineId:P,setSection:O,setMachineBackTarget:I}),ge=i.useMemo(()=>Wr(be.filter(Z=>Z.requiresAction)),[be]),ee=i.useMemo(()=>Wr(be.filter(Z=>Z.unread&&!Z.requiresAction)),[be]),de=i.useMemo(()=>Bx(be.filter(Z=>!Z.unread&&!Z.requiresAction&&Z.isWorking),W.current),[be]);i.useEffect(()=>{W.current=de.map(Z=>Z.conversation.tabKey)},[de]);const we=i.useMemo(()=>Wr(be.filter(Z=>!Z.unread&&!Z.requiresAction&&!Z.isWorking)),[be]),ue=i.useMemo(()=>te?be.filter(Z=>xs(Z.conversation)===te.id):[],[be,te]),xe=i.useMemo(()=>Ox(te,r),[r,te]),se=(te==null?void 0:te.version)||null,ie=!!te&&!!se&&!0&&se!==$,re=i.useMemo(()=>(te==null?void 0:te.availableProviders)||[],[te]),q=i.useMemo(()=>re.filter(Z=>ps(Z,"cli")).map(Z=>({type:Z.type,displayName:Z.displayName||Z.type,icon:Z.icon})),[re]),Y=i.useMemo(()=>re.filter(Z=>ps(Z,"acp")).map(Z=>({type:Z.type,displayName:Z.displayName||Z.type,icon:Z.icon})),[re]),le=i.useMemo(()=>Wx(ce,be),[be,ce]),ke=i.useCallback(async Z=>{te&&await fe.handleOpenRecent(te.id,Z)},[fe,te]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:K==="chat"&&z?s.jsx(Ax,{selectedConversation:z,isAcp:Xe(z),isStandalone:c,selectedIdeEntry:J,actionLogs:n,userName:l,isSendingChat:ye.isSendingChat,sendFeedbackMessage:ye.sendFeedbackMessage,isFocusingAgent:ye.isFocusingAgent,handleModalButton:ye.handleModalButton,handleRelaunch:ye.handleRelaunch,onBack:ae.backFromConversation,onOpenNativeConversation:ae.openNativeConversation,onOpenMachine:ae.openConversationMachine,onHideConversation:A,onOpenHistory:N,onOpenRemote:h,onStopCli:j,cliViewMode:he,onSetCliViewMode:async Z=>{await hl({conversation:z,mode:Z,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:T})},handleSendChat:ye.handleSendChat,handleFocusAgent:ye.handleFocusAgent}):K==="machine"&&te?s.jsx($x,{selectedMachineEntry:te,selectedMachineConversations:ue,selectedMachineRecentLaunches:xe,cliProviders:q,acpProviders:Y,selectedMachineNeedsUpgrade:ie,appVersion:$,machineAction:fe.machineAction,isStandalone:c,section:S,showBottomNav:C==="inbox",onBack:ae.backFromMachine,onSectionChange:ae.changeMachineSection,onOpenConversation:ae.openConversation,onOpenRecent:ke,onOpenMachineDetails:()=>E(`/machines/${te.id}`),onMachineUpgrade:()=>fe.handleMachineUpgrade(te.id),onLaunchDetectedIde:(Z,Ce)=>fe.handleLaunchDetectedIde(te.id,Z,Ce),onAddWorkspace:(Z,Ce)=>fe.handleAddWorkspace(te.id,Z,Ce),onBrowseDirectory:Z=>fe.handleBrowseDirectory(te.id,Z),onLaunchWorkspaceProvider:(Z,Ce,Ee)=>fe.handleLaunchWorkspaceProvider(te.id,Z,Ce,Ee),onListSavedSessions:Z=>fe.handleListSavedSessions(te.id,Z)}):s.jsx(Lx,{section:S,attentionItems:ge,unreadItems:ee,workingItems:de,completedItems:we,hiddenConversations:t,machineCards:le,getAvatarText:qx,actionLogs:n,sendDaemonCommand:a,onOpenConversation:ae.openConversation,onShowAllHidden:v,onHideConversation:A,onOpenNewSession:g,onOpenMachine:ae.openMachine,onOpenSettings:()=>E("/settings"),onSectionChange:O,wsStatus:x,isConnected:b,isStandalone:c})})}function Fn(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function Xx({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:o}){const c=i.useRef(0),[l,d]=i.useState(!1),[f,u]=i.useState(null),p=i.useCallback(()=>{c.current=0,d(!1),u(null)},[]);i.useEffect(()=>(window.addEventListener("dragend",p),window.addEventListener("drop",p),()=>{window.removeEventListener("dragend",p),window.removeEventListener("drop",p)}),[p]);const m=i.useCallback(j=>{j.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,d(!0))},[]),y=i.useCallback(j=>{if(!j.dataTransfer.types.includes("text/tab-key"))return;if(j.preventDefault(),!Fn(t,r)){u("merge");return}const x=j.currentTarget.getBoundingClientRect(),b=j.clientX-x.left,v=x.width/3;b<v?u("split-left"):b>v*2?u("split-right"):u("merge")},[t,r]),N=i.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,d(!1),u(null))},[]),h=i.useCallback(j=>{c.current=0,d(!1);const x=j.dataTransfer.getData("text/tab-key"),b=x?e.some(A=>A.tabKey===x):!1,v=f;if(u(null),o(),!!x){if(j.preventDefault(),v==="split-left"&&Fn(t,r)){r==null||r(x,"split-left");return}if(v==="split-right"&&Fn(t,r)){r==null||r(x,"split-right");return}if(b){a(x);return}n==null||n(x)}},[e,f,t,r,n,a,o]);return{dragOver:l,dropAction:f,resetDragState:p,handleDragEnter:m,handleDragOver:y,handleDragLeave:N,handleDrop:h}}function Jx(e,t){const r=new Set(t.map(o=>o.tabKey)),n=e.filter(o=>r.has(o)),a=t.filter(o=>!e.includes(o.tabKey)).map(o=>o.tabKey);return[...n,...a]}function Qx({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[o,c]=i.useState(t??null),[l,d]=i.useState(r??[]),[f,u]=i.useState(null),p=i.useRef(null),m=i.useRef(null),y=i.useRef(n),N=i.useRef(a);i.useEffect(()=>{y.current=n},[n]),i.useEffect(()=>{N.current=a},[a]),i.useEffect(()=>{t&&t!==o&&c(t)},[t,o]),i.useEffect(()=>{d(T=>{const k=Jx(T,e);return k.length===T.length&&k.every((w,K)=>w===T[K])?T:k})},[e]);const h=i.useMemo(()=>{const T=f??l;if(T.length===0)return e;const k=new Map(T.map((w,K)=>[w,K]));return[...e].sort((w,K)=>{const R=k.get(w.tabKey)??999,S=k.get(K.tabKey)??999;return R-S})},[e,f,l]);i.useEffect(()=>{var k,w;if(h.length===0){o!==null&&(c(null),(k=y.current)==null||k.call(y,null));return}if(o&&h.some(K=>K.tabKey===o))return;const T=h[0].tabKey;T!==o&&(c(T),(w=y.current)==null||w.call(y,T))},[h,o]);const j=i.useMemo(()=>h.find(T=>T.tabKey===o),[h,o]),x=i.useCallback(T=>{var k;c(T),(k=y.current)==null||k.call(y,T)},[]),b=i.useCallback((T,k,w)=>{d(K=>{var H;const R=K.filter(P=>P!==T),S=R.indexOf(k);if(S<0)return K;const O=w==="left"?S:S+1;return R.splice(O,0,T),(H=N.current)==null||H.call(N,R),R}),u(null)},[]),v=i.useCallback((T,k,w)=>{const R=(l.length>0?l:e.map(H=>H.tabKey)).filter(H=>H!==T),S=R.indexOf(k);if(S<0)return;const O=w==="left"?S:S+1;R.splice(O,0,T),p.current=R,u(R)},[l,e]),A=i.useCallback(()=>{var k;const T=p.current;T&&(d(T),(k=N.current)==null||k.call(N,T))},[]),g=i.useCallback(()=>{p.current=null,u(null)},[]),M=i.useCallback(T=>{d(k=>{var K;const w=k.filter(R=>R!==T);return w.push(T),(K=N.current)==null||K.call(N,w),w})},[]);return{activeTabId:o,activeConv:j,sortedConversations:h,previewOrderRef:p,draggingTabRef:m,selectTab:x,handleTabReorder:b,updatePreviewOrder:v,commitPreviewOrder:A,clearPreviewOrder:g,moveTabToEnd:M,setDraggingTabKey:T=>{m.current=T}}}function Zx({dropAction:e,canSplit:t}){return s.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-left"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Left"})}),s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Move Here"})}),s.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-right"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Right"})})]})}function po({conversationsCount:e,isSplitMode:t,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession:o}){if(a)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const c=!r&&!n,l=n&&!!o,d=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",f=n?zc:r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.";return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:d}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:f}),l&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:o,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:Et,"aria-label":Et,children:[s.jsx(Zi,{size:14}),s.jsx("span",{children:Et})]})}),c&&s.jsx(jl,{}),c&&s.jsx("div",{className:"mt-8",children:s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"📚 Read the documentation →"})})]})]}):s.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const Cl="adhdev-tab-shortcuts";function Tl(){try{return JSON.parse(localStorage.getItem(Cl)||"{}")}catch{return{}}}function Ml({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,c]=i.useState(()=>Tl()),[l,d]=i.useState(null),f=i.useCallback(p=>{const m=[];return p.metaKey&&m.push(a?"⌘":"Meta"),p.ctrlKey&&m.push("Ctrl"),p.altKey&&m.push(a?"⌥":"Alt"),p.shiftKey&&m.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(m.push(p.key.length===1?p.key.toUpperCase():p.key),m.join("+"))},[a]),u=i.useCallback(p=>{c(p);try{localStorage.setItem(Cl,JSON.stringify(p))}catch{}},[]);return i.useEffect(()=>{if(!e||!l)return;const p=m=>{if(m.preventDefault(),m.stopPropagation(),m.key==="Escape"){d(null);return}const y=f(m);if(!y)return;const N={...o};for(const[h,j]of Object.entries(N))j===y&&delete N[h];N[l]=y,u(N),d(null)};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[e,l,o,u,f]),i.useEffect(()=>{if(!e)return;const p=m=>{if(!(!m.ctrlKey&&!m.metaKey&&!m.altKey)){for(const[y,N]of Object.entries(o))if(t.includes(y)&&f(m)===N){m.preventDefault(),r(),n(y);return}}};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[e,o,t,r,n,f]),{isMac:a,tabShortcuts:o,shortcutListening:l,setShortcutListening:d,saveShortcuts:u}}const Hn=e=>{e.preventDefault()},eb=i.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:o,conversationKeys:c,draggingTabRef:l,onFocus:d,onSelectTab:f,onConversationActivated:u,onPreviewReorder:p,onReorderTab:m,onCommitPreviewOrder:y,onClearPreviewOrder:N,onDragStateReset:h,onDragTabKeyChange:j,onReceiveTab:x,onOpenContextMenu:b,longPressTimer:v,isGroupActive:A}){const g=Ds(t),M=g.isGenerating?"agent-tab-generating":g.isWaiting?"agent-tab-waiting":"",T=g.isReconnecting,k=i.useCallback(I=>{l.current=t.tabKey,j(t.tabKey),I.dataTransfer.setData("text/tab-key",t.tabKey),I.dataTransfer.effectAllowed="move"},[t.tabKey,l,j]),w=i.useCallback(()=>{l.current=null,j(null),y(),N(),h()},[l,j,y,N,h]),K=i.useCallback(I=>{const W=l.current;if(!(!W||W===t.tabKey)&&I.dataTransfer.types.includes("text/tab-key")){I.preventDefault(),I.stopPropagation();const E=I.currentTarget.getBoundingClientRect(),$=I.clientX<E.left+E.width/2?"left":"right";p(W,t.tabKey,$)}},[t.tabKey,l,p]),R=i.useCallback(I=>{I.preventDefault(),I.stopPropagation();const W=I.dataTransfer.getData("text/tab-key");if(W&&W!==t.tabKey){const E=I.currentTarget.getBoundingClientRect(),$=I.clientX<E.left+E.width/2?"left":"right";c.includes(W)?m(W,t.tabKey,$):x&&x(W)}N()},[t.tabKey,c,m,x,N]),S=i.useCallback(I=>{I.stopPropagation(),d(),f(t.tabKey),u(t)},[t,u,d,f]),O=i.useCallback(I=>{I.preventDefault(),b(I.clientX,I.clientY,t.tabKey)},[t.tabKey,b]),H=i.useCallback(I=>{const W=I.touches[0];v.current=setTimeout(()=>{b(W.clientX,W.clientY,t.tabKey)},600)},[t.tabKey,v,b]),P=i.useCallback(()=>{v.current&&clearTimeout(v.current)},[v]),C=["adhdev-dockview-tab",M,r&&"is-active",A&&"is-group-active",T&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:C,draggable:!0,onDragStart:k,onDragEnd:w,onDragOver:K,onDrop:R,onClick:S,onContextMenu:O,onTouchStart:H,onTouchEnd:P,onTouchMove:P,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:g.isGenerating?s.jsx("div",{className:"tab-spinner"}):g.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):T?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):g.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:it(t),children:it(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[T?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:rs(t)}):g.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[rs(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:rs(t)}),s.jsx(Is,{git:t.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),o&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${o}`,children:o})]})},(e,t)=>e.conv===t.conv&&e.isActive===t.isActive&&e.isDraggedTab===t.isDraggedTab&&e.isTaskCompleteUnread===t.isTaskCompleteUnread&&e.shortcut===t.shortcut&&e.conversationKeys===t.conversationKeys&&e.isGroupActive===t.isGroupActive);function tb({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:o,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:f,onCommitPreviewOrder:u,onClearPreviewOrder:p,onDragStateReset:m,onDragTabKeyChange:y,onReceiveTab:N,onHideTab:h,isGroupActive:j,allowTabShortcuts:x=!0}){const[b,v]=i.useState(null),A=i.useRef(null),g=i.useRef(null),M=i.useMemo(()=>e.map(O=>O.tabKey),[e]);dr("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(b==null?void 0:b.tabKey)||null});const{isMac:T,tabShortcuts:k,shortcutListening:w,setShortcutListening:K,saveShortcuts:R}=Ml({enabled:x,sortedTabKeys:e.map(O=>O.tabKey),onFocus:o,onSelectTab:c});i.useEffect(()=>{if(!b)return;const O=H=>{const P=document.querySelector("[data-pane-context-menu]");P&&P.contains(H.target)||v(null)};return window.addEventListener("mousedown",O,!0),()=>window.removeEventListener("mousedown",O,!0)},[b]),i.useEffect(()=>{const O=g.current;if(!O)return;const H=P=>{Math.abs(P.deltaY)<=Math.abs(P.deltaX)||(P.preventDefault(),O.scrollLeft+=P.deltaY)};return O.addEventListener("wheel",H,{passive:!1}),()=>O.removeEventListener("wheel",H)},[]);const S=i.useCallback((O,H,P)=>{v({x:O,y:H,tabKey:P})},[]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:s.jsxs("div",{ref:g,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(O=>s.jsx(eb,{conv:O,isActive:t===O.tabKey,isDraggedTab:a.current===O.tabKey,isTaskCompleteUnread:n.has(O.tabKey),shortcut:x?k[O.tabKey]:void 0,conversationKeys:M,draggingTabRef:a,onFocus:o,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:f,onCommitPreviewOrder:u,onClearPreviewOrder:p,onDragStateReset:m,onDragTabKeyChange:y,onReceiveTab:N,onOpenContextMenu:S,longPressTimer:A,isGroupActive:j},O.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),b&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:b.x,top:b.y},children:[x&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:Hn,onClick:O=>{O.stopPropagation(),K(b.tabKey),v(null)},children:["⌨ ",k[b.tabKey]?`Change shortcut (${k[b.tabKey]})`:"Set shortcut"]}),k[b.tabKey]&&s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:Hn,onClick:()=>{const O={...k};delete O[b.tabKey],R(O),v(null)},children:"✕ Remove shortcut"})]}),h&&s.jsxs(s.Fragment,{children:[x&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:Hn,onClick:()=>{h(b.tabKey),v(null)},children:"🚫 Hide from Dashboard"})]})]}),x&&w&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>K(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:O=>O.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",T?"⌘+1":"Ctrl+1",", ",T?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function sb({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,hasRegisteredMachines:l,userName:d,groupIndex:f,onFocus:u,isSplitMode:p,numGroups:m,onMoveTab:y,onReceiveTab:N,style:h,onActiveTabChange:j,initialActiveTabId:x,initialTabOrder:b,onTabOrderChange:v,onHideTab:A,isFocused:g,allowTabShortcuts:M=!0,onOpenNewSession:T,liveSessionInboxState:k}){const{sendCommand:w}=mt(),K=i.useRef(null),{activeTabId:R,activeConv:S,sortedConversations:O,draggingTabRef:H,selectTab:P,handleTabReorder:C,updatePreviewOrder:I,commitPreviewOrder:W,clearPreviewOrder:E,moveTabToEnd:$,setDraggingTabKey:z}=Qx({conversations:e,initialActiveTabId:x,initialTabOrder:b,onActiveTabChange:j,onTabOrderChange:v}),J=mn({sendDaemonCommand:a,activeConv:S,setActionLogs:o,isStandalone:c}),{dragOver:he,dropAction:ce,resetDragState:te,handleDragEnter:ye,handleDragOver:fe,handleDragLeave:be,handleDrop:X}=Xx({conversations:e,numGroups:m,onMoveTab:y,onReceiveTab:N,onOwnTabDrop:$,onClearPreviewOrder:E}),ae=S&&!Xe(S)&&Es(S)==="terminal",ge=i.useMemo(()=>S?t.find(ue=>ue.id===S.routeId):void 0,[t,S]),ee=i.useMemo(()=>S?n.filter(ue=>ue.routeId===S.tabKey):[],[n,S]),de=i.useMemo(()=>new Set(O.filter(ue=>qu(ue,k,{isOpenConversation:ue.tabKey===R})).map(ue=>ue.tabKey)),[R,k,O]);dr("PaneGroup",{groupIndex:f,conversationCount:e.length,activeTabId:R,dragOver:he});const we=i.useCallback(ue=>{ue.streamSource==="agent-stream"&&ue.agentType&&w(ue.routeId,jc(),{agentType:ue.agentType,...ue.sessionId&&{targetSessionId:ue.sessionId}}).catch(()=>{})},[w]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...h,outline:he?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(tb,{conversations:O,activeTabId:R,groupIndex:f,numGroups:m,unreadTabKeys:de,draggingTabRef:H,onFocus:u,onSelectTab:P,onConversationActivated:we,onPreviewReorder:I,onReorderTab:C,onCommitPreviewOrder:W,onClearPreviewOrder:E,onDragStateReset:te,onDragTabKeyChange:z,onMoveTab:y,onReceiveTab:N,onHideTab:A,isGroupActive:g??!1,allowTabShortcuts:M}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ye,onDragOver:fe,onDragLeave:be,onDrop:X,children:[he&&s.jsx(Zx,{dropAction:ce,canSplit:!!(m<4&&y)}),S?s.jsx(fo,{activeConv:S,clearToken:r[S.tabKey]||0,isCliTerminal:!!ae,ideEntry:ge,terminalRef:K,handleModalButton:J.handleModalButton,handleRelaunch:J.handleRelaunch,handleSendChat:J.handleSendChat,isSendingChat:J.isSendingChat,sendFeedbackMessage:J.sendFeedbackMessage,handleFocusAgent:J.handleFocusAgent,isFocusingAgent:J.isFocusingAgent,actionLogs:ee,userName:d,isInputActive:!p||!!g}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(po,{conversationsCount:e.length,isSplitMode:p,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:T})})]})]})}function rb({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:o,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:f,isStandalone:u,hasRegisteredMachines:p,userName:m,focusedGroup:y,focusGroup:N,moveTabToGroup:h,splitTabRelative:j,closeGroup:x,handleResizeStart:b,groupActiveTabIds:v,setGroupActiveTab:A,groupTabOrders:g,setGroupTabOrder:M,toggleHiddenTab:T,onOpenNewSession:k,allowTabShortcuts:w=!0,liveSessionInboxState:K}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((R,S)=>{const O=t&&n.length===r?`${n[S]}%`:void 0;return s.jsxs(kt.Fragment,{children:[t&&S>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:H=>b(S-1,H),onDoubleClick:()=>x(S),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(sb,{style:t?{flexBasis:O??`${100/r}%`,flexGrow:O?0:1,flexShrink:O?0:1}:void 0,conversations:R,clearedTabs:o,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:f,isStandalone:u,hasRegisteredMachines:p,userName:m,groupIndex:S,isFocused:t&&y===S,onFocus:()=>N(S),isSplitMode:t,numGroups:r,onMoveTab:(H,P)=>{P==="left"&&S>0?h(H,S-1):P==="right"&&S<r-1?h(H,S+1):P==="split-left"&&r<4?j(H,S,"left"):P==="split-right"&&r<4&&j(H,S,"right")},onReceiveTab:H=>h(H,S),onActiveTabChange:H=>A(S,H),initialActiveTabId:v[S],initialTabOrder:g[S],onTabOrderChange:H=>M(S,H),onHideTab:T,onOpenNewSession:k,allowTabShortcuts:w,liveSessionInboxState:K})]},S)})})}function Al({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,o]=i.useState(null),[c,l]=i.useState(null);i.useEffect(()=>e?ot.onScreenshot("ide-page",(u,p)=>{if(u!==e)return;const m=new FileReader;m.onload=()=>o(m.result),m.readAsDataURL(p)}):void 0,[e]),i.useEffect(()=>{r!=="connected"&&o(null)},[r]),i.useEffect(()=>{var u;return e?((u=ot.onStatus)==null?void 0:u.call(ot,(p,m)=>{p===e&&m!=null&&m.screenshotUsage&&l(m.screenshotUsage)}))||(()=>{}):void 0},[e]),i.useEffect(()=>{o(null)},[e,t]),i.useEffect(()=>{const f=e?ot.get(e):null;if(!(!f||r!=="connected"))return n!=="chat"&&t?f.startScreenshots(t):f.stopScreenshots(t),()=>{f.stopScreenshots(t)}},[n,r,t,e]);const d=i.useCallback(async(f,u)=>{const p=e?ot.get(e):null;return!p||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):p.sendInput(f,u,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:d}}const Il="adhdev-dashboard-action-shortcuts",nb=1200,ab=[["toggleHiddenTabs","G H"],["openNewSession","N"],["setActiveTabShortcut","G S"],["selectPreviousGroupTab","G K"],["selectPreviousGroupTab","T ←"],["selectPreviousGroupTab","⌥+["],["selectPreviousGroupTab","Ctrl+Alt+["],["selectNextGroupTab","G J"],["selectNextGroupTab","T →"],["selectNextGroupTab","⌥+]"],["selectNextGroupTab","Ctrl+Alt+]"],["splitActiveTabDown","S ↓"],["splitActiveTabDown","⌘+⌥+-"],["splitActiveTabDown","Ctrl+Alt+-"],["splitActiveTabRight","S →"],["splitActiveTabRight","⌘+⌥+\\"],["splitActiveTabRight","⌘+⌥+="],["splitActiveTabRight","Ctrl+Alt+\\"],["focusLeftPane","F ←"],["focusLeftPane","⌘+⌥+←"],["focusLeftPane","⌘+⌥+["],["focusLeftPane","Ctrl+Alt+←"],["focusRightPane","F →"],["focusRightPane","⌘+⌥+→"],["focusRightPane","⌘+⌥+]"],["focusRightPane","Ctrl+Alt+→"],["focusUpPane","F ↑"],["focusUpPane","⌘+⌥+U"],["focusUpPane","Ctrl+Alt+↑"],["focusDownPane","F ↓"],["focusDownPane","⌘+⌥+J"],["focusDownPane","Ctrl+Alt+↓"],["moveActiveTabToLeftPane","M ←"],["moveActiveTabToLeftPane","⌘+⌥+⇧+←"],["moveActiveTabToLeftPane","⌘+⌥+,"],["moveActiveTabToLeftPane","Ctrl+Alt+Shift+←"],["moveActiveTabToRightPane","M →"],["moveActiveTabToRightPane","⌘+⌥+⇧+→"],["moveActiveTabToRightPane","⌘+⌥+."],["moveActiveTabToRightPane","Ctrl+Alt+Shift+→"],["moveActiveTabToUpPane","M ↑"],["moveActiveTabToUpPane","⌘+⌥+I"],["moveActiveTabToUpPane","Ctrl+Alt+Shift+↑"],["moveActiveTabToDownPane","M ↓"],["moveActiveTabToDownPane","⌘+⌥+K"],["moveActiveTabToDownPane","Ctrl+Alt+Shift+↓"],["triggerPrimaryApprovalAction","⌥+A"],["triggerSecondaryApprovalAction","⌥+D"],["toggleCliView","T"]];function ob(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function st(e,t){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return t?"⌘+⇧+Enter":"Ctrl+Shift+Enter";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+Ctrl+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return t?"⌘+Ctrl+⇧+↓":"Ctrl+Alt+Shift+↓";case"focusLeftPane":return"";case"focusRightPane":return"";case"focusUpPane":return"";case"focusDownPane":return"";case"moveActiveTabToLeftPane":return"";case"moveActiveTabToRightPane":return"";case"moveActiveTabToUpPane":return"";case"moveActiveTabToDownPane":return"";case"triggerPrimaryApprovalAction":return t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌘+⇧+←":"Ctrl+Shift+←";case"selectNextGroupTab":return t?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function Ll(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:st("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:st("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:st("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:st("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:st("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:st("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:st("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:st("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:st("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:st("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:st("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:st("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:st("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:st("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:st("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:st("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:st("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:st("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:st("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:st("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:st("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:st("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:st("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:st("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:st("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:st("toggleCliView",e)}]}function Ca(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function nn(e){const t=Object.fromEntries(Ll(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Il)||"{}"),n={...t,...r};for(const[a,o]of ab)n[a]===o&&(n[a]=t[a]);return n}catch{return t}}function Rl(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function ib({enabled:e=!0,onTrigger:t}){const r=ob(),[n,a]=i.useState(()=>nn(r)),[o,c]=i.useState(null),[l,d]=i.useState([]),f=i.useRef({parts:[],timer:null}),u=i.useCallback(h=>{const j=[];return h.metaKey&&j.push(r?"⌘":"Meta"),h.ctrlKey&&j.push("Ctrl"),h.altKey&&j.push(r?"⌥":"Alt"),h.shiftKey&&h.key.length!==1&&j.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(j.push(Rl(h.key)),j.join("+"))},[r]),p=i.useCallback(h=>{a(h);try{localStorage.setItem(Il,JSON.stringify(h))}catch{}},[]);i.useEffect(()=>{const h=nn(r),j=Object.entries(n),x=Object.entries(h);j.length===x.length&&j.every(([b,v])=>h[b]===v)||p(h)},[n,r,p]);const m=i.useCallback(()=>{typeof window<"u"&&f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current={parts:[],timer:null}},[]),y=i.useCallback(()=>{typeof window>"u"||(f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current.timer=window.setTimeout(()=>{f.current={parts:[],timer:null}},nb))},[]);i.useEffect(()=>{if(!o)return;const h=j=>{if(j.preventDefault(),j.stopPropagation(),j.key==="Escape"){c(null),d([]);return}const x=u(j);if(!x)return;const v=!(j.metaKey||j.ctrlKey||j.altKey)&&/^[A-Z0-9]$/.test(x);if(l.length===0&&v){d([x]);return}const g=[...l,x].slice(0,2).join(" "),M={...n};for(const[T,k]of Object.entries(M))k===g&&delete M[T];M[o]=g,p(M),c(null),d([])};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[n,u,p,o,l]),i.useEffect(()=>{if(!e||o)return;const h=j=>{if(j.defaultPrevented)return;const x=u(j);if(!x)return;const b=j.metaKey||j.ctrlKey||j.altKey;if(Ca(j.target))return;const v=f.current.parts,A=b?[x]:[...v.slice(-1),x].slice(-2),g=A.join(" "),M=A[A.length-1],T=Object.entries(n).filter(([,S])=>!!S),k=T.find(([,S])=>S===g);if(k){j.preventDefault(),m(),t(k[0]);return}if(T.some(([,S])=>S.startsWith(`${g} `))){j.preventDefault(),f.current.parts=A,y();return}const K=T.find(([,S])=>S===M);if(K){j.preventDefault(),m(),t(K[0]);return}if(T.some(([,S])=>S.startsWith(`${M} `))){j.preventDefault(),f.current.parts=[M],y();return}m()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[n,y,e,u,t,m,o]),i.useEffect(()=>()=>m(),[m]);const N=i.useMemo(()=>Ll(r),[r]);return{isMac:r,actionDefinitions:N,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:d,saveShortcuts:p}}function cb({isTabInPopout:e,isTabFloating:t,tabShortcut:r,actionShortcuts:n}){const a=[];return e?(t&&a.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:n.dockActiveTab}),a.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:n.dockActiveTab})):t?a.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:n.dockActiveTab}):a.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:n.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:n.popoutActiveTab}),a.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:r?`Change shortcut (${r})`:"Set shortcut",shortcut:n.setActiveTabShortcut}),r&&a.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),a.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:n.hideCurrentTab,tone:"muted"}),a}function _l(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function xi({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!_l(n):!0}function lb({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:_l(r)}const Pl=1e3,db=4;function bi(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function gi(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function ub({detachDelayMs:e=Pl,stillnessThresholdPx:t=db,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,c=null,l=null,d=null,f=null,u=!1;const p=()=>{f!=null&&(a(f),f=null)},m=()=>{p(),l=null},y=()=>{p(),o=null,c=null,l=null,d=null,u=!1},N=()=>{!o||!l||!d||u||f!=null||(f=n(()=>{f=null,!(!o||!l||!d||u)&&bi(d,c)&&(gi(l,d,t)||(u=!0,r({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},h=x=>{if(!(!o||u)){if(!bi(x,c)){d={clientX:x.clientX,clientY:x.clientY},m();return}(!l||gi(l,x,t))&&(p(),l={clientX:x.clientX,clientY:x.clientY}),d={clientX:x.clientX,clientY:x.clientY},N()}},j=x=>{!o||u||(x&&(d={clientX:x.clientX,clientY:x.clientY}),m())};return{startDrag:x=>{p(),o=x.panelId,c=x.selfPanelBounds??null,l=null,d={clientX:x.clientX,clientY:x.clientY},u=!1},markSelfPanel:h,markNonSelfPanel:j,markNoDropTarget:j,markDockTarget:j,endDrag:y,isDragging:()=>o!=null,hasDetached:()=>u,dispose:y}}function fb(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}const Dl=i.createContext(null);function gn(){const e=i.useContext(Dl);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Fr(e){return it(e)||e.tabKey}function mb(e){return`remote:${e}`}function Lt(e){return e.startsWith("remote:")}function yi(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function pb(e){e.preventDefault()}function Un(e){var n;const t=e==null?void 0:e.defaultView;if(!t)return;const r=a=>{if(a)try{a.focus({preventScroll:!0})}catch{try{a.focus()}catch{}}};try{t.focus(),r(e==null?void 0:e.body),r(e==null?void 0:e.documentElement),(n=t.requestAnimationFrame)==null||n.call(t,()=>{try{t.focus(),r(e==null?void 0:e.body)}catch{}})}catch{}}function zn(e,t){e.classList.remove(aa.className,oa.className),e.classList.add(t==="light"?aa.className:oa.className)}function vi(e){return e?Array.from(new Set(e.groups.map(t=>{var r,n;return(n=(r=t.element)==null?void 0:r.ownerDocument)==null?void 0:n.defaultView}).filter(t=>!!t&&t!==window))):[]}function hb(e){const[,t]=i.useState(0);i.useEffect(()=>{const r=()=>t(a=>a+1),n=[e.api.onDidActiveGroupChange(r),e.api.onDidTitleChange(r),e.api.onDidGroupChange(r),e.containerApi.onDidActivePanelChange(r)];return()=>{for(const a of n)a.dispose()}},[e.api,e.containerApi])}function xb(e,t,r){var c;const n=[t];let a;for(const l of n){let d;for(const f of l){const u=e.addPanel({id:f.tabKey,component:"conversation",title:Fr(f),params:{kind:"conversation",tabKey:f.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});d||(d=u.id)}a=d??a}return r??((c=t[0])==null?void 0:c.tabKey)??null}function wi(e,t){const r=new Set(t.map(n=>n.tabKey));for(const n of[...e.panels])Lt(n.id)||r.has(n.id)||e.removePanel(n);for(const n of t){const a=e.getPanel(n.tabKey);if(a){a.update({params:{tabKey:n.tabKey}}),a.title!==Fr(n)&&a.api.setTitle(Fr(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:Fr(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 ji(e,t,r){var d,f;const n=r?mb(r):null;for(const u of[...e.panels])Lt(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=Pt(t,r);if(!a&&e.totalPanels===0)return;const o=e.getPanel(n),c=Uc(a);if(o){o.title!==c&&o.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((f=e.panels.find(u=>!Lt(u.id)))==null?void 0:f.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function bb({params:e,api:t}){var p;const r=gn(),n=i.useRef(null),[a,o]=i.useState(t.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=mn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});i.useEffect(()=>{o(t.isActive);const m=[t.onDidActiveChange(y=>o(y.isActive)),t.onDidActiveGroupChange(y=>{if(!t.isActive&&!y.isActive){o(!1);return}o(t.isActive)})];return()=>{for(const y of m)y.dispose()}},[t]);const d=i.useMemo(()=>c?r.ides.find(m=>m.id===c.routeId):void 0,[r.ides,c]),f=i.useMemo(()=>c?r.actionLogs.filter(m=>m.routeId===c.tabKey):[],[r.actionLogs,c]);if(!c)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(po,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const u=!Xe(c)&&Es(c)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(fo,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:u,ideEntry:d,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:f,userName:r.userName,scrollToBottomRequestNonce:((p=r.scrollToBottomRequest)==null?void 0:p.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:a})})}function gb({params:e}){var d;const t=gn(),r=i.useMemo(()=>Pt([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=i.useMemo(()=>t.ides.find(f=>f.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((d=r==null?void 0:r.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:c,handleRemoteAction:l}=Al({doId:a,targetSessionId:r?wc(r):(n==null?void 0:n.sessionId)||(n==null?void 0:n.instanceId),connState:(r==null?void 0:r.connectionState)||"new",viewMode:"remote"});return r?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(ac,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:o,screenshotUsage:c,transportType:r.transport,onAction:l})}):s.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:"Remote view unavailable"})}function yb(){const e=gn();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(po,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function vb(e){var y,N;hb(e);const t=gn(),r=i.useCallback(h=>{"button"in h&&h.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const h=Pt([...t.conversationsByTabKey.values()],e.params.routeId),j=((y=e.api.group.activePanel)==null?void 0:y.id)===e.api.id,x=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${j?" is-active":""}${x?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(h==null?void 0:h.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:h!=null&&h.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:h.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const n=t.conversationsByTabKey.get(e.params.tabKey);if(!n)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const a=((N=e.api.group.activePanel)==null?void 0:N.id)===e.api.id,o=e.api.isGroupActive,c=dn(n,t.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,d=c.isConnecting,f=c.isGenerating,u=c.isWaiting,p=c.unread,m=t.tabShortcuts[n.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${o?" is-group-active":""}${l?" is-reconnecting":""}`,title:it(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:h=>{var j;h.preventDefault(),r(h),t.openTabContextMenu({x:h.clientX,y:h.clientY,tabKey:n.tabKey,sourceDocument:((j=h.target)==null?void 0:j.ownerDocument)??document})},children:[p&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:f?s.jsx("div",{className:"tab-spinner"}):u?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):d?s.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:it(n)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:rs(n)}):d?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:rs(n)}):s.jsx("span",{children:rs(n)})})]}),m&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:m,children:m})]})}function wb({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:d,userName:f,toggleHiddenTab:u,actionShortcuts:p,registerActionHandlers:m,onActiveTabChange:y,onOpenNewSession:N,onRequestScrollToBottom:h,requestedActiveTabKey:j,requestedRemoteIdeId:x,onRequestedActiveTabConsumed:b,scrollToBottomRequest:v,liveSessionInboxState:A,layoutProfile:g}){var Ze,qe,tt;const{theme:M}=ao(),{sendCommand:T}=mt(),k=i.useRef(null),w=i.useRef(null),K=i.useRef(null),R=i.useRef(!1),S=i.useRef(!1),O=i.useRef(!1),H=i.useRef(null),P=i.useRef([]),[C,I]=i.useState(null),[W,E]=i.useState(0),$=i.useRef(typeof window>"u"?{}:Vh(g)),z=i.useMemo(()=>new Map(e.map(F=>[F.tabKey,F])),[e]),J=i.useMemo(()=>{const F=k.current;return F?F.groups.some(V=>{try{const L=V.model.location.type;return L!=="floating"&&L!=="popout"?!1:V.panels.some(G=>z.has(G.id))}catch{return!1}}):!1},[z,W,e]),he=i.useCallback(()=>{var F;(F=k.current)==null||F.focus()},[]),ce=i.useCallback((F,V)=>{h==null||h(F,V)},[h]),te=i.useCallback(F=>{const V=document,L=F.document;for(const ne of V.querySelectorAll('link[rel="stylesheet"]')){const ve=L.createElement("link");ve.rel="stylesheet",ve.href=ne.href,ne.crossOrigin&&(ve.crossOrigin=ne.crossOrigin),L.head.appendChild(ve)}for(const ne of V.querySelectorAll("style")){const ve=L.createElement("style");ve.textContent=ne.textContent,L.head.appendChild(ve)}const G=[];for(const ne of V.styleSheets)try{for(const ve of ne.cssRules)ve instanceof CSSStyleRule&&(ve.selectorText===":root"||ve.selectorText==="html")&&G.push(ve.cssText)}catch{}if(G.length>0){const ne=L.createElement("style");ne.textContent=G.join(`
|
|
51
|
+
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:w,onCancel:()=>u(null)})]})}const nh=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function ah(){const{preference:e,setPreference:t}=ao();return s.jsx("div",{className:"flex gap-2",children:nh.map(r=>s.jsxs("button",{onClick:()=>t(r.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===r.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===r.id?{color:"var(--accent-on-primary)"}:void 0,children:[s.jsx("span",{children:r.icon}),r.label]},r.id))})}function oh(e){const t=e.trim();return/^#[0-9a-fA-F]{6}$/.test(t)?t:/^#[0-9a-fA-F]{3}$/.test(t)?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:null}function ih(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function _n(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function ri(e){const{r:t,g:r,b:n}=ih(e);return .2126*_n(t)+.7152*_n(r)+.0722*_n(n)}function ni(e,t){const r=ri(e),n=ri(t),a=Math.max(r,n),o=Math.min(r,n);return(a+.05)/(o+.05)}function ol(e){const t=oh(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return ni(t,r)>=ni(t,n)?r:n}const ka={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},Sa={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},ch=[{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"}}}],il="adhdev-chat-theme",cl="adhdev-chat-theme-custom";function Kr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(il)||"ember"}catch{return"ember"}}function _t(e){try{const t=localStorage.getItem(cl);if(t){const r=JSON.parse(t);return{...e==="dark"?ka:Sa,...r[e]}}}catch{}return e==="dark"?ka:Sa}function Tr(e,t){try{localStorage.setItem(cl,JSON.stringify({dark:e,light:t}))}catch{}}function Mt(e,t){const r=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${r}, ${n}, ${a}, ${t})`}function rn(e,t){const r=Math.min(255,parseInt(e.slice(1,3),16)+t),n=Math.min(255,parseInt(e.slice(3,5),16)+t),a=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const lh={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function er(e,t){var a;const r=(a=lh[e])==null?void 0:a[t];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",rn(r,24)),n.style.setProperty("--accent-on-primary",ol(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${rn(r,18)})`),n.style.setProperty("--border-accent",Mt(r,.35)),n.style.setProperty("--nav-active-bg",Mt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Mt(r,.06)}`)}function os(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Mt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Mt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Mt(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",Mt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Mt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",rn(e.accentColor,30)),t.style.setProperty("--accent-on-primary",ol(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${rn(e.accentColor,40)})`),t.style.setProperty("--border-accent",Mt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Mt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Mt(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${Mt(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function oo(){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 dh(e){try{localStorage.setItem(il,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=is()?"dark":"light";os(_t(t))}else oo(),er(e,is()?"dark":"light")}function uh(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Kr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=is()?"dark":"light";os(_t(t))}else oo(),er(e,is()?"dark":"light")}function is(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function gt({label:e,value:t,onChange:r}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,onChange:n=>{/^#[0-9a-fA-F]{0,6}$/.test(n.target.value)&&r(n.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function Hs({title:e,children:t}){return s.jsxs("div",{style:{marginBottom:14},children:[s.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:t})]})}function fh({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=i.useState(()=>_t(r));i.useEffect(()=>{a(_t(r))},[r]);const o=i.useCallback((c,l)=>{a(d=>{const f={...d,[c]:l},p=_t(r==="dark"?"light":"dark");return r==="dark"?Tr(f,p):Tr(p,f),os(f),t(f),f})},[r,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",s.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(Hs,{title:"App Background",children:[s.jsx(gt,{label:"Background",value:n.bgPrimary,onChange:c=>o("bgPrimary",c)}),s.jsx(gt,{label:"Surface",value:n.bgSecondary,onChange:c=>o("bgSecondary",c)}),s.jsx(gt,{label:"Card",value:n.surfacePrimary,onChange:c=>o("surfacePrimary",c)})]}),s.jsxs(Hs,{title:"App Text",children:[s.jsx(gt,{label:"Primary",value:n.textPrimary,onChange:c=>o("textPrimary",c)}),s.jsx(gt,{label:"Secondary",value:n.textSecondary,onChange:c=>o("textSecondary",c)}),s.jsx(gt,{label:"Muted",value:n.textMuted,onChange:c=>o("textMuted",c)})]}),s.jsxs(Hs,{title:"Borders & Accent",children:[s.jsx(gt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>o("borderSubtle",c)}),s.jsx(gt,{label:"Border default",value:n.borderDefault,onChange:c=>o("borderDefault",c)}),s.jsx(gt,{label:"Accent",value:n.accentColor,onChange:c=>o("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Hs,{title:"Chat Bubbles",children:[s.jsx(gt,{label:"User bubble",value:n.userBubble,onChange:c=>o("userBubble",c)}),s.jsx(gt,{label:"User text",value:n.userText,onChange:c=>o("userText",c)}),s.jsx(gt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>o("assistantBubble",c)}),s.jsx(gt,{label:"Agent text",value:n.assistantText,onChange:c=>o("assistantText",c)})]}),s.jsxs(Hs,{title:"Chat Layout",children:[s.jsx(gt,{label:"Chat BG",value:n.containerBg,onChange:c=>o("containerBg",c)}),s.jsx(gt,{label:"Send button",value:n.sendButton,onChange:c=>o("sendButton",c)}),s.jsx(gt,{label:"Input border",value:n.inputBorder,onChange:c=>o("inputBorder",c)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.jsx("input",{type:"range",min:4,max:24,value:n.bubbleRadius,onChange:c=>o("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?ka:Sa,d=_t(e?"light":"dark");e?Tr(c,d):Tr(d,c),a(c),os(c),t(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:"Reset to defaults"})]})}function mh(){const[e,t]=i.useState(Kr),[r,n]=i.useState(!0),[a,o]=i.useState(()=>_t("dark"));i.useEffect(()=>{n(is());const d=new MutationObserver(()=>{const p=is();n(p);const m=Kr();m==="custom"?os(_t(p?"dark":"light")):er(m,p?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const f=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const p=is();n(p);const m=Kr();m==="custom"?os(_t(p?"dark":"light")):er(m,p?"dark":"light")};return f.addEventListener("change",u),()=>{d.disconnect(),f.removeEventListener("change",u)}},[]),i.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?os(_t(r?"dark":"light")):(oo(),er(e,r?"dark":"light"))},[e,r]),i.useEffect(()=>{o(_t(r?"dark":"light"))},[r]);const c=d=>{t(d),dh(d)},l=[...ch,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:l.map(d=>{const f=e===d.id,u=r?d.preview.dark:d.preview.light,p=d.id==="honey"||d.id==="ember"?"#1a1a1a":d.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>c(d.id),className:"text-left rounded-xl p-3 transition-all",style:{background:f?"var(--bg-glass-hover)":"var(--bg-glass)",border:f?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:f?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:u.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"Hello! How can I help?"}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.userBubble,color:p},children:"Fix the bug please"}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"On it! ✨"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[f&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:d.id==="custom"?"🎨 Custom":d.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:d.description})]})]})]},d.id)})}),e==="custom"&&s.jsx(fh,{dark:r,onColorsChange:d=>o(d)})]})}const io="adhdev_mobileDashboardMode_v1",Na="adhdev:mobile-dashboard-mode-change";function co(){try{return localStorage.getItem(io)==="workspace"?"workspace":"chat"}catch{return"chat"}}function ph(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??co())},r=a=>{const o=a.detail;t(o)},n=a=>{a.key&&a.key!==io||t()};return window.addEventListener(Na,r),window.addEventListener("storage",n),()=>{window.removeEventListener(Na,r),window.removeEventListener("storage",n)}}function hh(e){try{localStorage.setItem(io,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Na,{detail:e}))}function xh(){const[e,t]=i.useState(!0);return i.useEffect(()=>{t(co()==="chat")},[]),s.jsx(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ut,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:r=>{t(r),hh(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const Pn=new Map,ai=new Map;function bh(e){if(!e||typeof e!="object")return null;const t=e,r=t.result&&typeof t.result=="object"?t.result:t,n=r.machine;return!n||typeof n!="object"?null:{machine:n,timestamp:typeof r.timestamp=="number"?r.timestamp:void 0}}function gh(e,t,r,n){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:n,platform:r.platform,machine:r}}function ll(){const{sendCommand:e}=mt(),{injectEntries:t,getIdes:r}=rr();return i.useCallback(async(n,a)=>{if(!n)return;const o=(a==null?void 0:a.minFreshMs)??pm,c=ai.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<o)return;const l=Pn.get(n);if(l)return l;const d=(async()=>{const f=await e(n,"get_machine_runtime_stats"),u=bh(f);if(!u)return;const p=r().find(y=>y.id===n),m=gh(p,n,u.machine,u.timestamp||Date.now());t([m]),ai.set(n,Date.now())})().finally(()=>{Pn.delete(n)});return Pn.set(n,d),d},[r,t,e])}function yh(e,t,r){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:r.timestamp,platform:r.machine.platform,machine:{...(e==null?void 0:e.machine)||{},...r.machine}}}function vh(e,t){const{sendData:r}=mt(),{injectEntries:n,getIdes:a}=rr(),o=Array.from(new Set(e.filter(Boolean))).join("|");i.useEffect(()=>{if(!(t!=null&&t.enabled)||!r)return;const c=o?o.split("|"):[];if(c.length===0)return;const l=c.map(d=>Ht.subscribe({sendData:r},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const p=a().find(y=>y.id===d),m=yh(p,d,u);n([m])}));return()=>{l.forEach(d=>d())}},[o,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function wh(e,t){const{sendData:r}=mt(),[n,a]=i.useState(null),[o,c]=i.useState(!1);return i.useEffect(()=>{if(!e){a(null),c(!1);return}if(!(t!=null&&t.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const d=Ht.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},f=>{l&&(clearTimeout(l),l=null),a(f.diagnostics),c(!1)});return d.initialSendAccepted?l=setTimeout(()=>{c(!1)},gm):c(!1),()=>{l&&clearTimeout(l),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,r]),{diagnostics:n,loading:o,applyDiagnostics:a}}function jh(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function dl(e){const{sendData:t}=mt(),[r,n]=i.useState({});return i.useEffect(()=>{const a=jh(e);if(!a||!e.sessionId||!t){n({});return}const o=Ht.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),Ns.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 o.initialSendAccepted||n({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),r}const ul="adhdev_hiddenTabs";function kh(){try{const e=localStorage.getItem(ul);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function bs(e){try{localStorage.setItem(ul,JSON.stringify([...e]))}catch{}}function Dn(e){return qa(e)}function lo(e,t){return Ss(t).some(r=>e.has(r))}function Sh(){const[e,t]=i.useState(kh),r=i.useCallback(f=>{const u=Dn(f);t(p=>{const m=new Set(p);return m.has(u)?m.delete(u):m.add(u),bs(m),m})},[]),n=i.useCallback(f=>{const u=Dn(f);t(p=>{if(p.has(u))return p;const m=new Set(p);return m.add(u),bs(m),m})},[]),a=i.useCallback(f=>{const u=Dn(f);t(p=>{if(!p.has(u))return p;const m=new Set(p);return m.delete(u),bs(m),m})},[]),o=i.useCallback(()=>{t(f=>{if(f.size===0)return f;const u=new Set;return bs(u),u})},[]),c=i.useCallback((f,u)=>{t(p=>{const m=new Set(p);for(const y of u)m.add(y);return bs(m),m})},[]),l=i.useCallback((f,u)=>{t(p=>{const m=new Set(p);for(const y of u)m.delete(y);return bs(m),m})},[]),d=i.useCallback(f=>lo(e,f),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:o,hideAllForDaemon:c,showAllForDaemon:l,isHidden:d}}function fl(e){return e instanceof Error?e.message:String(e||"")}function ml(e){const t=fl(e);return t.includes("P2P command timeout")||t.includes("P2P not connected")||t.includes("P2P channel not open")||t.includes("P2P not available")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}function pl(e){const t=fl(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function hl({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!et(e)||Xe(e))return;const o=Es(e);if(o===t)return;const c=e.sessionId;c&&a(l=>({...l,[c]:t}));try{await n(xs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Bt(e),mode:t})}catch(l){const d=pl(l);c&&!d&&a(f=>{const u={...f};return o===xl(r,c)?delete u[c]:u[c]=o,u}),ml(l)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",l instanceof Error?l.message:String(l)):console.error("Failed to switch CLI view mode:",l)}}function oi(e,t){const r=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!r||e.transport!=="pty")return e;const n=t[r];return!n||e.mode===n?e:{...e,mode:n}}function Nh(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let r=!1;const n=e.map(a=>{const o=oi(a,t),c=Array.isArray(a.childSessions)?a.childSessions.map(d=>oi(d,t)):a.childSessions,l=c!==a.childSessions;return o!==a||l?(r=!0,{...o,...l?{childSessions:c}:{}}):a});return r?n:e}function xl(e,t){if(!t)return null;for(const r of e){if(r.sessionId===t&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal";for(const n of r.childSessions||[])if(n.id===t&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal"}return null}function Ch(e,t){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,o]of Object.entries(e))xl(t,a)===o&&(delete n[a],r=!0);return r?n:e}function Th({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){i.useEffect(()=>{mc()},[]);const a=i.useMemo(()=>e.map(o=>({id:o.tabKey,name:Hc(o),status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null})),[e]);return vf(a),i.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{r(l=>{const d=Date.now(),f={};for(const[u,p]of Object.entries(l))d-p<5e3&&(f[u]=p);return Object.keys(f).length===Object.keys(l).length?l:f})},5500);return()=>clearTimeout(c)},[t,r]),i.useEffect(()=>{const o=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const d=l.filter(f=>f.timestamp>c).slice(-100);return d.length===l.length?l:d})},6e4);return()=>clearInterval(o)},[n]),null}function Mh(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=r.get(n.id);if(!a){r.set(n.id,n);continue}const o=(a.workspace?1:0)+(a.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>o||(n.timestamp||0)>(a.timestamp||0))&&r.set(n.id,n)}return Array.from(r.values())}function En(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function Ah(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function ii(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?Ah(Kt(r.content)):"";return[e.id||"",e.title||"",e.status||"",t.length,String((r==null?void 0:r.id)||""),String((r==null?void 0:r.index)??""),String((r==null?void 0:r.receivedAt)??(r==null?void 0:r.timestamp)??""),n].join(":")}function Ih(e){const t=Array.isArray(e.childSessions)?e.childSessions:[];return[e.id,e.sessionId||"",e.providerSessionId||"",e.transport||"",e.mode||"",e.status||"",e.workspace||"",e.lastMessageHash||"",String(e.lastMessageAt||""),e.lastMessagePreview||"",e.lastMessageRole||"",String(e.lastUpdated||""),ii(e.activeChat),...t.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastMessageAt||""),r.lastMessagePreview||"",r.lastMessageRole||"",String(r.lastUpdated||""),ii(r.activeChat)].join(":"))].join("|")}function Lh(e,t){const r=Date.now();return e.map(n=>{const a=t[n.tabKey];return a&&r-a<5e3?{...n,messages:[],title:""}:n})}function Rh(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const o of Ss({routeId:n.routeId}))r.set(o,a);for(const o of Ss({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(o,n.streamSource==="native"?a:n);for(const o of Ss({tabKey:n.tabKey}))r.set(o,n)}return r}function _h(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Ph(e){const t=_h(e);if(!t)return`empty:${e.messages.length}`;if(t.id)return`id:${String(t.id)}`;if(t._localId)return`local:${String(t._localId)}`;const r=String(t.role||""),n=Kt(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Dh({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=i.useMemo(()=>Mh(e),[e]),o=i.useMemo(()=>Xc(e),[e]),c=i.useRef([]),l=i.useRef([]),d=i.useRef([]),f=i.useRef(new Map),u=i.useRef(new Map),p=i.useMemo(()=>{const A=new Map,g=[];for(const w of a){const{connectionState:K="new",machineName:R}=Jc(w,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),S=Ih(w),O=f.current.get(w.id);if(O&&O.ide===w&&O.sourceSignature===S&&O.connectionState===K&&O.machineName===R){A.set(w.id,O),g.push(...O.conversations);continue}const H=no(w,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),P={ide:w,sourceSignature:S,connectionState:K,machineName:R,conversations:H};A.set(w.id,P),g.push(...H)}f.current=A;const M=new Map,T=w=>{const K=Ph(w),R=u.current.get(w.tabKey);if(R&&R.signature===K)return M.set(w.tabKey,R),R.timestamp;const S={signature:K,timestamp:Mc(w)||(R==null?void 0:R.timestamp)||0};return M.set(w.tabKey,S),S.timestamp},k=[...g].sort((w,K)=>Ac(w,K,T));return u.current=M,k},[a,t,o]),m=i.useMemo(()=>{const A=Lh(p,r);return En(c.current,A)?c.current:(c.current=A,A)},[p,r]),y=i.useMemo(()=>{const A=new Map,g=Array.from(new Set(m.map(M=>M.routeId)));for(const M of g){const T=Pt(m,M);T&&A.set(M,T)}return A},[m]),N=i.useMemo(()=>{const A=new Map;for(const g of m){const M=y.get(g.routeId),T=g.streamSource==="native"&&M?M:g;for(const k of Ss({providerSessionId:g.providerSessionId,sessionId:g.sessionId}))A.set(k,T)}return A},[m,y]),h=i.useMemo(()=>Rh(m,y),[m,y]),j=i.useCallback(A=>{if(A)return N.get(A)},[N]),x=i.useCallback(A=>{if(A)return h.get(A)},[h]),b=i.useMemo(()=>{const A=m.filter(g=>!lo(n,g));return En(l.current,A)?l.current:(l.current=A,A)},[m,n]),v=i.useMemo(()=>{const A=b.map(g=>g.tabKey);return En(d.current,A)?d.current:(d.current=A,A)},[b]);return{chatIdes:a,conversations:m,visibleConversations:b,visibleTabKeys:v,resolveConversationBySessionId:j,resolveConversationByTarget:x}}function Eh({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:r,setSearchParams:n}){const a=i.useMemo(()=>{var l;return e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),o=i.useMemo(()=>{var l;return!e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),c=i.useCallback(()=>{t&&n(l=>{const d=new URLSearchParams(l);return d.delete("activeTab"),d},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:o,consumeRequestedActiveTab:c}}function $h({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){i.useEffect(()=>{rt.setIdes(e)},[e]),i.useEffect(()=>{rt.setResolveAction((a,o,c)=>{t(a,o,c).catch(()=>{})})},[t]),i.useEffect(()=>{const a=rt.onToast(o=>{r(l=>l.some(f=>f.message===o.message&&o.timestamp-f.timestamp<3e3)?l:[...l.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const c=o.duration||5e3;setTimeout(()=>r(l=>l.filter(d=>d.id!==o.id)),c)});return()=>{a()}},[r]),i.useEffect(()=>{const a=Oc.on("status_event",o=>{rt.handleRawEvent(o,"ws")});return()=>{a()}},[]),i.useEffect(()=>{var o;const a=c=>{var h;const l=c.data;if((l==null?void 0:l.type)!=="notification_action"||typeof l.action!="string"||!l.action.startsWith("approval_")||!(l.daemonId||l.targetSessionId||l.targetKey))return;const d=l.targetSessionId||l.targetKey||l.daemonId,f=n(d),u=(f==null?void 0:f.routeId)||l.daemonId;if(!u)return;const p=Number(l.buttonIndex),m=l.button||((h=f==null?void 0:f.modalButtons)==null?void 0:h[p])||"Approve",y=String(m).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),N=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(y);t(u,"resolve_action",{action:N?"approve":"reject",button:m,...Number.isFinite(p)&&{buttonIndex:p},...(f==null?void 0:f.sessionId)&&{targetSessionId:f.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(j=>console.error("[SW Action] approval failed:",j))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",a),()=>{var c;return(c=navigator.serviceWorker)==null?void 0:c.removeEventListener("message",a)}},[n,t])}const Bh="adhdev_dashboardLayout_v1",Kh="adhdev_dashboardDockview_v1",Oh="adhdev_dashboardDockviewHiddenRestore_v1",Us={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function uo(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function Wh(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function bl(e){return`${Bh}:${e}`}function Fh(e){const t=bl(e);return uo(t,null)}function Hh(e,t){try{const r=t.groupAssignments.length===0&&t.focusedGroup===0&&Object.keys(t.groupActiveTabIds).length===0&&Object.keys(t.groupTabOrders).length===0&&t.groupSizes.length===0,n=bl(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function gl(e){return`${Kh}:${e}`}function Uh(e){const t=gl(e);return uo(t,null)}function zh(e,t){try{const r=gl(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function yl(e){return`${Oh}:${e}`}function Vh(e){const t=yl(e);return uo(t,{})}function Gh(e,t){try{const r=yl(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function qh(){return{groupAssignments:[...Us.groupAssignments],focusedGroup:Us.focusedGroup,groupActiveTabIds:{...Us.groupActiveTabIds},groupTabOrders:{...Us.groupTabOrders},groupSizes:[...Us.groupSizes]}}function Yh(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function Xh(){const[e]=i.useState(()=>Wh(typeof window<"u"?window.innerWidth:1280)),[t,r]=i.useState(()=>new Map),[n,a]=i.useState(0),[o,c]=i.useState({}),[l,d]=i.useState({}),[f,u]=i.useState([]),[p,m]=i.useState(()=>typeof window<"u"&&window.innerWidth<768),[y,N]=i.useState(!1),h=i.useCallback(()=>{if(y)return;const w=Fh(e)??qh();r(new Map(w.groupAssignments)),a(w.focusedGroup),c(w.groupActiveTabIds),d(w.groupTabOrders),u(w.groupSizes),N(!0)},[y,e]);i.useEffect(()=>{y&&Hh(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:l,groupSizes:f})},[y,e,t,n,o,l,f]),i.useEffect(()=>{const w=window.matchMedia("(max-width: 767px)"),K=R=>m(R.matches);return w.addEventListener("change",K),()=>w.removeEventListener("change",K)},[]);const j=i.useCallback(w=>{r(w)},[]),x=i.useCallback(w=>{a(w)},[]),b=i.useCallback(w=>{c(w)},[]),v=i.useCallback(w=>{d(w)},[]),A=i.useCallback(w=>{u(w)},[]),g=i.useCallback(w=>{x(w)},[x]),M=i.useCallback((w,K)=>{c(R=>(R[w]??null)===(K??null)?R:{...R,[w]:K})},[]),T=i.useCallback((w,K)=>{d(R=>{const S=R[w];return Yh(S,K)?R:{...R,[w]:K}})},[]),k=i.useCallback((w,K)=>{const R=K.get(w)??0;return M(R,w),g(R),R},[g,M]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:j,focusedGroup:n,updateFocusedGroup:x,focusGroup:g,groupActiveTabIds:o,updateGroupActiveTabIds:b,setGroupActiveTab:M,groupTabOrders:l,updateGroupTabOrders:v,setGroupTabOrder:T,groupSizes:f,updateGroupSizes:A,isMobile:p,hasHydratedStoredLayout:y,hydrateStoredLayout:h,focusConversationTab:k}}function Jh(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=Ga(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Qh({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:c,setSearchParams:l,historyModalOpen:d,activeConv:f,isRefreshingHistory:u,ides:p,handleRefreshHistory:m}){const y=i.useRef(!1),N=i.useRef(!1),h=i.useRef(null),j=i.useRef(!1);i.useEffect(()=>{if(!e||y.current||t.length===0)return;if(!a){o();return}const x=r(e);x&&(c(x.tabKey,n),y.current=!0,N.current=!0,h.current!=null&&(window.clearTimeout(h.current),h.current=null),l(b=>{const v=new URLSearchParams(b);return v.delete("activeTab"),v},{replace:!0}))},[e,t,r,n,a,o,c,l]),i.useEffect(()=>{if(!(N.current||a)&&t.length!==0){if(!e){o(),N.current=!0;return}if(y.current){N.current=!0;return}if(h.current==null)return h.current=window.setTimeout(()=>{h.current=null,!(N.current||a)&&(o(),N.current=!0)},1500),()=>{h.current!=null&&(window.clearTimeout(h.current),h.current=null)}}},[e,t.length,a,o]),i.useEffect(()=>{if(!d){j.current=!1;return}if(!f||j.current||u)return;const x=p.find(b=>b.id===f.routeId);x&&(!x.chats||x.chats.length===0||Jh(x.chats,f))&&(j.current=!0,m())},[d,f,u,p,m])}function $n(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0];if((r==null?void 0:r.active)===!0)return!0;const n=Ga(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function vl({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:o}){const[c,l]=i.useState(!1),[d,f]=i.useState(!1),u=i.useCallback(async N=>{try{await e("standalone","launch_ide",{ideType:N,enableCdp:!0})}catch(h){console.error("Launch failed",h)}},[e]),p=i.useCallback(async(N,h)=>{try{const j=N||(t==null?void 0:t.daemonId)||"",x=await e(j,"switch_chat",{id:h,sessionId:h,...ts(t)}),b=x==null?void 0:x.result;if((x==null?void 0:x.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?Ws(a,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?Ws(a,`⚠️ Switch error: ${b}`):Ws(a,"⚠️ Session switch failed")}catch(j){console.error("Switch failed",j),Ws(a,`❌ Switch failed: ${j.message||"connection error"}`)}},[t,e,a]),m=i.useCallback(async()=>{if(!(!t||c)){l(!0);try{const N=Ms(t);await e(N,"new_chat",{...ts(t)}),o(h=>({...h,[t.tabKey]:Date.now()}))}catch(N){console.error("New chat failed",N)}finally{l(!1)}}},[t,c,e,o]),y=i.useCallback(async()=>{var N,h;if(!(!t||d)){f(!0);try{const j=Ms(t),x=async()=>e(j,"list_chats",{forceExpand:!0,...ts(t)});let b=await x(),v=(b==null?void 0:b.chats)||((N=b==null?void 0:b.result)==null?void 0:N.chats);$n(v,t)&&(await new Promise(A=>setTimeout(A,450)),b=await x(),v=(b==null?void 0:b.chats)||((h=b==null?void 0:b.result)==null?void 0:h.chats)),b!=null&&b.success&&Array.isArray(v)&&(n(t.routeId,v),$n(v,t)&&!$n(r,t)&&Ws(a,"⚠️ History dialog did not fully open — try once more"))}catch(j){console.error("Refresh history failed",j)}finally{f(!1)}}},[t,r,d,e,n,a]);return{isCreatingChat:c,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:p,handleNewChat:m,handleRefreshHistory:y}}function Zh(e,t){if(e.size!==t.size)return!1;for(const[r,n]of e)if(t.get(r)!==n)return!1;return!0}function ex(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function ci(e,t){const r=Object.keys(e),n=Object.keys(t);return r.length!==n.length?!1:r.every(a=>t[Number(a)]===e[Number(a)])}function Mr(e,t){const r=new Set(t),n=t.length>0?[0]:[];for(const[c,l]of e)!r.has(c)||l<=0||n.includes(l)||n.push(l);n.sort((c,l)=>c-l);const a={};n.forEach((c,l)=>{a[c]=l}),n.length===0&&(a[0]=0);const o=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const d=a[l];typeof d=="number"&&d>0&&o.set(c,d)}return{assignments:o,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function li(e,t){const r={};for(const[n,a]of Object.entries(e)){const o=t[Number(n)];typeof o=="number"&&(r[o]=a)}return r}function tx(e,t,r){if(t.length===0)return 0;if(typeof r[e]=="number")return r[e];const n=[...t].reverse().find(a=>a<e)??t[0];return r[n]??0}function sx(e,t,r){if(t.length<=1)return[];const n=t.map(c=>e[c]).filter(c=>Number.isFinite(c)),a=n.length===t.length?n:Array(r).fill(100/r),o=a.reduce((c,l)=>c+l,0);return o>0?a.map(c=>c/o*100):Array(r).fill(100/r)}function di(e,t){const r={};for(const[n,a]of Object.entries(e)){const o=Number(n);r[o>=t?o+1:o]=a}return r}function ui(e){return Array(e).fill(100/e)}function rx({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:c,isMobile:l,visibleConversations:d,visibleTabKeys:f}){const u=i.useRef(null),p=i.useMemo(()=>Mr(e,f),[e,f]),m=p.assignments,y=i.useMemo(()=>l?1:p.groupCount,[p.groupCount,l]),N=y>1,h=i.useCallback((g,M)=>{t(T=>{const k=new Map(Mr(T,f).assignments);return M===0?k.delete(g):k.set(g,M),k}),n(T=>({...T,[M]:g})),r(M)},[t,f,n,r]),j=i.useCallback(g=>{t(M=>{const T=Mr(M,f).assignments,k=new Map;for(const[w,K]of T)K!==g&&(K>g?k.set(w,K-1):k.set(w,K));return k}),c(M=>{if(M.length<=1)return[];const T=[...M];T.splice(g,1);const k=T.reduce((w,K)=>w+K,0);return k>0?T.map(w=>w/k*100):[]}),r(0)},[t,f,c,r]),x=i.useCallback((g,M)=>{M.preventDefault();const T=u.current;if(!T)return;const k=M.clientX,w=T.offsetWidth,K=o.length===y?[...o]:ui(y),R=O=>{const P=(O.clientX-k)/w*100,C=[...K];C[g]=Math.max(15,K[g]+P),C[g+1]=Math.max(15,K[g+1]-P),c(C)},S=()=>{document.removeEventListener("mousemove",R),document.removeEventListener("mouseup",S),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",R),document.addEventListener("mouseup",S)},[o,y,c]),b=i.useCallback((g,M,T)=>{if(y>=4)return;const k=T==="left"?M:M+1;t(w=>{const K=Mr(w,f).assignments,R=new Map;for(const S of d){const O=K.get(S.tabKey)??0,H=O>=k?O+1:O;H>0&&R.set(S.tabKey,H)}return k>0&&R.set(g,k),R}),c(w=>{const K=w.length===y?[...w]:ui(y),R=K[M]??100/y,S=Math.max(15,R/2),O=Math.max(15,R/2),H=[...K];H[M]=S,H.splice(k,0,O);const P=H.reduce((C,I)=>C+I,0);return H.map(C=>C/P*100)}),n(w=>{const K=di(w,k);return K[k]=g,K}),a(w=>{const K=di(w,k);return K[k]=[g],K}),r(k)},[y,t,f,d,c,n,a,r]);i.useEffect(()=>{Zh(e,m)||t(m)},[e,m,t]),i.useEffect(()=>{const{mapping:g,usedGroups:M}=p;n(T=>{const k=li(T,g);return ci(T,k)?T:k}),a(T=>{const k=li(T,g);return ci(T,k)?T:k}),r(T=>{const k=l?0:tx(T,M,g);return T===k?T:k}),c(T=>{const k=l?[]:sx(T,M,p.groupCount);return ex(T,k)?T:k})},[p,l,n,a,r,c]);const v=i.useMemo(()=>{const g=Array.from({length:y},()=>[]);for(const M of d){const T=m.get(M.tabKey)??0,k=Math.min(T,y-1);g[k].push(M)}return g},[d,m,y]),A=i.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:u,normalizedGroupAssignments:m,numGroups:y,isSplitMode:N,groupedConvs:v,moveTabToGroup:h,closeGroup:j,handleResizeStart:x,splitTabRelative:b,clearAllSplits:A}}function nx({ides:e,sendDaemonCommand:t}){const r="0.9.61",n=i.useMemo(()=>e.filter(u=>u.type!=="adhdev-daemon"?!1:al(u,r)).sort((u,p)=>Number(Zs(p,r))-Number(Zs(u,r))),[r,e]),a=i.useMemo(()=>n.some(u=>Zs(u,r)),[r,n]),[o,c]=i.useState(!1),[l,d]=i.useState({}),f=i.useCallback(async u=>{var p,m;d(y=>({...y,[u]:"upgrading"}));try{const y=await t(u,"daemon_upgrade",{});(p=y==null?void 0:y.result)!=null&&p.upgraded||(m=y==null?void 0:y.result)!=null&&m.success?d(N=>({...N,[u]:"done"})):d(N=>({...N,[u]:"error"}))}catch{d(y=>({...y,[u]:"error"}))}},[t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:o,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:f}}const wl=80;function Or(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function ax(e){return{...e,createdAt:Or(e.createdAt),updatedAt:Or(e.updatedAt,e.createdAt),lastEventAt:Or(e.lastEventAt,e.updatedAt||e.createdAt)}}function ox(e){const t=qa(e);return t==="unknown:"?e.id:t}function ix(e){return[e.type,Tc(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function cx(e,t=wl){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=ox(n),o=r.get(a);if(!o){r.set(a,n);continue}(n.updatedAt>o.updatedAt||n.updatedAt===o.updatedAt&&n.createdAt>o.createdAt)&&r.set(a,n)}return Array.from(r.values()).sort((n,a)=>{const o=a.updatedAt-n.updatedAt;return o!==0?o:a.createdAt-n.createdAt}).slice(0,Math.max(0,t))}function lx(e,t){const r=Date.now(),n=[];for(const a of e){const o=a.sessionId?t.get(a.sessionId):void 0;if(o!=null&&o.surfaceHidden)continue;const c=dn(a,t),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const d=Or(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,r),f=ix({type:l,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(o==null?void 0:o.lastUpdated)||a.lastUpdated});n.push(ax({id:f,dedupKey:f,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:gc(a),preview:zf(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return cx(n)}function dx(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function ux(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=wl}=e,a=i.useMemo(()=>lx(t,r).slice(0,Math.max(0,n)),[t,r,n]),o=i.useMemo(()=>dx(a),[a]);return{notifications:a,unreadCount:o}}function fx({notifications:e,sendDaemonCommand:t}){const r=i.useCallback(o=>{const c=e.find(d=>d.id===o),l=Math.max(Date.now(),(c==null?void 0:c.updatedAt)||0);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_session_seen",{sessionId:c.sessionId,seenAt:l}).catch(()=>{})},[e,t]),n=i.useCallback(o=>{const c=e.find(l=>l.id===o);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_notification_unread",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]),a=i.useCallback(o=>{const c=e.find(l=>l.id===o);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"delete_notification",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}function pn(...e){const t=new Set,r=[],n=a=>{const o=typeof a=="string"?a.trim():"";if(!o)return;const c=o.toLowerCase();t.has(c)||(t.add(c),r.push(o))};for(const a of e){if(Array.isArray(a)){for(const o of a)n(o);continue}n(a)}return r}function mx(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const r=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),a=(r[2]||"").replace(/[\\/]+/g,"\\");return a?`${n}:\\${a}`:`${n}:\\`}return null}function hn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=mx(r);if(n)return n}return"C:\\"}for(const r of t){const n=typeof r=="string"?r.trim():"";if(n)return n}return"~"}function px(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const r=t.includes("\\")?"\\":"/",n=t.split(/[\\/]/);return/^[A-Za-z]:$/.test(n[0]||"")?n.length<=2?`${n[0]}\\`:n.slice(0,-1).join("\\"):n.length<=2?r:n.slice(0,-1).join(r)||r}function hx(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function xn(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=hx(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 o=typeof(a==null?void 0:a.path)=="string"?a.path:r,c=o.includes("\\")?"\\":"/",l=(f,u)=>/^[A-Za-z]:\\?$/.test(f)?`${f.replace(/\\?$/,"\\")}${u}`:f==="/"||f==="\\"?`${c}${u}`:`${f.replace(/[\\/]+$/,"")}${c}${u}`,d=Array.isArray(a==null?void 0:a.files)?a.files.filter(f=>(f==null?void 0:f.type)==="directory"&&typeof(f==null?void 0:f.name)=="string").map(f=>({name:f.name,path:typeof(f==null?void 0:f.path)=="string"&&f.path.trim()?f.path:l(o,f.name)})).sort((f,u)=>f.name.localeCompare(u.name)):[];return{path:o,directories:d}}function xx(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function fi(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function bx(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function gx({ides:e,conversations:t,onOpenSession:r}){const[n,a]=i.useState(null),o=i.useCallback(c=>{a(c)},[]);return i.useEffect(()=>{if(!n)return;const c=fi(n.workspacePath),l=e.find(f=>{var N,h,j,x;if(!f||f.type==="adhdev-daemon"||xx(f.daemonId||f.id)!==n.machineId||(or(f)?"cli":js(f)?"acp":"ide")!==n.kind||String(f.agentType||f.type||"")!==n.providerType)return!1;if(n.resumeSessionId)return String(f.providerSessionId||"")===n.resumeSessionId;if(c){const b=fi(f.workspace||f.runtimeWorkspaceLabel);return b?b===c:!1}return Number(f.lastUpdated||f._lastUpdate||f.timestamp||((x=(j=(h=(N=f.activeChat)==null?void 0:N.messages)==null?void 0:h.at)==null?void 0:j.call(h,-1))==null?void 0:x.timestamp)||0)>=n.startedAt-5e3});if(!l)return;const d=Ic({entrySessionId:l.sessionId,entryInstanceId:l.instanceId,entryRouteId:l.id,conversations:t});d&&(a(null),r(d))},[t,e,r,n]),i.useEffect(()=>{if(!n)return;const c=window.setTimeout(()=>{a(l=>!l||l.startedAt!==n.startedAt?l:null)},45e3);return()=>window.clearTimeout(c)},[n]),{trackPendingLaunch:o}}function yx({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:o}){const c=i.useCallback(async(m,y)=>xn(e,m,y),[e]),l=i.useCallback(async(m,y)=>{if(!y.trim())return{ok:!1,error:"Choose a workspace path first."};try{const N=await e(m,"workspace_add",{path:y.trim()});return N!=null&&N.success?{ok:!0}:{ok:!1,error:(N==null?void 0:N.error)||"Could not save workspace"}}catch(N){return{ok:!1,error:N instanceof Error?N.message:"Could not save workspace"}}},[e]),d=i.useCallback(async(m,y,N)=>{var h;try{const j={ideType:y,enableCdp:!0};(h=N==null?void 0:N.workspacePath)!=null&&h.trim()&&(j.workspace=N.workspacePath.trim());const x=await e(m,"launch_ide",j);return!(x!=null&&x.success)&&(x==null?void 0:x.success)!==void 0?{ok:!1,error:(x==null?void 0:x.error)||"Could not launch IDE"}:(t({machineId:m,kind:"ide",providerType:y,workspacePath:(N==null?void 0:N.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(j){return{ok:!1,error:j instanceof Error?j.message:"Could not launch IDE"}}},[e,t]),f=i.useCallback(async(m,y,N,h)=>{var x,b,v;const j=Date.now();try{const A={cliType:N};(x=h==null?void 0:h.workspacePath)!=null&&x.trim()?A.dir=h.workspacePath.trim():h!=null&&h.workspaceId&&(A.workspaceId=h.workspaceId),(b=h==null?void 0:h.resumeSessionId)!=null&&b.trim()&&(A.resumeSessionId=h.resumeSessionId.trim()),Array.isArray(h==null?void 0:h.cliArgs)&&h.cliArgs.length>0&&(A.cliArgs=h.cliArgs),(v=h==null?void 0:h.initialModel)!=null&&v.trim()&&(A.initialModel=h.initialModel.trim());const g=await e(m,"launch_cli",A),M=(g==null?void 0:g.result)||g,T=(M==null?void 0:M.sessionId)||(M==null?void 0:M.id);return g!=null&&g.success&&T?(r(T),{ok:!0}):g!=null&&g.success?(t({machineId:m,kind:y,providerType:N,workspacePath:(h==null?void 0:h.workspacePath)||null,resumeSessionId:(h==null?void 0:h.resumeSessionId)||null,startedAt:j}),{ok:!0}):{ok:!1,error:(g==null?void 0:g.error)||(M==null?void 0:M.error)||`Could not launch ${y.toUpperCase()} session`}}catch(A){return bx(A)?(t({machineId:m,kind:y,providerType:N,workspacePath:(h==null?void 0:h.workspacePath)||null,resumeSessionId:(h==null?void 0:h.resumeSessionId)||null,startedAt:j}),{ok:!0}):{ok:!1,error:A instanceof Error?A.message:`Could not launch ${y.toUpperCase()} session`}}},[r,e,t]),u=i.useCallback(async(m,y)=>{if(!m||!y)return[];try{const N=await e(m,"list_saved_sessions",{providerType:y,kind:"cli",limit:30}),h=(N==null?void 0:N.result)??N;return Array.isArray(h==null?void 0:h.sessions)?h.sessions:[]}catch(N){return console.error("List saved sessions failed",N),[]}},[e]),p=i.useCallback(async m=>{await hl({conversation:n,mode:m,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[n,a,e,o]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:l,handleLaunchMachineIde:d,handleLaunchMachineProvider:f,handleListMachineSavedSessions:u,setActiveCliViewMode:p}}function vx(e){switch(e){case"notification-open":case"toast-open":case"conversation-open":case"requested-tab":return!0;case"dockview-shortcut":case"dockview-focus":case"dockview-move":case"dockview-split":case"stored-layout-restore":case"passive-tab-sync":return!1;default:return!1}}function wx(e,t,r=Date.now()){return!e||!vx(t)?null:{tabKey:e,nonce:r}}function jx({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:o,setSearchParams:c}){const[l,d]=i.useState(null),[f,u]=i.useState(null),p=i.useMemo(()=>{var j,x;if(!e){if(l){const b=t.find(v=>v.tabKey===l);if(b)return b}return r[0]}const h=n[a];if(h){const b=t.find(v=>v.tabKey===h);if(b)return b}return((j=o[a])==null?void 0:j[0])||((x=o[0])==null?void 0:x[0])},[t,l,a,n,o,e,r]),m=i.useCallback(h=>{d(h)},[]),y=i.useCallback(h=>{d(h.tabKey),c(j=>{const x=new URLSearchParams(j),b=Gf(h);return b?x.set("activeTab",b):x.delete("activeTab"),x},{replace:!0})},[c]),N=i.useCallback((h,j)=>{const x=wx(h,j);x&&u(x)},[]);return{activeConv:p,openDesktopConversation:y,requestScrollToBottom:N,scrollToBottomRequest:f,setDesktopActiveTab:m}}function kx(e){const t=e.completedKey||null,r=e.pendingKey||null;return e.shouldMarkSeen?t===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:r===e.autoReadKey?r:null}:r===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:!1,nextPendingKey:r}:{shouldSchedule:!0,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:e.autoReadKey}:{shouldSchedule:!1,shouldCancelPending:!!r,nextPendingKey:null}}function Sx(e){const t=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,o=[e.tabKey,e.historySessionId||"",t,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&t&&t!==r),autoReadKey:o,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function Nx({activeConv:e,isMobile:t,liveSessionInboxState:r,sendDaemonCommand:n}){const a=i.useRef(null),o=i.useRef(null),c=i.useRef(null),l=i.useRef(null),d=i.useRef(null);i.useEffect(()=>{const f=()=>{c.current&&(clearTimeout(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),o.current=null};if(t){f(),a.current=null;return}if(!(e!=null&&e.sessionId)){f(),a.current=null;return}const u=Yr(e,r),p=Sx({tabKey:e.tabKey,historySessionId:ur(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:ss(e),liveState:u}),m=p.autoReadKey,y=kx({autoReadKey:m,shouldMarkSeen:p.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!p.shouldMarkSeen){y.shouldCancelPending&&f(),a.current=m;return}if(!y.shouldSchedule)return;y.shouldCancelPending&&f();const N=()=>{if(document.visibilityState!=="visible"||a.current===m)return;a.current=m,o.current=null,c.current=null,l.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const j=p.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:j,completionMarker:p.completionMarker}).catch(()=>{})};if(o.current=y.nextPendingKey,document.visibilityState==="visible"){c.current=setTimeout(N,1500);const j=()=>{document.visibilityState!=="visible"&&c.current&&(clearTimeout(c.current),c.current=null)};d.current=j,document.addEventListener("visibilitychange",j);return}const h=()=>{document.visibilityState==="visible"&&(l.current&&clearTimeout(l.current),l.current=setTimeout(N,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=h,document.addEventListener("visibilitychange",h)},[e,t,r,n]),i.useEffect(()=>()=>{c.current&&clearTimeout(c.current),l.current&&clearTimeout(l.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function Bn(e){if(!e)return"";const t=String(e.workspacePath||"").trim();if(t)return t;const r=String(e.workspaceName||"").trim();return/^(?:~\/|\/|[A-Za-z]:[\\/])/.test(r)?r:""}function Cx({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:o,setToasts:c,setClearedTabs:l,setSearchParams:d}){var I;const[f,u]=i.useState(!1),[p,m]=i.useState([]),[y,N]=i.useState(()=>xt()),[h,j]=i.useState(!1),[x,b]=i.useState(null),v=i.useRef(null),A=i.useMemo(()=>r||t||e,[e,r,t]),g=!!A&&et(A)&&!Xe(A),M=i.useMemo(()=>{if(!A||!g)return null;const W=A.daemonId||A.routeId||"",E=Bt(A),$=Bn(A);return`${W}:${E}:${A.providerSessionId||""}:${$}`},[A,g]),T=i.useMemo(()=>!A||!g?"":Bn(A),[A,g]),{isCreatingChat:k,isRefreshingHistory:w,handleSwitchSession:K,handleNewChat:R,handleRefreshHistory:S}=vl({sendDaemonCommand:a,activeConv:A,chats:(I=n.find(W=>W.id===(A==null?void 0:A.routeId)))==null?void 0:I.chats,updateRouteChats:o,setToasts:c,setClearedTabs:l}),O=i.useCallback(()=>{u(!0)},[]),H=i.useCallback(()=>{u(!1)},[]),P=i.useCallback(async()=>{if(!(!A||!g||h)){j(!0);try{const W=A.daemonId||A.routeId,E=Bt(A),$=Bn(A),z=await a(W,"list_saved_sessions",{agentType:E,providerType:E,kind:"cli",limit:50,...A.providerSessionId?{providerSessionId:A.providerSessionId}:{},...$?{workspace:$}:{}}),J=(z==null?void 0:z.result)??z;m(Array.isArray(J==null?void 0:J.sessions)?J.sessions:[])}catch(W){console.error("Refresh saved sessions failed",W),m([])}finally{j(!1)}}},[A,h,g,a]);i.useEffect(()=>{if(!f){v.current=null;return}if(!g){v.current=null,m([]),j(!1);return}!M||h||v.current!==M&&(v.current=M,P())},[P,f,h,g,M]);const C=i.useCallback(async W=>{if(!A||!g||!W.providerSessionId||!W.workspace)return;const E=A.daemonId||A.routeId,$=Bt(A);try{b(W.providerSessionId);const z=await a(E,"launch_cli",{cliType:$,dir:W.workspace,resumeSessionId:W.providerSessionId,initialModel:uc(W.summaryMetadata,"model",{preferShortValue:!0})||void 0}),J=(z==null?void 0:z.result)??z,he=typeof(J==null?void 0:J.sessionId)=="string"?J.sessionId:typeof(J==null?void 0:J.id)=="string"?J.id:"";he&&d(ce=>{const te=new URLSearchParams(ce);return te.set("activeTab",he),te},{replace:!0}),H()}catch(z){console.error("Resume saved session failed",z)}finally{b(null)}},[H,A,g,a,d]);return{historyModalOpen:f,openHistoryModal:O,closeHistoryModal:H,historyTargetConv:A,isSavedSessionHistoryTarget:g,isHistoryCreatingChat:k,isHistoryRefreshingHistory:w,handleHistorySwitchSession:K,handleHistoryNewChat:R,handleHistoryRefresh:S,savedHistorySessions:p,savedHistoryFilters:y,setSavedHistoryFilters:N,missingWorkspaceResumePath:T,isSavedHistoryLoading:h,resumingSavedHistorySessionId:x,handleRefreshSavedHistory:P,handleResumeSavedHistorySession:C}}function Tx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l}){const[d,f]=i.useState(null),[u,p]=i.useState(null),m=i.useMemo(()=>{if(e||!n)return null;const x=l(n);return x&&!et(x)&&!Xe(x)?x:null},[e,n,l]),y=i.useMemo(()=>{const x=d==null?void 0:d.routeId;if(!x)return null;const b=d!=null&&d.tabKey?o.find(v=>v.tabKey===d.tabKey):a?o.find(v=>v.tabKey===a):null;return(b==null?void 0:b.routeId)===x?b:Pt(o,x)},[o,d,a]),N=i.useMemo(()=>{if(y)return c.find(x=>x.id===y.routeId)},[c,y]);i.useEffect(()=>{m&&(f({routeId:m.routeId,tabKey:Ko(m)}),p(m),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,m]);const h=i.useCallback(x=>{x&&(f({routeId:x.routeId,tabKey:Ko(x)}),p(x))},[]),j=i.useCallback(()=>{f(null),p(null)},[]);return{remoteDialogConv:y,remoteDialogIdeEntry:N,remoteDialogActiveConv:u,setRemoteDialogActiveConv:p,openRemoteDialog:h,closeRemoteDialog:j}}function Mx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l,activeConv:d,sendDaemonCommand:f}){const{remoteDialogConv:u,remoteDialogIdeEntry:p,remoteDialogActiveConv:m,setRemoteDialogActiveConv:y,openRemoteDialog:N,closeRemoteDialog:h}=Tx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l}),[j,x]=i.useState(!1),[b,v]=i.useState(null),A=i.useCallback(async T=>{const k=T||d;!k||!et(k)&&!Xe(k)||(v(k),x(!0))},[d]),g=i.useCallback(()=>{x(!1),v(null)},[]),M=i.useCallback(async T=>{const k=b||d;if(!k||!et(k)&&!Xe(k)){g();return}x(!1);try{const w=Bt(k),K=k.routeId||k.daemonId||"";await f(K,"stop_cli",{cliType:w,targetSessionId:k.sessionId,mode:T})}catch(w){console.error("Stop CLI failed:",w)}finally{v(null)}},[d,g,b,f]);return{remoteDialogConv:u,remoteDialogIdeEntry:p,remoteDialogActiveConv:m,setRemoteDialogActiveConv:y,openRemoteDialog:N,closeRemoteDialog:h,cliStopDialogOpen:j,cliStopTargetConv:b,requestCliStop:A,cancelCliStop:g,confirmCliStop:M}}function Kn(e,t=!0){return(e??!0)&&t}const fo=i.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:o,handleModalButton:c,handleRelaunch:l,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u=null,handleFocusAgent:p,isFocusingAgent:m,actionLogs:y,userName:N,scrollToBottomRequestNonce:h,isInputActive:j=!0,isVisible:x=!0}){const b=n,v=!n,A=Kn(x,b),g=Kn(x,v),M=Kn(x),T=dl(t),k=T.status||T.modalMessage||T.modalButtons?{...t,...T.status?{status:T.status}:{},...T.modalMessage!==void 0?{modalMessage:T.modalMessage}:{},...T.modalButtons!==void 0?{modalButtons:T.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(ic,{activeConv:k,onModalButton:c}),k.transport!=="pty"&&k.transport!=="acp"&&k.cdpConnected===!1?s.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:s.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[s.jsx("span",{className:"text-sm",children:s.jsx(nr,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:l,children:"Relaunch with CDP"})]})}):null,k.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:b?"visible":"hidden",pointerEvents:b?"auto":"none"},children:s.jsx(fp,{activeConv:k,clearToken:r,terminalRef:o,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u,isVisible:A,isInputActive:j&&A})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:v?"visible":"hidden",pointerEvents:v?"auto":"none"},children:s.jsx(wa,{activeConv:k,ideEntry:a,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u,handleFocusAgent:p,isFocusingAgent:m,actionLogs:y,userName:N,scrollToBottomRequestNonce:h,isInputActive:j&&g,isVisible:g})})]}):s.jsx(wa,{activeConv:k,ideEntry:a,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u,handleFocusAgent:p,isFocusingAgent:m,actionLogs:y,userName:N,scrollToBottomRequestNonce:h,isInputActive:j&&M,isVisible:M})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function Ax({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:o,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:d,onBack:f,onOpenNativeConversation:u,onOpenMachine:p,onOpenHistory:m,onOpenRemote:y,onHideConversation:N,onStopCli:h,cliViewMode:j,onSetCliViewMode:x,handleSendChat:b,handleFocusAgent:v,handleModalButton:A,handleRelaunch:g}){const M=i.useRef(null),T=et(e)&&!t,k=T&&j==="terminal",w=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${w} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:f,type:"button","aria-label":"Back",children:s.jsx(_a,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:it(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(Lc,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>p(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[T&&j&&s.jsx(Qa,{mode:j,onChange:x,compact:!0}),T&&h&&s.jsx("button",{onClick:()=>{h(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(St,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>m(e),type:"button",children:s.jsx(Pa,{size:14})}),!t&&!T&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>y(e),type:"button",children:s.jsx(Tt,{size:14})}),N&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>N(e),type:"button",title:"Close chat",children:s.jsx(St,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(fo,{activeConv:e,clearToken:0,isCliTerminal:k,ideEntry:n,terminalRef:M,handleModalButton:A,handleRelaunch:g,handleSendChat:b,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:v,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const On={unix:{cmd:"curl -fsSL https://adhf.dev/install | sh",shell:"Terminal",prompt:"$ "},powershell:{cmd:"irm https://adhf.dev/install.ps1 | iex",shell:"PowerShell",prompt:"PS> "},cmd:{cmd:"curl -fsSL https://adhf.dev/install.cmd -o %TEMP%\\adhdev.cmd && %TEMP%\\adhdev.cmd",shell:"CMD",prompt:"> "}};function Ix(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function jl(){const[e,t]=i.useState("unix"),[r,n]=i.useState("powershell"),[a,o]=i.useState(!1),c=e==="unix"?"unix":r;i.useEffect(()=>{t(Ix())},[]);const l=i.useCallback(()=>{navigator.clipboard.writeText(On[c].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!1),2e3)},[c]);return s.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("unix"),children:"🍎🐧 macOS / Linux"}),s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("windows"),children:"🪟 Windows"})]}),e==="windows"&&s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("powershell"),children:"⚡ PowerShell"}),s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("cmd"),children:">_ CMD"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:l,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:On[c].prompt}),s.jsx("span",{className:"flex-1 break-all",children:On[c].cmd}),s.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:a?"✓":"📋"})]}),s.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",s.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function kl({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Tt},{key:"chats",label:"Chats",icon:Ut}];return s.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:s.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:n,label:a,icon:o})=>{const c=e===n;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${c?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(n),type:"button","aria-pressed":c,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(o,{size:15})}),s.jsx("span",{children:a})]},n)})})})}function Ar({title:e,className:t=""}){return s.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${t}`,children:s.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function gs({children:e,className:t=""}){return s.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${t}`,children:e})}function zs({icon:e,title:t,subtitle:r,children:n}){return s.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[s.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function Ir({item:e,type:t,getAvatarText:r,onOpenConversation:n,onHideConversation:a,onCollectChatDebugBundle:o}){const c=t==="needs_attention"||t==="task_complete",l=t==="working",d=t==="earlier",f=t==="task_complete",{isReconnecting:u,isConnecting:p}=Ds(e.conversation),m=it(e.conversation),y=As(e.conversation),N=Fc(e.conversation,{requiresAction:t==="needs_attention"}),h=c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":l?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":d?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",j=c?"bg-accent-primary shadow-glow":l?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":d?"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",x=d?"text-text-secondary":"text-text-primary",b=d?"text-text-muted":"text-text-secondary",v=d?"text-text-secondary opacity-80":"text-text-muted",A=d?"text-text-muted opacity-80":"text-text-muted",g=!l&&!f,M="text-[color:var(--status-warning)]",T=k=>{if(!o)return;k.preventDefault(),k.stopPropagation();const w=o==null?void 0:o(e.conversation);Promise.resolve(w).catch(K=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",K)})};return s.jsxs("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${h}`,children:[s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left relative ${a?"pb-2":""}`,onClick:()=>n(e.conversation),onContextMenu:T,type:"button",children:[c||l?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${j}`,style:c?{color:"var(--accent-on-primary)"}:void 0,children:r(m)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${x}`,children:m}),g&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${A}`,children:oc(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${b}`,children:[s.jsx("span",{className:"truncate",children:y}),s.jsx(Is,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),u?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${M} animate-pulse`,children:"Reconnecting…"})]}):p?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):N==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:M,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${v}`,children:e.preview})]}),c&&!f&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),f&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Done"}),l&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Live"})]}),a&&s.jsx("div",{className:"flex justify-end px-4 pb-3 -mt-1",children:s.jsxs("button",{type:"button",className:"mobile-inbox-hide-button inline-flex items-center gap-1.5 rounded-full border border-border-subtle bg-bg-primary/70 px-2.5 py-1 text-[11px] font-semibold text-text-muted hover:border-border-default hover:text-text-primary",onClick:k=>{k.preventDefault(),k.stopPropagation(),a(e.conversation)},"aria-label":`Hide ${m}`,title:"Hide conversation",children:[s.jsx(Da,{size:12}),s.jsx("span",{children:"Hide"})]})})]},e.conversation.tabKey)}function mi({size:e=32}){return s.jsx("div",{className:"flex flex-col items-center gap-2.5",children:s.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}})})}function Lx({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:o,machineCards:c,getAvatarText:l,actionLogs:d,sendDaemonCommand:f,onOpenConversation:u,onShowAllHidden:p,onHideConversation:m,onOpenNewSession:y,onOpenMachine:N,onOpenSettings:h,onSectionChange:j,wsStatus:x="connected",isStandalone:b=!1,onCollectChatDebugBundle:v}){const A=x==="disconnected"||x==="reconnecting"||x==="offline"||x==="auth_failed",g=c.length>0,M=t.length>0||r.length>0||n.length>0||a.length>0,T=e==="machines"?"Machines":"Chats",k=b?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",w=b?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",K=i.useCallback(async S=>{const O=Ms(S);if(!O)return;const H=Array.isArray(S.messages)?S.messages:[],P=kc({activeConv:S,visibleMessages:H,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:H.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),C=await f(O,"get_chat_debug_bundle",{...ts(S),delivery:"daemon_file",frontendSnapshot:P}),I=Qr(C),W=Cc(I),E=await Nc(W);E==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),rt.showToast(Sc(I,{locatorCopyStatus:E}),E==="failed"?"warning":"success")},[d,f]),R=v||K;return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${k}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:T}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||r.length>0)&&s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[s.jsx(cn,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:h,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:s.jsx(on,{size:18})})]})]})}),s.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${w}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:A?s.jsx(zs,{icon:s.jsx(mi,{}),title:x==="offline"?"Network offline":x==="auth_failed"?"Session expired":"Reconnecting",subtitle:x==="offline"?"Waiting for network…":x==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):c.length===0?s.jsx(zs,{icon:s.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&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(jl,{})})}):s.jsx(gs,{children:c.map((S,O)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${O>0?"border-t border-border-subtle/70":""}`,onClick:()=>N(S.id),type:"button",children:[s.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:l(S.label)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:S.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:S.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[S.unread," new"]}):S.total>0?`${S.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:S.subtitle}),S.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[S.total," chat",S.total!==1?"s":"",S.unread>0?` · ${S.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},S.id))})}),e==="chats"&&t.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(Ar,{title:"Needs attention",className:"mb-0"}),s.jsx(gs,{children:t.map((S,O)=>s.jsx("div",{className:O>0?"border-t border-border-subtle/70":"",children:s.jsx(Ir,{item:S,type:"needs_attention",getAvatarText:l,onOpenConversation:u,onHideConversation:m,onCollectChatDebugBundle:R})},S.conversation.tabKey))})]}),e==="chats"&&r.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(Ar,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(gs,{children:r.map((S,O)=>s.jsx("div",{className:O>0?"border-t border-border-subtle/70":"",children:s.jsx(Ir,{item:S,type:"task_complete",getAvatarText:l,onOpenConversation:u,onHideConversation:m,onCollectChatDebugBundle:R})},S.conversation.tabKey))})]}),e==="chats"&&n.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(Ar,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(gs,{children:n.map((S,O)=>s.jsx("div",{className:O>0?"border-t border-border-subtle/70":"",children:s.jsx(Ir,{item:S,type:"working",getAvatarText:l,onOpenConversation:u,onHideConversation:m,onCollectChatDebugBundle:R})},S.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&s.jsx(Ar,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(gs,{children:a.map((S,O)=>s.jsx("div",{className:O>0?"border-t border-border-subtle/70":"",children:s.jsx(Ir,{item:S,type:"earlier",getAvatarText:l,onOpenConversation:u,onHideConversation:m,onCollectChatDebugBundle:R})},S.conversation.tabKey))}):M?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):A?s.jsx(zs,{icon:s.jsx(mi,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):g?s.jsx(zs,{icon:s.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:s.jsx(Ut,{size:20})}),title:"No conversations yet",subtitle:zc,children:y&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:y,"aria-label":Et,title:Et,children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s.jsx("span",{children:Et})]})}):s.jsx(zs,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),e==="chats"&&o.length>0&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(gs,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:"Hidden tabs"}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[o.length," collapsed ",o.length===1?"conversation":"conversations"]})]}),s.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-[12px] font-semibold text-accent-primary hover:border-border-default",onClick:p,children:"Restore all"})]})})})]}),e==="chats"&&y&&M&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:y,"aria-label":Et,title:Et,children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),s.jsx(kl,{section:e,onSectionChange:j})]})}function Rx(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 Sl(e){const t=[e.workspace||"Workspace unknown"],r=fs(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=Rx(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function bn({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:o="",confirmLabel:c="Use this folder",onClose:l,onNavigate:d,onConfirm:f}){const[u,p]=i.useState(r);i.useEffect(()=>{p(r)},[r]);const m=px(r),y=u.trim();return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:l,"aria-label":"Close folder browser",children:s.jsx(St,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!m||a||d(m)},disabled:!m||a,children:[s.jsx(_a,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:N=>p(N.target.value),onKeyDown:N=>{N.key!=="Enter"||!y||a||(N.preventDefault(),d(y))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!y||a||d(y)},disabled:!y||a,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):n.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:n.map(N=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>d(N.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Cs,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:N.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:N.path})]})]},N.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>f(y||r),disabled:!y&&!r||a,children:c})]})]})})}function mo({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:d=!1,showArgsInput:f,argsValue:u,onArgsChange:p,showModelInput:m,modelValue:y,onModelChange:N,historyProviderNode:h,onConfirm:j,onCancel:x}){const b=n==null?void 0:n.find(v=>v.key===a);return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:x,"aria-label":"Close launch confirmation",children:s.jsx(St,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[n&&n.length>0&&o&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),s.jsx("select",{value:a||"",onChange:v=>o(v.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:d,children:n.map(v=>s.jsx("option",{value:v.key,children:v.label},v.key))}),(b==null?void 0:b.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:b.description})]}),h,r.map(v=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:v.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:v.value})]},`${v.label}:${v.value}`)),m&&N&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),s.jsx("input",{type:"text",value:y||"",onChange:v=>N(v.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:d})]}),f&&p&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:u||"",onChange:v=>p(v.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:d})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:x,disabled:d,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:j,disabled:d,children:[s.jsx($a,{size:14}),d?l:c]})]})]})})}function pi(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function cs(e){const{machine:t,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,o=[];a&&o.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const d of t.workspaces||[])o.push({key:`saved:${d.id}`,label:`${d.id===t.defaultWorkspaceId?"⭐ ":""}${pi(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const c=(r==null?void 0:r.trim())||"",l=c?(t.workspaces||[]).find(d=>d.path===c):null;if(c&&!l&&o.push({key:`custom:${c}`,label:pi(c),description:c,workspaceId:null,workspacePath:c}),n){const d=`saved:${n}`;if(o.some(f=>f.key===d))return{options:o,selectedKey:d}}return l?{options:o,selectedKey:`saved:${l.id}`}:c?{options:o,selectedKey:`custom:${c}`}:{options:o,selectedKey:"__home__"}}function _x(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Px(e){return[_x(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Dx(e){return e.lastLaunchedAt?ln(e.lastLaunchedAt):""}function Nl(e){return{metaText:Px(e),updatedLabel:Dx(e)}}function Wn(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function Ex({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:o}){var Qe,lt,dt,ut;const c=fr(),[l,d]=i.useState(!1),f=(((Qe=e.detectedIdes)==null?void 0:Qe.length)||0)>0,u=i.useMemo(()=>(e.workspaces||[]).map(Te=>({id:Te.id,path:Te.path,label:Te.label})),[e]),p=e.defaultWorkspaceId||null,[m,y]=i.useState(p||((lt=u[0])==null?void 0:lt.id)||""),[N,h]=i.useState(""),[j,x]=i.useState(""),[b,v]=i.useState([]),[A,g]=i.useState(!1),[M,T]=i.useState(""),[k,w]=i.useState(!1),[K,R]=i.useState(Wn(f,t.length,r.length)),S=i.useRef(null),[O,H]=i.useState(null),P=i.useRef("__home__"),[C,I]=i.useState("__home__"),[W,E]=i.useState(""),[$,z]=i.useState(""),[J,he]=i.useState(""),[ce,te]=i.useState([]),[ye,fe]=i.useState(()=>xt().textQuery),[be,X]=i.useState(()=>xt().workspaceQuery),[ae,ge]=i.useState(()=>xt().modelQuery),[ee,de]=i.useState(()=>xt().resumableOnly),[we,ue]=i.useState(()=>xt().sortMode),[xe,se]=i.useState(!1),[ie,re]=i.useState(!1),q=i.useRef(null),Y=i.useRef(null);i.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const le=m==="__custom__"?N.trim():((dt=u.find(Te=>Te.id===m))==null?void 0:dt.path)||"",ke=m==="__custom__"&&!!le&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),Z=m!=="__custom__"&&((ut=u.find(Te=>Te.id===m))==null?void 0:ut.path)||"",Ce=i.useMemo(()=>(e.recentLaunches||[]).map(Te=>Te.workspace),[e]),Ee=i.useCallback(async Te=>{g(!0),T("");try{const Ge=await a(Te);x(Ge.path),h(Ge.path),v(Ge.directories)}catch(Ge){T(Ge instanceof Error?Ge.message:"Could not load folder")}finally{g(!1)}},[a]),We=i.useCallback(()=>{var Ge;y("__custom__"),w(!0);const Te=hn(e.platform,pn(N.trim(),Z,Ce,e.defaultWorkspacePath,(Ge=u.find(Ze=>Ze.id===p))==null?void 0:Ge.path,u.map(Ze=>Ze.path)));Ee(Te)},[N,p,Ee,Ce,Z,e.platform,u]),Fe=i.useCallback(Te=>{if(Te!=null&&Te.workspaceId){y(Te.workspaceId),h("");return}if(Te!=null&&Te.workspacePath){y("__custom__"),h(Te.workspacePath);return}y(""),h("")},[]),D=i.useCallback(Te=>{if(y(Te),Te==="__custom__"){We();return}h("")},[We]),Se=i.useCallback(Te=>{y("__custom__"),h(Te)},[]),Ae=i.useCallback((Te,Ge)=>{S.current=Ge,P.current=Te.selectedWorkspaceKey||"__home__",I(Te.selectedWorkspaceKey||"__home__"),E(Te.initialArgs||""),z(Te.initialModel||""),he(""),te([]);const Ze=Te.providerType?`${e.id}:${Te.providerType}`:null;if(kp(Y.current,Ze)){const qe=xt();fe(qe.textQuery),X(qe.workspaceQuery),ge(qe.modelQuery),de(qe.resumableOnly),ue(qe.sortMode)}Y.current=Ze,H(Te),Te.providerType&&o&&(se(!0),o(Te.providerType).then(qe=>te(qe||[])).catch(qe=>console.warn("Failed to load saved sessions",qe)).finally(()=>se(!1)))},[o,e.id]),Le=i.useMemo(()=>Vc(ce,{textQuery:ye,workspaceQuery:be,modelQuery:ae,resumableOnly:ee,sortMode:we}),[ae,ee,ce,we,ye,be]);i.useEffect(()=>{J&&(Le.some(Te=>Te.providerSessionId===J)||he(""))},[Le,J]);const Pe=i.useCallback(()=>{S.current&&(re(!0),S.current().finally(()=>{S.current=null,re(!1),H(null)}))},[]),He=i.useCallback(()=>{S.current=null,H(null)},[]),Ue=i.useCallback(Te=>{P.current=Te,I(Te)},[]);return i.useEffect(()=>{var Te;q.current!==e.id&&(q.current=e.id,y(p||((Te=u[0])==null?void 0:Te.id)||"__custom__"),h(""),x(""),v([]),T(""),w(!1),fe(xt().textQuery),X(xt().workspaceQuery),ge(xt().modelQuery),de(xt().resumableOnly),ue(xt().sortMode),Y.current=null,R(Wn(f,t.length,r.length)))},[r.length,t.length,p,f,e.id,u]),i.useEffect(()=>{var Te;m!=="__custom__"&&(m&&u.some(Ge=>Ge.id===m)||y(p||((Te=u[0])==null?void 0:Te.id)||"__custom__"))},[p,m,u]),i.useEffect(()=>{K==="ide"&&f||K==="cli"&&t.length>0||K==="acp"&&r.length>0||R(Wn(f,t.length,r.length))},[K,r.length,t.length,f]),{showAllRecent:l,setShowAllRecent:d,hasIdeOptions:f,workspaceRows:u,defaultWorkspaceId:p,workspaceChoice:m,customWorkspacePath:N,browseCurrentPath:j,browseDirectories:b,browseBusy:A,browseError:M,browseDialogOpen:k,activeLauncherKind:K,launchConfirm:O,launchConfirmWorkspaceKeyRef:P,launchConfirmWorkspaceKey:C,launchConfirmArgs:W,launchConfirmModel:$,launchConfirmResumeId:J,launchConfirmSavedSessions:ce,launchConfirmTextFilter:ye,launchConfirmWorkspaceFilter:be,launchConfirmModelFilter:ae,launchConfirmResumableOnly:ee,launchConfirmSortMode:we,filteredLaunchConfirmSavedSessions:Le,launchConfirmSessionsLoading:xe,launchConfirmBusy:ie,resolvedWorkspacePath:le,canCreateMissingWorkspace:ke,openBrowseDialog:We,loadBrowsePath:Ee,handleWorkspaceChoiceChange:D,chooseCustomWorkspacePath:Se,setCustomWorkspacePath:h,setBrowseDialogOpen:w,setActiveLauncherKind:R,openLaunchConfirm:Ae,handleConfirmLaunch:Pe,closeLaunchConfirm:He,setWorkspaceSelectionFromOption:Fe,setLaunchConfirmWorkspaceKeyAndSync:Ue,setLaunchConfirmArgs:E,setLaunchConfirmModel:z,setLaunchConfirmResumeId:he,setLaunchConfirmTextFilter:fe,setLaunchConfirmWorkspaceFilter:X,setLaunchConfirmModelFilter:ge,setLaunchConfirmResumableOnly:de,setLaunchConfirmSortMode:ue}}function $x({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:c,machineAction:l,isStandalone:d,section:f,showBottomNav:u,onBack:p,onSectionChange:m,onOpenConversation:y,onOpenRecent:N,onOpenMachineDetails:h,onMachineUpgrade:j,onLaunchDetectedIde:x,onAddWorkspace:b,onBrowseDirectory:v,onLaunchWorkspaceProvider:A,onListSavedSessions:g}){const M=C=>C==="ide"?"IDE":C==="cli"?"CLI":"ACP",T=r.slice(0,4),k=t.slice(0,3),w=Ex({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:v,onListSavedSessions:g}),K=i.useMemo(()=>T.map(C=>{const{metaText:I,updatedLabel:W}=Nl(C);return{key:`recent-launch:${C.id}`,primary:C.label,secondary:I,updatedLabel:W,onClick:()=>{const{options:E,selectedKey:$}=cs({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspacePath:C.workspace});w.openLaunchConfirm({title:C.kind==="ide"?ns("restart-ide",C.label):C.providerSessionId?to(C.label):ns("start-fresh",C.label),description:C.kind==="ide"?as("restart-ide"):C.providerSessionId?so():as("start-fresh"),confirmLabel:C.kind==="ide"?Ls("restart-ide"):C.providerSessionId?tn(!0):Ls("start-fresh"),busyLabel:C.kind==="ide"?Rs("restart-ide"):C.providerSessionId?Za(!0):Rs("start-fresh"),workspaceOptions:E,selectedWorkspaceKey:$,details:[{label:"Mode",value:M(C.kind)},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]},async()=>{const z=E.find(J=>J.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(z),await N({...C,workspace:(z==null?void 0:z.workspacePath)??null})})}}}),[w,N,T]),R=i.useMemo(()=>k.map(C=>({key:`recent-chat:${C.conversation.tabKey}`,primary:it(C.conversation),secondary:cp(C.conversation,{timestampLabel:C.timestamp?oc(C.timestamp):null}),unread:C.unread,onClick:()=>y(C.conversation)})),[y,k]),S=w.showAllRecent?K:K.slice(0,4),O=K.length>0,H=R.length>0,P=d?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${P} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:s.jsx(_a,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:Ct(e,{fallbackId:e.id})}),s.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[H&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:R.map(C=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${C.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:C.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))})]}),O&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:S.map(C=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:C.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:C.primary}),C.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:C.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))}),K.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>w.setShowAllRecent(C=>!C),children:w.showAllRecent?"Show fewer":`Show ${K.length-4} more`})})]}),(w.hasIdeOptions||n.length>0||a.length>0)&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:s.jsxs("div",{className:"flex flex-col gap-2.5 w-full p-3.5 rounded-2xl border border-border-default/80 bg-surface-primary/90",children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),s.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),s.jsx("select",{value:w.workspaceChoice,onChange:C=>w.handleWorkspaceChoiceChange(C.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:w.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[w.workspaceRows.map(C=>s.jsxs("option",{value:C.id,children:[C.id===w.defaultWorkspaceId?"⭐ ":"",un(C.path,C.label)||C.path]},C.id)),s.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):s.jsx("option",{value:"__custom__",children:"Select workspace…"})}),w.workspaceChoice==="__custom__"&&s.jsxs("div",{className:"flex flex-col gap-2.5",children:[s.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Cs,{size:17})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),s.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:w.resolvedWorkspacePath||w.browseCurrentPath||"No folder selected yet."})]})]})}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-secondary text-[12px] font-bold",onClick:w.openBrowseDialog,children:"Select workspace…"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-accent-primary/30 bg-accent-primary/10 text-text-primary text-[12px] font-bold disabled:opacity-40",onClick:()=>{w.resolvedWorkspacePath&&b(w.resolvedWorkspacePath)},disabled:!w.resolvedWorkspacePath||w.browseBusy,children:"Save as workspace"})]})]}),w.resolvedWorkspacePath&&s.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:w.resolvedWorkspacePath})]})}),s.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[w.hasIdeOptions&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${w.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:()=>w.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${w.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:()=>w.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${w.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:()=>w.setActiveLauncherKind("acp"),children:"ACP"})]}),w.activeLauncherKind&&s.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[s.jsx("div",{className:"text-xs font-bold text-text-secondary",children:w.activeLauncherKind==="ide"?"Choose an IDE":w.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),s.jsx("div",{className:"grid grid-cols-1 gap-2",children:w.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(C=>s.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const{options:I,selectedKey:W}=cs({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspaceId:w.workspaceChoice!=="__custom__"?w.workspaceChoice:null,currentWorkspacePath:w.resolvedWorkspacePath});w.openLaunchConfirm({title:`Launch ${C.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:I,selectedWorkspaceKey:W,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:C.name}]},async()=>{const E=I.find($=>$.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(E),x(C.type,{workspacePath:(E==null?void 0:E.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:C.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:w.resolvedWorkspacePath||"Use selected workspace"})]},C.type)):(w.activeLauncherKind==="cli"?n:a).map(C=>s.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const I=w.activeLauncherKind==="cli"?"cli":"acp",{options:W,selectedKey:E}=cs({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspaceId:w.workspaceChoice!=="__custom__"?w.workspaceChoice:null,currentWorkspacePath:w.resolvedWorkspacePath});w.openLaunchConfirm({title:`Launch ${C.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${I.toUpperCase()}`,workspaceOptions:W,selectedWorkspaceKey:E,details:[{label:"Mode",value:I.toUpperCase()},{label:"Provider",value:C.displayName}],showArgsInput:!0,showModelInput:I==="acp",initialArgs:"",initialModel:"",providerType:C.type},async()=>{const $=W.find(z=>z.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption($),A(I,C.type,{workspaceId:($==null?void 0:$.workspaceId)??null,workspacePath:($==null?void 0:$.workspacePath)??null,args:w.launchConfirmArgs,model:w.launchConfirmModel,resumeSessionId:w.launchConfirmResumeId||null})})},children:[s.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[C.icon?`${C.icon} `:"",C.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:w.resolvedWorkspacePath||"Use selected workspace"})]},C.type))})]}),l.message&&s.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${l.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[l.message,w.canCreateMissingWorkspace&&s.jsx("div",{className:"mt-2",children:s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[34px] px-4 rounded-lg bg-surface-primary text-text-primary font-bold text-xs",onClick:()=>b(w.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:j,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:h,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),w.browseDialogOpen&&s.jsx(bn,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:w.browseCurrentPath,directories:w.browseDirectories,busy:w.browseBusy,error:w.browseError,confirmLabel:"Use this folder",onClose:()=>w.setBrowseDialogOpen(!1),onNavigate:C=>{w.loadBrowsePath(C)},onConfirm:C=>{w.chooseCustomWorkspacePath(C),w.setBrowseDialogOpen(!1)}}),w.launchConfirm&&s.jsx(mo,{title:w.launchConfirm.title,description:w.launchConfirm.description,details:w.launchConfirm.details,workspaceOptions:w.launchConfirm.workspaceOptions,selectedWorkspaceKey:w.launchConfirmWorkspaceKey,onWorkspaceChange:w.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:w.launchConfirm.providerType?tn(!!w.launchConfirmResumeId):w.launchConfirm.confirmLabel,busyLabel:w.launchConfirm.providerType?void 0:w.launchConfirm.busyLabel,busy:w.launchConfirmBusy,showArgsInput:w.launchConfirm.showArgsInput,argsValue:w.launchConfirmArgs,onArgsChange:w.setLaunchConfirmArgs,showModelInput:w.launchConfirm.showModelInput,modelValue:w.launchConfirmModel,onModelChange:w.setLaunchConfirmModel,historyProviderNode:w.launchConfirm.providerType&&(w.launchConfirmSessionsLoading||w.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),w.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:eo()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:w.launchConfirmTextFilter,onChange:C=>w.setLaunchConfirmTextFilter(C.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:w.launchConfirmWorkspaceFilter,onChange:C=>w.setLaunchConfirmWorkspaceFilter(C.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:w.launchConfirmModelFilter,onChange:C=>w.setLaunchConfirmModelFilter(C.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),s.jsxs("select",{value:w.launchConfirmSortMode,onChange:C=>w.setLaunchConfirmSortMode(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:w.launchConfirmResumableOnly,onChange:C=>w.setLaunchConfirmResumableOnly(C.target.checked),disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:w.launchConfirmResumeId,onChange:C=>w.setLaunchConfirmResumeId(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Cp()}),w.filteredLaunchConfirmSavedSessions.map(C=>s.jsxs("option",{value:C.providerSessionId,disabled:!C.canResume,children:[C.title||C.providerSessionId," ",C.canResume?"":"(workspace missing)"]},C.providerSessionId))]}),!w.launchConfirmSessionsLoading&&w.launchConfirmSavedSessions.length>0&&w.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),w.launchConfirmResumeId&&(()=>{const C=w.filteredLaunchConfirmSavedSessions.find(W=>W.providerSessionId===w.launchConfirmResumeId);if(!C)return null;const I=Sl(C);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:I.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:I.providerSessionId}),s.jsx("div",{className:"mt-1",children:I.metaLine}),I.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:I.updatedLabel}),I.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:I.preview})]})})()]}),onConfirm:w.handleConfirmLaunch,onCancel:w.closeLaunchConfirm}),u&&s.jsx(kl,{section:f,onSectionChange:m})]})}function Wr(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Bx(e,t=[]){const r=new Map(e.map(a=>[a.conversation.tabKey,a])),n=t.map(a=>r.get(a)).filter(a=>!!a);return n.length===e.length?n:Wr(e)}function Kx(e){var r;const t=((r=e.p2p)==null?void 0:r.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":"Offline"}function Ox(e,t){if(!e)return[];const r=e.recentLaunches||[];return r.length>0?r.map(n=>({id:n.id,label:n.title||n.providerName||n.providerType,kind:n.kind,providerType:n.providerType,providerSessionId:n.providerSessionId,subtitle:fs(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):t.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var c,l,d,f,u;const a=or(n)?"cli":js(n)?"acp":"ide",o=fs(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(or(n)?n.cliName||n.type:js(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:js(n)?o||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((u=(f=(d=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:d.at)==null?void 0:f.call(d,-1))==null?void 0:u.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function Wx(e,t){const r=new Map;for(const n of t){const a=xs(n.conversation),o=r.get(a);o?o.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],o=[...a].sort((p,m)=>m.timestamp-p.timestamp)[0]||null,c=(o==null?void 0:o.conversation)||null,l=fa(n),d=a.filter(p=>p.unread||p.requiresAction).length,f=Kx(n),u=[n.platform||"machine",f].filter(Boolean);return{id:n.id,label:Ct(n,{fallbackId:n.id}),subtitle:u.join(" · "),unread:d,total:a.length,latestConversation:c,latestTimestamp:(o==null?void 0:o.timestamp)||0,fallbackActivityAt:l,preview:c?lp(c):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((n,a)=>{const o=n.latestTimestamp||n.fallbackActivityAt||0,c=a.latestTimestamp||a.fallbackActivityAt||0;return c!==o?c-o:n.label.localeCompare(a.label)})}function Fx(e){return e==="chat"}function Lr(e,t){var r;if(!(typeof window>"u"))try{if(!(!!((r=import.meta.env)!=null&&r.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,t)}catch{}}function Hx({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:o,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:f,requestedMachineId:u,onRequestedMachineConsumed:p,requestedMobileSection:m,onRequestedMobileSectionConsumed:y,setSelectedTabKey:N,setScreen:h,setSelectedMachineId:j,setSection:x,setMachineBackTarget:b,resetMachineAction:v}){const A=i.useRef(null),g=i.useCallback(M=>{if(!(M!=null&&M.sessionId))return;const T=Yr(M,c),k=Math.max(Date.now(),ss(M),T.lastUpdated||0);Lr("mark_read:start",{tabKey:M.tabKey,sessionId:M.sessionId,displayPrimary:it(M),inboxBucket:T.inboxBucket,unread:T.unread,lastSeenAt:T.lastSeenAt,lastUpdated:T.lastUpdated,activityAt:ss(M),readAt:k}),l(xs(M)||M.routeId,"mark_session_seen",{sessionId:M.sessionId,providerSessionId:M.providerSessionId,seenAt:k,completionMarker:T.completionMarker}).then(w=>{Lr("mark_read:result",{tabKey:M.tabKey,sessionId:M.sessionId,result:w})}).catch(w=>{Lr("mark_read:error",{tabKey:M.tabKey,sessionId:M.sessionId,error:w instanceof Error?w.message:String(w)})})},[c,l]);return i.useEffect(()=>{var T;if(!n){Fx(o)&&h("inbox"),N(((T=e[0])==null?void 0:T.tabKey)||null),A.current=null;return}if(o!=="chat"){A.current=null;return}const M=`${n.tabKey}:${n.sessionId||""}`;A.current!==M&&(A.current=M,g(n))},[e,g,o,n,h,N]),i.useEffect(()=>{if(!d)return;const M=e.find(T=>T.tabKey===d);M&&(N(M.tabKey),h("chat"),f==null||f())},[e,f,d,h,N]),i.useEffect(()=>{if(!u)return;const M=t.find(T=>T.id===u);M&&(j(M.id),v(),x("machines"),b("inbox"),h("machine"),p==null||p())},[t,p,u,v,b,h,x,j]),i.useEffect(()=>{m&&(x(m),h("inbox"),y==null||y())},[y,m,h,x]),i.useEffect(()=>{const M=r.filter(T=>T.inboxBucket==="task_complete"||T.unread);M.length!==0&&Lr("inbox_state",{screen:o,selectedTabKey:a,items:M.map(T=>{const k=Yr(T.conversation,c);return{liveState:k,tabKey:T.conversation.tabKey,sessionId:T.conversation.sessionId,displayPrimary:it(T.conversation),serverBucket:k.inboxBucket,computedBucket:T.inboxBucket,serverUnread:k.unread,computedUnread:T.unread,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,activityAt:ss(T.conversation)}})})},[r,c,o,a]),{markConversationRead:g}}function Ux(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function hi(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function zx(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Vx({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const[a,o]=i.useState("idle"),[c,l]=i.useState(""),[d,f]=i.useState(null),u=i.useCallback(()=>{o("idle"),l(""),f(null)},[]),p=i.useCallback(async(b,v,A)=>{var g;try{o("loading"),l(`Launching ${v}…`);const M={ideType:v,enableCdp:!0};(g=A==null?void 0:A.workspacePath)!=null&&g.trim()&&(M.workspace=A.workspacePath.trim()),await e(b,"launch_ide",M),o("done"),l(`${v} launch requested`)}catch(M){o("error"),l(M instanceof Error?M.message:"Launch IDE failed"),console.error("Launch IDE failed",M)}},[e]),m=i.useCallback(async(b,v,A)=>{if(v.trim())try{o("loading"),l(A!=null&&A.createIfMissing?"Creating folder…":"Saving workspace…");const g=await e(b,"workspace_add",{path:v.trim(),createIfMissing:(A==null?void 0:A.createIfMissing)===!0});if(g!=null&&g.success){o("done"),l(A!=null&&A.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}o("error"),l((g==null?void 0:g.error)||"Could not save workspace")}catch(g){o("error"),l(g instanceof Error?g.message:"Could not save workspace")}},[e]),y=i.useCallback(async b=>{var v,A,g,M,T,k;try{o("loading"),l("Starting daemon upgrade…");const w=await e(b,"daemon_upgrade",{});if((v=w==null?void 0:w.result)!=null&&v.alreadyLatest){o("done"),l(`Already on v${((A=w==null?void 0:w.result)==null?void 0:A.version)||"latest"}.`);return}if((g=w==null?void 0:w.result)!=null&&g.upgraded||(M=w==null?void 0:w.result)!=null&&M.success){o("done"),l(`Upgrade to v${((T=w==null?void 0:w.result)==null?void 0:T.version)||"latest"} started. Daemon is restarting…`);return}o("error"),l(((k=w==null?void 0:w.result)==null?void 0:k.error)||"Upgrade failed")}catch(w){o("error"),l(w instanceof Error?w.message:"Upgrade failed")}},[e]),N=i.useCallback(async(b,v,A,g)=>{var k,w,K;const M=Date.now(),T={machineId:b,kind:v,providerType:A,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:M};try{o("loading"),l(`Launching ${A}…`),f(T);const R={cliType:A};(k=g==null?void 0:g.workspacePath)!=null&&k.trim()?R.dir=g.workspacePath.trim():g!=null&&g.workspaceId&&(R.workspaceId=g.workspaceId),g!=null&&g.resumeSessionId&&(R.resumeSessionId=g.resumeSessionId),(w=g==null?void 0:g.args)!=null&&w.trim()&&(R.cliArgs=g.args.trim().split(/\s+/).filter(Boolean)),(K=g==null?void 0:g.model)!=null&&K.trim()&&(R.initialModel=g.model.trim());const S=await e(b,"launch_cli",R),O=(S==null?void 0:S.result)||S,H=(O==null?void 0:O.sessionId)||(O==null?void 0:O.id);if(S!=null&&S.success&&H){f(null),o("done"),l(`${A} launched`),t(Yt(H));return}if(S!=null&&S.success){o("loading"),l(`${A} launch requested — waiting for session…`);return}f(null),o("error"),l((S==null?void 0:S.error)||(O==null?void 0:O.error)||`Could not launch ${v.toUpperCase()} workspace`)}catch(R){if(zx(R)){o("loading"),l(`${A} launch requested — waiting for session…`);return}f(null),o("error"),l(R instanceof Error?R.message:`Could not launch ${v.toUpperCase()} workspace`)}},[t,e]),h=i.useCallback(async(b,v)=>{try{const A=await e(b,"list_saved_sessions",{providerType:v,kind:"cli",limit:30}),g=(A==null?void 0:A.result)??A;return Array.isArray(g==null?void 0:g.sessions)?g.sessions:[]}catch(A){return console.error("Failed to list saved sessions on mobile:",A),[]}},[e]),j=i.useCallback(async(b,v)=>xn(e,b,v),[e]);i.useEffect(()=>{if(!d)return;const b=hi(d.workspacePath),v=r.find(g=>{var R,S,O,H;if(!g||g.type==="adhdev-daemon"||Ux(g.daemonId||g.id)!==d.machineId||(g.transport==="acp"?"acp":g.transport==="pty"?"cli":null)!==d.kind||String(g.agentType||g.type||"")!==d.providerType)return!1;const w=String(g.providerSessionId||"");if(d.resumeSessionId&&w)return w===d.resumeSessionId;if(b){const P=hi(g.workspace||g.runtimeWorkspaceLabel);return P?P===b:!1}return Number(g.lastUpdated||g._lastUpdate||g.timestamp||((H=(O=(S=(R=g.activeChat)==null?void 0:R.messages)==null?void 0:S.at)==null?void 0:O.call(S,-1))==null?void 0:H.timestamp)||0)>=d.startedAt-5e3});if(!v)return;const A=Ic({entrySessionId:v.sessionId,entryInstanceId:v.instanceId,entryRouteId:v.id,conversations:n});A&&(f(null),o("done"),l(`${d.providerType} launched`),t(Yt(A)))},[n,r,t,d]),i.useEffect(()=>{if(!d)return;const b=window.setTimeout(()=>{f(v=>!v||v.startedAt!==d.startedAt?v:(o("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(b)},[d]);const x=i.useCallback(async(b,v)=>{if(v.kind==="ide"&&v.providerType){await p(b,v.providerType,{workspacePath:v.workspace||null});return}(v.kind==="cli"||v.kind==="acp")&&v.providerType&&await N(b,v.kind,v.providerType,{workspacePath:v.workspace||null,resumeSessionId:v.providerSessionId||null})},[p,N]);return{machineAction:{state:a,message:c},resetMachineAction:u,handleLaunchDetectedIde:p,handleAddWorkspace:m,handleMachineUpgrade:y,handleLaunchWorkspaceProvider:N,handleListSavedSessions:h,handleBrowseDirectory:j,handleOpenRecent:x}}function Gx({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:o,setScreen:c,setSelectedMachineId:l,setSection:d,setMachineBackTarget:f}){const u=i.useCallback(x=>{o(x.tabKey),c("chat"),n(x)},[n,c,o]),p=i.useCallback(x=>{const b=e.find(v=>v.routeId===x.routeId&&v.streamSource==="native");b&&(o(b.tabKey),c("chat"),n(b))},[e,n,c,o]),m=i.useCallback(()=>{n(t),c("inbox")},[n,t,c]),y=i.useCallback((x,b="inbox")=>{l(x),a(),d("machines"),f(b),c("machine")},[a,f,c,d,l]),N=i.useCallback(x=>{const b=xs(x);b&&y(b,"chat")},[y]),h=i.useCallback(()=>{a(),c(r)},[r,a,c]),j=i.useCallback(x=>{d(x),c("inbox")},[c,d]);return{openConversation:u,openNativeConversation:p,backFromConversation:m,openMachine:y,openConversationMachine:N,backFromMachine:h,changeMachineSection:j}}function ps(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function qx(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function Yx({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,userName:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:f,requestedMachineId:u,onRequestedMachineConsumed:p,requestedMobileSection:m,onRequestedMobileSectionConsumed:y,onOpenHistory:N,onOpenRemote:h,onStopCli:j,wsStatus:x,isConnected:b,onShowAllHiddenConversations:v,onHideConversation:A,onOpenNewSession:g,liveSessionInboxState:M,setCliViewModeOverrides:T}){const[k,w]=i.useState(()=>{var Z;return((Z=e[0])==null?void 0:Z.tabKey)||null}),[K,R]=i.useState(()=>e[0]?"chat":"inbox"),[S,O]=i.useState("chats"),[H,P]=i.useState(null),[C,I]=i.useState("inbox"),W=i.useRef([]),E=Ps(),$="0.9.61",z=i.useMemo(()=>e.find(Z=>Z.tabKey===k)||e[0]||null,[e,k]),J=i.useMemo(()=>z?r.find(Z=>Z.id===z.routeId):void 0,[r,z]),he=i.useMemo(()=>!z||Xe(z)||!et(z)?null:Es(z),[z]),ce=i.useMemo(()=>r.filter(Z=>Z.type==="adhdev-daemon").sort(Wa),[r]),te=i.useMemo(()=>ce.find(Z=>Z.id===H)||null,[ce,H]),ye=mn({sendDaemonCommand:a,activeConv:z||void 0,setActionLogs:o,isStandalone:c}),fe=Vx({sendDaemonCommand:a,navigate:E,ides:r,conversations:e}),be=i.useMemo(()=>e.map(Z=>{const Ce=K==="chat"&&(z==null?void 0:z.tabKey)===Z.tabKey,Ee=dn(Z,M,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Ce}),We=ss(Z),Fe=Wc(Z);return{conversation:Z,timestamp:We,preview:Fe,unread:Ee.unread,requiresAction:Ee.requiresAction,isWorking:Ee.isWorking,inboxBucket:Ee.inboxBucket}}),[e,M,K,z]),{markConversationRead:X}=Hx({conversations:e,machineEntries:ce,items:be,selectedConversation:z,selectedTabKey:k,screen:K,liveSessionInboxState:M,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:f,requestedMachineId:u,onRequestedMachineConsumed:p,requestedMobileSection:m,onRequestedMobileSectionConsumed:y,setSelectedTabKey:w,setScreen:R,setSelectedMachineId:P,setSection:O,setMachineBackTarget:I,resetMachineAction:fe.resetMachineAction}),ae=Gx({conversations:e,selectedConversation:z,machineBackTarget:C,markConversationRead:X,resetMachineAction:fe.resetMachineAction,setSelectedTabKey:w,setScreen:R,setSelectedMachineId:P,setSection:O,setMachineBackTarget:I}),ge=i.useMemo(()=>Wr(be.filter(Z=>Z.requiresAction)),[be]),ee=i.useMemo(()=>Wr(be.filter(Z=>Z.unread&&!Z.requiresAction)),[be]),de=i.useMemo(()=>Bx(be.filter(Z=>!Z.unread&&!Z.requiresAction&&Z.isWorking),W.current),[be]);i.useEffect(()=>{W.current=de.map(Z=>Z.conversation.tabKey)},[de]);const we=i.useMemo(()=>Wr(be.filter(Z=>!Z.unread&&!Z.requiresAction&&!Z.isWorking)),[be]),ue=i.useMemo(()=>te?be.filter(Z=>xs(Z.conversation)===te.id):[],[be,te]),xe=i.useMemo(()=>Ox(te,r),[r,te]),se=(te==null?void 0:te.version)||null,ie=!!te&&!!se&&!0&&se!==$,re=i.useMemo(()=>(te==null?void 0:te.availableProviders)||[],[te]),q=i.useMemo(()=>re.filter(Z=>ps(Z,"cli")).map(Z=>({type:Z.type,displayName:Z.displayName||Z.type,icon:Z.icon})),[re]),Y=i.useMemo(()=>re.filter(Z=>ps(Z,"acp")).map(Z=>({type:Z.type,displayName:Z.displayName||Z.type,icon:Z.icon})),[re]),le=i.useMemo(()=>Wx(ce,be),[be,ce]),ke=i.useCallback(async Z=>{te&&await fe.handleOpenRecent(te.id,Z)},[fe,te]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:K==="chat"&&z?s.jsx(Ax,{selectedConversation:z,isAcp:Xe(z),isStandalone:c,selectedIdeEntry:J,actionLogs:n,userName:l,isSendingChat:ye.isSendingChat,sendFeedbackMessage:ye.sendFeedbackMessage,isFocusingAgent:ye.isFocusingAgent,handleModalButton:ye.handleModalButton,handleRelaunch:ye.handleRelaunch,onBack:ae.backFromConversation,onOpenNativeConversation:ae.openNativeConversation,onOpenMachine:ae.openConversationMachine,onHideConversation:A,onOpenHistory:N,onOpenRemote:h,onStopCli:j,cliViewMode:he,onSetCliViewMode:async Z=>{await hl({conversation:z,mode:Z,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:T})},handleSendChat:ye.handleSendChat,handleFocusAgent:ye.handleFocusAgent}):K==="machine"&&te?s.jsx($x,{selectedMachineEntry:te,selectedMachineConversations:ue,selectedMachineRecentLaunches:xe,cliProviders:q,acpProviders:Y,selectedMachineNeedsUpgrade:ie,appVersion:$,machineAction:fe.machineAction,isStandalone:c,section:S,showBottomNav:C==="inbox",onBack:ae.backFromMachine,onSectionChange:ae.changeMachineSection,onOpenConversation:ae.openConversation,onOpenRecent:ke,onOpenMachineDetails:()=>E(`/machines/${te.id}`),onMachineUpgrade:()=>fe.handleMachineUpgrade(te.id),onLaunchDetectedIde:(Z,Ce)=>fe.handleLaunchDetectedIde(te.id,Z,Ce),onAddWorkspace:(Z,Ce)=>fe.handleAddWorkspace(te.id,Z,Ce),onBrowseDirectory:Z=>fe.handleBrowseDirectory(te.id,Z),onLaunchWorkspaceProvider:(Z,Ce,Ee)=>fe.handleLaunchWorkspaceProvider(te.id,Z,Ce,Ee),onListSavedSessions:Z=>fe.handleListSavedSessions(te.id,Z)}):s.jsx(Lx,{section:S,attentionItems:ge,unreadItems:ee,workingItems:de,completedItems:we,hiddenConversations:t,machineCards:le,getAvatarText:qx,actionLogs:n,sendDaemonCommand:a,onOpenConversation:ae.openConversation,onShowAllHidden:v,onHideConversation:A,onOpenNewSession:g,onOpenMachine:ae.openMachine,onOpenSettings:()=>E("/settings"),onSectionChange:O,wsStatus:x,isConnected:b,isStandalone:c})})}function Fn(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function Xx({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:o}){const c=i.useRef(0),[l,d]=i.useState(!1),[f,u]=i.useState(null),p=i.useCallback(()=>{c.current=0,d(!1),u(null)},[]);i.useEffect(()=>(window.addEventListener("dragend",p),window.addEventListener("drop",p),()=>{window.removeEventListener("dragend",p),window.removeEventListener("drop",p)}),[p]);const m=i.useCallback(j=>{j.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,d(!0))},[]),y=i.useCallback(j=>{if(!j.dataTransfer.types.includes("text/tab-key"))return;if(j.preventDefault(),!Fn(t,r)){u("merge");return}const x=j.currentTarget.getBoundingClientRect(),b=j.clientX-x.left,v=x.width/3;b<v?u("split-left"):b>v*2?u("split-right"):u("merge")},[t,r]),N=i.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,d(!1),u(null))},[]),h=i.useCallback(j=>{c.current=0,d(!1);const x=j.dataTransfer.getData("text/tab-key"),b=x?e.some(A=>A.tabKey===x):!1,v=f;if(u(null),o(),!!x){if(j.preventDefault(),v==="split-left"&&Fn(t,r)){r==null||r(x,"split-left");return}if(v==="split-right"&&Fn(t,r)){r==null||r(x,"split-right");return}if(b){a(x);return}n==null||n(x)}},[e,f,t,r,n,a,o]);return{dragOver:l,dropAction:f,resetDragState:p,handleDragEnter:m,handleDragOver:y,handleDragLeave:N,handleDrop:h}}function Jx(e,t){const r=new Set(t.map(o=>o.tabKey)),n=e.filter(o=>r.has(o)),a=t.filter(o=>!e.includes(o.tabKey)).map(o=>o.tabKey);return[...n,...a]}function Qx({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[o,c]=i.useState(t??null),[l,d]=i.useState(r??[]),[f,u]=i.useState(null),p=i.useRef(null),m=i.useRef(null),y=i.useRef(n),N=i.useRef(a);i.useEffect(()=>{y.current=n},[n]),i.useEffect(()=>{N.current=a},[a]),i.useEffect(()=>{t&&t!==o&&c(t)},[t,o]),i.useEffect(()=>{d(T=>{const k=Jx(T,e);return k.length===T.length&&k.every((w,K)=>w===T[K])?T:k})},[e]);const h=i.useMemo(()=>{const T=f??l;if(T.length===0)return e;const k=new Map(T.map((w,K)=>[w,K]));return[...e].sort((w,K)=>{const R=k.get(w.tabKey)??999,S=k.get(K.tabKey)??999;return R-S})},[e,f,l]);i.useEffect(()=>{var k,w;if(h.length===0){o!==null&&(c(null),(k=y.current)==null||k.call(y,null));return}if(o&&h.some(K=>K.tabKey===o))return;const T=h[0].tabKey;T!==o&&(c(T),(w=y.current)==null||w.call(y,T))},[h,o]);const j=i.useMemo(()=>h.find(T=>T.tabKey===o),[h,o]),x=i.useCallback(T=>{var k;c(T),(k=y.current)==null||k.call(y,T)},[]),b=i.useCallback((T,k,w)=>{d(K=>{var H;const R=K.filter(P=>P!==T),S=R.indexOf(k);if(S<0)return K;const O=w==="left"?S:S+1;return R.splice(O,0,T),(H=N.current)==null||H.call(N,R),R}),u(null)},[]),v=i.useCallback((T,k,w)=>{const R=(l.length>0?l:e.map(H=>H.tabKey)).filter(H=>H!==T),S=R.indexOf(k);if(S<0)return;const O=w==="left"?S:S+1;R.splice(O,0,T),p.current=R,u(R)},[l,e]),A=i.useCallback(()=>{var k;const T=p.current;T&&(d(T),(k=N.current)==null||k.call(N,T))},[]),g=i.useCallback(()=>{p.current=null,u(null)},[]),M=i.useCallback(T=>{d(k=>{var K;const w=k.filter(R=>R!==T);return w.push(T),(K=N.current)==null||K.call(N,w),w})},[]);return{activeTabId:o,activeConv:j,sortedConversations:h,previewOrderRef:p,draggingTabRef:m,selectTab:x,handleTabReorder:b,updatePreviewOrder:v,commitPreviewOrder:A,clearPreviewOrder:g,moveTabToEnd:M,setDraggingTabKey:T=>{m.current=T}}}function Zx({dropAction:e,canSplit:t}){return s.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-left"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Left"})}),s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Move Here"})}),s.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-right"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Right"})})]})}function po({conversationsCount:e,isSplitMode:t,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession:o}){if(a)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const c=!r&&!n,l=n&&!!o,d=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",f=n?zc:r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.";return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:d}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:f}),l&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:o,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:Et,"aria-label":Et,children:[s.jsx(Zi,{size:14}),s.jsx("span",{children:Et})]})}),c&&s.jsx(jl,{}),c&&s.jsx("div",{className:"mt-8",children:s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"📚 Read the documentation →"})})]})]}):s.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const Cl="adhdev-tab-shortcuts";function Tl(){try{return JSON.parse(localStorage.getItem(Cl)||"{}")}catch{return{}}}function Ml({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,c]=i.useState(()=>Tl()),[l,d]=i.useState(null),f=i.useCallback(p=>{const m=[];return p.metaKey&&m.push(a?"⌘":"Meta"),p.ctrlKey&&m.push("Ctrl"),p.altKey&&m.push(a?"⌥":"Alt"),p.shiftKey&&m.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(m.push(p.key.length===1?p.key.toUpperCase():p.key),m.join("+"))},[a]),u=i.useCallback(p=>{c(p);try{localStorage.setItem(Cl,JSON.stringify(p))}catch{}},[]);return i.useEffect(()=>{if(!e||!l)return;const p=m=>{if(m.preventDefault(),m.stopPropagation(),m.key==="Escape"){d(null);return}const y=f(m);if(!y)return;const N={...o};for(const[h,j]of Object.entries(N))j===y&&delete N[h];N[l]=y,u(N),d(null)};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[e,l,o,u,f]),i.useEffect(()=>{if(!e)return;const p=m=>{if(!(!m.ctrlKey&&!m.metaKey&&!m.altKey)){for(const[y,N]of Object.entries(o))if(t.includes(y)&&f(m)===N){m.preventDefault(),r(),n(y);return}}};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[e,o,t,r,n,f]),{isMac:a,tabShortcuts:o,shortcutListening:l,setShortcutListening:d,saveShortcuts:u}}const Hn=e=>{e.preventDefault()},eb=i.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:o,conversationKeys:c,draggingTabRef:l,onFocus:d,onSelectTab:f,onConversationActivated:u,onPreviewReorder:p,onReorderTab:m,onCommitPreviewOrder:y,onClearPreviewOrder:N,onDragStateReset:h,onDragTabKeyChange:j,onReceiveTab:x,onOpenContextMenu:b,longPressTimer:v,isGroupActive:A}){const g=Ds(t),M=g.isGenerating?"agent-tab-generating":g.isWaiting?"agent-tab-waiting":"",T=g.isReconnecting,k=i.useCallback(I=>{l.current=t.tabKey,j(t.tabKey),I.dataTransfer.setData("text/tab-key",t.tabKey),I.dataTransfer.effectAllowed="move"},[t.tabKey,l,j]),w=i.useCallback(()=>{l.current=null,j(null),y(),N(),h()},[l,j,y,N,h]),K=i.useCallback(I=>{const W=l.current;if(!(!W||W===t.tabKey)&&I.dataTransfer.types.includes("text/tab-key")){I.preventDefault(),I.stopPropagation();const E=I.currentTarget.getBoundingClientRect(),$=I.clientX<E.left+E.width/2?"left":"right";p(W,t.tabKey,$)}},[t.tabKey,l,p]),R=i.useCallback(I=>{I.preventDefault(),I.stopPropagation();const W=I.dataTransfer.getData("text/tab-key");if(W&&W!==t.tabKey){const E=I.currentTarget.getBoundingClientRect(),$=I.clientX<E.left+E.width/2?"left":"right";c.includes(W)?m(W,t.tabKey,$):x&&x(W)}N()},[t.tabKey,c,m,x,N]),S=i.useCallback(I=>{I.stopPropagation(),d(),f(t.tabKey),u(t)},[t,u,d,f]),O=i.useCallback(I=>{I.preventDefault(),b(I.clientX,I.clientY,t.tabKey)},[t.tabKey,b]),H=i.useCallback(I=>{const W=I.touches[0];v.current=setTimeout(()=>{b(W.clientX,W.clientY,t.tabKey)},600)},[t.tabKey,v,b]),P=i.useCallback(()=>{v.current&&clearTimeout(v.current)},[v]),C=["adhdev-dockview-tab",M,r&&"is-active",A&&"is-group-active",T&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:C,draggable:!0,onDragStart:k,onDragEnd:w,onDragOver:K,onDrop:R,onClick:S,onContextMenu:O,onTouchStart:H,onTouchEnd:P,onTouchMove:P,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:g.isGenerating?s.jsx("div",{className:"tab-spinner"}):g.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):T?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):g.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:it(t),children:it(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[T?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:rs(t)}):g.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[rs(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:rs(t)}),s.jsx(Is,{git:t.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),o&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${o}`,children:o})]})},(e,t)=>e.conv===t.conv&&e.isActive===t.isActive&&e.isDraggedTab===t.isDraggedTab&&e.isTaskCompleteUnread===t.isTaskCompleteUnread&&e.shortcut===t.shortcut&&e.conversationKeys===t.conversationKeys&&e.isGroupActive===t.isGroupActive);function tb({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:o,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:f,onCommitPreviewOrder:u,onClearPreviewOrder:p,onDragStateReset:m,onDragTabKeyChange:y,onReceiveTab:N,onHideTab:h,isGroupActive:j,allowTabShortcuts:x=!0}){const[b,v]=i.useState(null),A=i.useRef(null),g=i.useRef(null),M=i.useMemo(()=>e.map(O=>O.tabKey),[e]);dr("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(b==null?void 0:b.tabKey)||null});const{isMac:T,tabShortcuts:k,shortcutListening:w,setShortcutListening:K,saveShortcuts:R}=Ml({enabled:x,sortedTabKeys:e.map(O=>O.tabKey),onFocus:o,onSelectTab:c});i.useEffect(()=>{if(!b)return;const O=H=>{const P=document.querySelector("[data-pane-context-menu]");P&&P.contains(H.target)||v(null)};return window.addEventListener("mousedown",O,!0),()=>window.removeEventListener("mousedown",O,!0)},[b]),i.useEffect(()=>{const O=g.current;if(!O)return;const H=P=>{Math.abs(P.deltaY)<=Math.abs(P.deltaX)||(P.preventDefault(),O.scrollLeft+=P.deltaY)};return O.addEventListener("wheel",H,{passive:!1}),()=>O.removeEventListener("wheel",H)},[]);const S=i.useCallback((O,H,P)=>{v({x:O,y:H,tabKey:P})},[]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:s.jsxs("div",{ref:g,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(O=>s.jsx(eb,{conv:O,isActive:t===O.tabKey,isDraggedTab:a.current===O.tabKey,isTaskCompleteUnread:n.has(O.tabKey),shortcut:x?k[O.tabKey]:void 0,conversationKeys:M,draggingTabRef:a,onFocus:o,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:f,onCommitPreviewOrder:u,onClearPreviewOrder:p,onDragStateReset:m,onDragTabKeyChange:y,onReceiveTab:N,onOpenContextMenu:S,longPressTimer:A,isGroupActive:j},O.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),b&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:b.x,top:b.y},children:[x&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:Hn,onClick:O=>{O.stopPropagation(),K(b.tabKey),v(null)},children:["⌨ ",k[b.tabKey]?`Change shortcut (${k[b.tabKey]})`:"Set shortcut"]}),k[b.tabKey]&&s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:Hn,onClick:()=>{const O={...k};delete O[b.tabKey],R(O),v(null)},children:"✕ Remove shortcut"})]}),h&&s.jsxs(s.Fragment,{children:[x&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:Hn,onClick:()=>{h(b.tabKey),v(null)},children:"🚫 Hide from Dashboard"})]})]}),x&&w&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>K(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:O=>O.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",T?"⌘+1":"Ctrl+1",", ",T?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function sb({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,hasRegisteredMachines:l,userName:d,groupIndex:f,onFocus:u,isSplitMode:p,numGroups:m,onMoveTab:y,onReceiveTab:N,style:h,onActiveTabChange:j,initialActiveTabId:x,initialTabOrder:b,onTabOrderChange:v,onHideTab:A,isFocused:g,allowTabShortcuts:M=!0,onOpenNewSession:T,liveSessionInboxState:k}){const{sendCommand:w}=mt(),K=i.useRef(null),{activeTabId:R,activeConv:S,sortedConversations:O,draggingTabRef:H,selectTab:P,handleTabReorder:C,updatePreviewOrder:I,commitPreviewOrder:W,clearPreviewOrder:E,moveTabToEnd:$,setDraggingTabKey:z}=Qx({conversations:e,initialActiveTabId:x,initialTabOrder:b,onActiveTabChange:j,onTabOrderChange:v}),J=mn({sendDaemonCommand:a,activeConv:S,setActionLogs:o,isStandalone:c}),{dragOver:he,dropAction:ce,resetDragState:te,handleDragEnter:ye,handleDragOver:fe,handleDragLeave:be,handleDrop:X}=Xx({conversations:e,numGroups:m,onMoveTab:y,onReceiveTab:N,onOwnTabDrop:$,onClearPreviewOrder:E}),ae=S&&!Xe(S)&&Es(S)==="terminal",ge=i.useMemo(()=>S?t.find(ue=>ue.id===S.routeId):void 0,[t,S]),ee=i.useMemo(()=>S?n.filter(ue=>ue.routeId===S.tabKey):[],[n,S]),de=i.useMemo(()=>new Set(O.filter(ue=>qu(ue,k,{isOpenConversation:ue.tabKey===R})).map(ue=>ue.tabKey)),[R,k,O]);dr("PaneGroup",{groupIndex:f,conversationCount:e.length,activeTabId:R,dragOver:he});const we=i.useCallback(ue=>{ue.streamSource==="agent-stream"&&ue.agentType&&w(ue.routeId,jc(),{agentType:ue.agentType,...ue.sessionId&&{targetSessionId:ue.sessionId}}).catch(()=>{})},[w]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...h,outline:he?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(tb,{conversations:O,activeTabId:R,groupIndex:f,numGroups:m,unreadTabKeys:de,draggingTabRef:H,onFocus:u,onSelectTab:P,onConversationActivated:we,onPreviewReorder:I,onReorderTab:C,onCommitPreviewOrder:W,onClearPreviewOrder:E,onDragStateReset:te,onDragTabKeyChange:z,onMoveTab:y,onReceiveTab:N,onHideTab:A,isGroupActive:g??!1,allowTabShortcuts:M}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ye,onDragOver:fe,onDragLeave:be,onDrop:X,children:[he&&s.jsx(Zx,{dropAction:ce,canSplit:!!(m<4&&y)}),S?s.jsx(fo,{activeConv:S,clearToken:r[S.tabKey]||0,isCliTerminal:!!ae,ideEntry:ge,terminalRef:K,handleModalButton:J.handleModalButton,handleRelaunch:J.handleRelaunch,handleSendChat:J.handleSendChat,isSendingChat:J.isSendingChat,sendFeedbackMessage:J.sendFeedbackMessage,handleFocusAgent:J.handleFocusAgent,isFocusingAgent:J.isFocusingAgent,actionLogs:ee,userName:d,isInputActive:!p||!!g}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(po,{conversationsCount:e.length,isSplitMode:p,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:T})})]})]})}function rb({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:o,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:f,isStandalone:u,hasRegisteredMachines:p,userName:m,focusedGroup:y,focusGroup:N,moveTabToGroup:h,splitTabRelative:j,closeGroup:x,handleResizeStart:b,groupActiveTabIds:v,setGroupActiveTab:A,groupTabOrders:g,setGroupTabOrder:M,toggleHiddenTab:T,onOpenNewSession:k,allowTabShortcuts:w=!0,liveSessionInboxState:K}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((R,S)=>{const O=t&&n.length===r?`${n[S]}%`:void 0;return s.jsxs(kt.Fragment,{children:[t&&S>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:H=>b(S-1,H),onDoubleClick:()=>x(S),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(sb,{style:t?{flexBasis:O??`${100/r}%`,flexGrow:O?0:1,flexShrink:O?0:1}:void 0,conversations:R,clearedTabs:o,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:f,isStandalone:u,hasRegisteredMachines:p,userName:m,groupIndex:S,isFocused:t&&y===S,onFocus:()=>N(S),isSplitMode:t,numGroups:r,onMoveTab:(H,P)=>{P==="left"&&S>0?h(H,S-1):P==="right"&&S<r-1?h(H,S+1):P==="split-left"&&r<4?j(H,S,"left"):P==="split-right"&&r<4&&j(H,S,"right")},onReceiveTab:H=>h(H,S),onActiveTabChange:H=>A(S,H),initialActiveTabId:v[S],initialTabOrder:g[S],onTabOrderChange:H=>M(S,H),onHideTab:T,onOpenNewSession:k,allowTabShortcuts:w,liveSessionInboxState:K})]},S)})})}function Al({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,o]=i.useState(null),[c,l]=i.useState(null);i.useEffect(()=>e?ot.onScreenshot("ide-page",(u,p)=>{if(u!==e)return;const m=new FileReader;m.onload=()=>o(m.result),m.readAsDataURL(p)}):void 0,[e]),i.useEffect(()=>{r!=="connected"&&o(null)},[r]),i.useEffect(()=>{var u;return e?((u=ot.onStatus)==null?void 0:u.call(ot,(p,m)=>{p===e&&m!=null&&m.screenshotUsage&&l(m.screenshotUsage)}))||(()=>{}):void 0},[e]),i.useEffect(()=>{o(null)},[e,t]),i.useEffect(()=>{const f=e?ot.get(e):null;if(!(!f||r!=="connected"))return n!=="chat"&&t?f.startScreenshots(t):f.stopScreenshots(t),()=>{f.stopScreenshots(t)}},[n,r,t,e]);const d=i.useCallback(async(f,u)=>{const p=e?ot.get(e):null;return!p||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):p.sendInput(f,u,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:d}}const Il="adhdev-dashboard-action-shortcuts",nb=1200,ab=[["toggleHiddenTabs","G H"],["openNewSession","N"],["setActiveTabShortcut","G S"],["selectPreviousGroupTab","G K"],["selectPreviousGroupTab","T ←"],["selectPreviousGroupTab","⌥+["],["selectPreviousGroupTab","Ctrl+Alt+["],["selectNextGroupTab","G J"],["selectNextGroupTab","T →"],["selectNextGroupTab","⌥+]"],["selectNextGroupTab","Ctrl+Alt+]"],["splitActiveTabDown","S ↓"],["splitActiveTabDown","⌘+⌥+-"],["splitActiveTabDown","Ctrl+Alt+-"],["splitActiveTabRight","S →"],["splitActiveTabRight","⌘+⌥+\\"],["splitActiveTabRight","⌘+⌥+="],["splitActiveTabRight","Ctrl+Alt+\\"],["focusLeftPane","F ←"],["focusLeftPane","⌘+⌥+←"],["focusLeftPane","⌘+⌥+["],["focusLeftPane","Ctrl+Alt+←"],["focusRightPane","F →"],["focusRightPane","⌘+⌥+→"],["focusRightPane","⌘+⌥+]"],["focusRightPane","Ctrl+Alt+→"],["focusUpPane","F ↑"],["focusUpPane","⌘+⌥+U"],["focusUpPane","Ctrl+Alt+↑"],["focusDownPane","F ↓"],["focusDownPane","⌘+⌥+J"],["focusDownPane","Ctrl+Alt+↓"],["moveActiveTabToLeftPane","M ←"],["moveActiveTabToLeftPane","⌘+⌥+⇧+←"],["moveActiveTabToLeftPane","⌘+⌥+,"],["moveActiveTabToLeftPane","Ctrl+Alt+Shift+←"],["moveActiveTabToRightPane","M →"],["moveActiveTabToRightPane","⌘+⌥+⇧+→"],["moveActiveTabToRightPane","⌘+⌥+."],["moveActiveTabToRightPane","Ctrl+Alt+Shift+→"],["moveActiveTabToUpPane","M ↑"],["moveActiveTabToUpPane","⌘+⌥+I"],["moveActiveTabToUpPane","Ctrl+Alt+Shift+↑"],["moveActiveTabToDownPane","M ↓"],["moveActiveTabToDownPane","⌘+⌥+K"],["moveActiveTabToDownPane","Ctrl+Alt+Shift+↓"],["triggerPrimaryApprovalAction","⌥+A"],["triggerSecondaryApprovalAction","⌥+D"],["toggleCliView","T"]];function ob(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function st(e,t){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return t?"⌘+⇧+Enter":"Ctrl+Shift+Enter";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+Ctrl+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return t?"⌘+Ctrl+⇧+↓":"Ctrl+Alt+Shift+↓";case"focusLeftPane":return"";case"focusRightPane":return"";case"focusUpPane":return"";case"focusDownPane":return"";case"moveActiveTabToLeftPane":return"";case"moveActiveTabToRightPane":return"";case"moveActiveTabToUpPane":return"";case"moveActiveTabToDownPane":return"";case"triggerPrimaryApprovalAction":return t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌘+⇧+←":"Ctrl+Shift+←";case"selectNextGroupTab":return t?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function Ll(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:st("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:st("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:st("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:st("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:st("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:st("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:st("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:st("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:st("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:st("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:st("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:st("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:st("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:st("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:st("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:st("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:st("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:st("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:st("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:st("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:st("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:st("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:st("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:st("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:st("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:st("toggleCliView",e)}]}function Ca(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function nn(e){const t=Object.fromEntries(Ll(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Il)||"{}"),n={...t,...r};for(const[a,o]of ab)n[a]===o&&(n[a]=t[a]);return n}catch{return t}}function Rl(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function ib({enabled:e=!0,onTrigger:t}){const r=ob(),[n,a]=i.useState(()=>nn(r)),[o,c]=i.useState(null),[l,d]=i.useState([]),f=i.useRef({parts:[],timer:null}),u=i.useCallback(h=>{const j=[];return h.metaKey&&j.push(r?"⌘":"Meta"),h.ctrlKey&&j.push("Ctrl"),h.altKey&&j.push(r?"⌥":"Alt"),h.shiftKey&&h.key.length!==1&&j.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(j.push(Rl(h.key)),j.join("+"))},[r]),p=i.useCallback(h=>{a(h);try{localStorage.setItem(Il,JSON.stringify(h))}catch{}},[]);i.useEffect(()=>{const h=nn(r),j=Object.entries(n),x=Object.entries(h);j.length===x.length&&j.every(([b,v])=>h[b]===v)||p(h)},[n,r,p]);const m=i.useCallback(()=>{typeof window<"u"&&f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current={parts:[],timer:null}},[]),y=i.useCallback(()=>{typeof window>"u"||(f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current.timer=window.setTimeout(()=>{f.current={parts:[],timer:null}},nb))},[]);i.useEffect(()=>{if(!o)return;const h=j=>{if(j.preventDefault(),j.stopPropagation(),j.key==="Escape"){c(null),d([]);return}const x=u(j);if(!x)return;const v=!(j.metaKey||j.ctrlKey||j.altKey)&&/^[A-Z0-9]$/.test(x);if(l.length===0&&v){d([x]);return}const g=[...l,x].slice(0,2).join(" "),M={...n};for(const[T,k]of Object.entries(M))k===g&&delete M[T];M[o]=g,p(M),c(null),d([])};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[n,u,p,o,l]),i.useEffect(()=>{if(!e||o)return;const h=j=>{if(j.defaultPrevented)return;const x=u(j);if(!x)return;const b=j.metaKey||j.ctrlKey||j.altKey;if(Ca(j.target))return;const v=f.current.parts,A=b?[x]:[...v.slice(-1),x].slice(-2),g=A.join(" "),M=A[A.length-1],T=Object.entries(n).filter(([,S])=>!!S),k=T.find(([,S])=>S===g);if(k){j.preventDefault(),m(),t(k[0]);return}if(T.some(([,S])=>S.startsWith(`${g} `))){j.preventDefault(),f.current.parts=A,y();return}const K=T.find(([,S])=>S===M);if(K){j.preventDefault(),m(),t(K[0]);return}if(T.some(([,S])=>S.startsWith(`${M} `))){j.preventDefault(),f.current.parts=[M],y();return}m()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[n,y,e,u,t,m,o]),i.useEffect(()=>()=>m(),[m]);const N=i.useMemo(()=>Ll(r),[r]);return{isMac:r,actionDefinitions:N,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:d,saveShortcuts:p}}function cb({isTabInPopout:e,isTabFloating:t,tabShortcut:r,actionShortcuts:n}){const a=[];return e?(t&&a.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:n.dockActiveTab}),a.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:n.dockActiveTab})):t?a.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:n.dockActiveTab}):a.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:n.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:n.popoutActiveTab}),a.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:r?`Change shortcut (${r})`:"Set shortcut",shortcut:n.setActiveTabShortcut}),r&&a.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),a.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:n.hideCurrentTab,tone:"muted"}),a}function _l(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function xi({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!_l(n):!0}function lb({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:_l(r)}const Pl=1e3,db=4;function bi(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function gi(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function ub({detachDelayMs:e=Pl,stillnessThresholdPx:t=db,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,c=null,l=null,d=null,f=null,u=!1;const p=()=>{f!=null&&(a(f),f=null)},m=()=>{p(),l=null},y=()=>{p(),o=null,c=null,l=null,d=null,u=!1},N=()=>{!o||!l||!d||u||f!=null||(f=n(()=>{f=null,!(!o||!l||!d||u)&&bi(d,c)&&(gi(l,d,t)||(u=!0,r({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},h=x=>{if(!(!o||u)){if(!bi(x,c)){d={clientX:x.clientX,clientY:x.clientY},m();return}(!l||gi(l,x,t))&&(p(),l={clientX:x.clientX,clientY:x.clientY}),d={clientX:x.clientX,clientY:x.clientY},N()}},j=x=>{!o||u||(x&&(d={clientX:x.clientX,clientY:x.clientY}),m())};return{startDrag:x=>{p(),o=x.panelId,c=x.selfPanelBounds??null,l=null,d={clientX:x.clientX,clientY:x.clientY},u=!1},markSelfPanel:h,markNonSelfPanel:j,markNoDropTarget:j,markDockTarget:j,endDrag:y,isDragging:()=>o!=null,hasDetached:()=>u,dispose:y}}function fb(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}const Dl=i.createContext(null);function gn(){const e=i.useContext(Dl);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Fr(e){return it(e)||e.tabKey}function mb(e){return`remote:${e}`}function Lt(e){return e.startsWith("remote:")}function yi(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function pb(e){e.preventDefault()}function Un(e){var n;const t=e==null?void 0:e.defaultView;if(!t)return;const r=a=>{if(a)try{a.focus({preventScroll:!0})}catch{try{a.focus()}catch{}}};try{t.focus(),r(e==null?void 0:e.body),r(e==null?void 0:e.documentElement),(n=t.requestAnimationFrame)==null||n.call(t,()=>{try{t.focus(),r(e==null?void 0:e.body)}catch{}})}catch{}}function zn(e,t){e.classList.remove(aa.className,oa.className),e.classList.add(t==="light"?aa.className:oa.className)}function vi(e){return e?Array.from(new Set(e.groups.map(t=>{var r,n;return(n=(r=t.element)==null?void 0:r.ownerDocument)==null?void 0:n.defaultView}).filter(t=>!!t&&t!==window))):[]}function hb(e){const[,t]=i.useState(0);i.useEffect(()=>{const r=()=>t(a=>a+1),n=[e.api.onDidActiveGroupChange(r),e.api.onDidTitleChange(r),e.api.onDidGroupChange(r),e.containerApi.onDidActivePanelChange(r)];return()=>{for(const a of n)a.dispose()}},[e.api,e.containerApi])}function xb(e,t,r){var c;const n=[t];let a;for(const l of n){let d;for(const f of l){const u=e.addPanel({id:f.tabKey,component:"conversation",title:Fr(f),params:{kind:"conversation",tabKey:f.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});d||(d=u.id)}a=d??a}return r??((c=t[0])==null?void 0:c.tabKey)??null}function wi(e,t){const r=new Set(t.map(n=>n.tabKey));for(const n of[...e.panels])Lt(n.id)||r.has(n.id)||e.removePanel(n);for(const n of t){const a=e.getPanel(n.tabKey);if(a){a.update({params:{tabKey:n.tabKey}}),a.title!==Fr(n)&&a.api.setTitle(Fr(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:Fr(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 ji(e,t,r){var d,f;const n=r?mb(r):null;for(const u of[...e.panels])Lt(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=Pt(t,r);if(!a&&e.totalPanels===0)return;const o=e.getPanel(n),c=Uc(a);if(o){o.title!==c&&o.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((f=e.panels.find(u=>!Lt(u.id)))==null?void 0:f.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function bb({params:e,api:t}){var p;const r=gn(),n=i.useRef(null),[a,o]=i.useState(t.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=mn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});i.useEffect(()=>{o(t.isActive);const m=[t.onDidActiveChange(y=>o(y.isActive)),t.onDidActiveGroupChange(y=>{if(!t.isActive&&!y.isActive){o(!1);return}o(t.isActive)})];return()=>{for(const y of m)y.dispose()}},[t]);const d=i.useMemo(()=>c?r.ides.find(m=>m.id===c.routeId):void 0,[r.ides,c]),f=i.useMemo(()=>c?r.actionLogs.filter(m=>m.routeId===c.tabKey):[],[r.actionLogs,c]);if(!c)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(po,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const u=!Xe(c)&&Es(c)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(fo,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:u,ideEntry:d,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:f,userName:r.userName,scrollToBottomRequestNonce:((p=r.scrollToBottomRequest)==null?void 0:p.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:a})})}function gb({params:e}){var d;const t=gn(),r=i.useMemo(()=>Pt([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=i.useMemo(()=>t.ides.find(f=>f.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((d=r==null?void 0:r.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:c,handleRemoteAction:l}=Al({doId:a,targetSessionId:r?wc(r):(n==null?void 0:n.sessionId)||(n==null?void 0:n.instanceId),connState:(r==null?void 0:r.connectionState)||"new",viewMode:"remote"});return r?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(ac,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:o,screenshotUsage:c,transportType:r.transport,onAction:l})}):s.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:"Remote view unavailable"})}function yb(){const e=gn();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(po,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function vb(e){var y,N;hb(e);const t=gn(),r=i.useCallback(h=>{"button"in h&&h.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const h=Pt([...t.conversationsByTabKey.values()],e.params.routeId),j=((y=e.api.group.activePanel)==null?void 0:y.id)===e.api.id,x=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${j?" is-active":""}${x?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(h==null?void 0:h.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:h!=null&&h.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:h.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const n=t.conversationsByTabKey.get(e.params.tabKey);if(!n)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const a=((N=e.api.group.activePanel)==null?void 0:N.id)===e.api.id,o=e.api.isGroupActive,c=dn(n,t.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,d=c.isConnecting,f=c.isGenerating,u=c.isWaiting,p=c.unread,m=t.tabShortcuts[n.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${o?" is-group-active":""}${l?" is-reconnecting":""}`,title:it(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:h=>{var j;h.preventDefault(),r(h),t.openTabContextMenu({x:h.clientX,y:h.clientY,tabKey:n.tabKey,sourceDocument:((j=h.target)==null?void 0:j.ownerDocument)??document})},children:[p&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:f?s.jsx("div",{className:"tab-spinner"}):u?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):d?s.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:it(n)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:rs(n)}):d?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:rs(n)}):s.jsx("span",{children:rs(n)})})]}),m&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:m,children:m})]})}function wb({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:d,userName:f,toggleHiddenTab:u,actionShortcuts:p,registerActionHandlers:m,onActiveTabChange:y,onOpenNewSession:N,onRequestScrollToBottom:h,requestedActiveTabKey:j,requestedRemoteIdeId:x,onRequestedActiveTabConsumed:b,scrollToBottomRequest:v,liveSessionInboxState:A,layoutProfile:g}){var Ze,qe,tt;const{theme:M}=ao(),{sendCommand:T}=mt(),k=i.useRef(null),w=i.useRef(null),K=i.useRef(null),R=i.useRef(!1),S=i.useRef(!1),O=i.useRef(!1),H=i.useRef(null),P=i.useRef([]),[C,I]=i.useState(null),[W,E]=i.useState(0),$=i.useRef(typeof window>"u"?{}:Vh(g)),z=i.useMemo(()=>new Map(e.map(F=>[F.tabKey,F])),[e]),J=i.useMemo(()=>{const F=k.current;return F?F.groups.some(V=>{try{const L=V.model.location.type;return L!=="floating"&&L!=="popout"?!1:V.panels.some(G=>z.has(G.id))}catch{return!1}}):!1},[z,W,e]),he=i.useCallback(()=>{var F;(F=k.current)==null||F.focus()},[]),ce=i.useCallback((F,V)=>{h==null||h(F,V)},[h]),te=i.useCallback(F=>{const V=document,L=F.document;for(const ne of V.querySelectorAll('link[rel="stylesheet"]')){const ve=L.createElement("link");ve.rel="stylesheet",ve.href=ne.href,ne.crossOrigin&&(ve.crossOrigin=ne.crossOrigin),L.head.appendChild(ve)}for(const ne of V.querySelectorAll("style")){const ve=L.createElement("style");ve.textContent=ne.textContent,L.head.appendChild(ve)}const G=[];for(const ne of V.styleSheets)try{for(const ve of ne.cssRules)ve instanceof CSSStyleRule&&(ve.selectorText===":root"||ve.selectorText==="html")&&G.push(ve.cssText)}catch{}if(G.length>0){const ne=L.createElement("style");ne.textContent=G.join(`
|
|
52
52
|
`),L.head.appendChild(ne)}const _=V.documentElement.getAttribute("data-theme");_&&L.documentElement.setAttribute("data-theme",_),L.documentElement.style.colorScheme=_==="light"?"light":"dark",L.body.className=V.body.className;const U=V.documentElement.getAttribute("style");U&&L.documentElement.setAttribute("style",U);const Q=L.getElementById("dv-popout-window");Q instanceof HTMLElement&&(Q.classList.add("adhdev-dockview"),zn(Q,M))},[M]),ye=i.useCallback(()=>{var V;const F=k.current;if(F)for(const L of F.groups)try{const G=(V=L.element)==null?void 0:V.ownerDocument;if(!G||G===document)continue;const _=G.getElementById("dv-popout-window");_ instanceof HTMLElement&&(_.classList.add("adhdev-dockview"),zn(_,M));const U=document.documentElement.getAttribute("data-theme");U&&G.documentElement.setAttribute("data-theme",U),G.documentElement.style.colorScheme=U==="light"?"light":"dark",G.body.className=document.body.className;const Q=document.documentElement.getAttribute("style");Q?G.documentElement.setAttribute("style",Q):G.documentElement.removeAttribute("style")}catch{}},[M]),fe=i.useCallback(F=>{const V=k.current;if(!V)return;const L=V.getPanel(F);L&&V.addPopoutGroup(L,{popoutUrl:"/popout.html",onDidOpen:({window:G})=>{te(G),xe();const _=z.get(F);G.document.title=_?`${it(_)} — ADHDev`:"ADHDev — Popout"}})},[z,te]),be=i.useCallback(F=>{const V=k.current,L=V==null?void 0:V.getPanel(F);if(!V||!L)return;const G=V.groups.filter(_=>{var U;try{return((U=_.element)==null?void 0:U.ownerDocument)===document}catch{return!0}});G.length>0?L.api.moveTo({group:G[0],position:"center"}):L.api.moveTo({position:"center"}),L.api.setActive()},[]),X=i.useCallback(F=>{var G;const V=k.current;if(!V)return!1;const L=V.getPanel(F);if(!L)return!1;try{return((G=L.group.element)==null?void 0:G.ownerDocument)!==document}catch{return!1}},[]),ae=i.useCallback(F=>{X(F)&&be(F),u(F)},[X,be,u]),ge=i.useCallback(F=>{const V=k.current,L=V==null?void 0:V.getPanel(F);!V||!L||V.addFloatingGroup(L,{width:600,height:500})},[]),ee=i.useCallback(F=>{var L;const V=(L=k.current)==null?void 0:L.getPanel(F);if(!V)return!1;try{return V.group.model.location.type==="floating"}catch{return!1}},[]),de=i.useCallback(()=>{var V,L;const F=(L=(V=k.current)==null?void 0:V.activePanel)==null?void 0:L.id;return!F||Lt(F)?null:z.has(F)?F:null},[z]),we=i.useCallback(F=>{const V=k.current,L=V==null?void 0:V.getPanel(F);if(!V||!L)return;const G=V.groups.filter(_=>{try{return _.model.location.type==="grid"}catch{return!0}});G.length>0?L.api.moveTo({group:G[0],position:"center"}):L.api.moveTo({position:"center"}),L.api.setActive()},[]),ue=i.useCallback(()=>{var U;const F=k.current;if(!F)return;const L=F.groups.filter(Q=>{var ne;try{return((ne=Q.element)==null?void 0:ne.ownerDocument)===document&&Q.model.location.type==="grid"}catch{return!1}})[0]||null,G=[...F.panels];for(const Q of G){const ne=(U=Q.group.element)==null?void 0:U.ownerDocument,ve=Q.group.model.location.type;ne===document&&ve==="grid"||(L&&L.id!==Q.group.id?Q.api.moveTo({group:L,position:"center"}):Q.api.moveTo({position:"center"}))}const _=F.activePanel;_&&(_.group.model.openPanel(_),_.api.setActive()),Un(document)},[]),xe=i.useCallback(()=>{var V,L;const F=k.current;if(F)for(const G of F.groups){const _=(V=G.element)==null?void 0:V.ownerDocument;if(!_||_===document)continue;const U=_.getElementById("dv-popout-window");if(!(U instanceof HTMLElement))continue;let Q=null,ne=_.title||"ADHDev",ve="Popout workspace";const Me=G.activePanel;if(Me)if(Q=Me.id,Lt(Me.id)){const Re=((L=Me.params)==null?void 0:L.routeId)||Me.id.slice(7),ze=Pt([...z.values()],Re);ne=Uc(ze),ve=ze!=null&&ze.machineName?`Remote view · ${ze.machineName}`:"Remote view"}else{const Re=z.get(Me.id);ne=Re?it(Re):Me.title||Me.id,ve=Re?rs(Re):"Dockview panel"}_.title=`${ne} — ADHDev`;const _e=Array.from(_.querySelectorAll("#adhdev-popout-header"));for(const Re of _e)Re.remove();const Ne=_.createElement("div");Ne.id="adhdev-popout-header",_.body.appendChild(Ne),Ne.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(";")),Ne.innerHTML=`
|
|
53
53
|
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
54
54
|
<div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
|
|
@@ -86,9 +86,9 @@ This will disconnect CDP and optionally kill the process.`))try{const $=await r(
|
|
|
86
86
|
|
|
87
87
|
`)}function Og(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Wg(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Fg({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:c,searchQuery:l,daemonLoading:d,traceLoading:f,daemonFetchError:u,traceFetchError:p}){const m=gg(n,o),y=wg(e,l),N=Sg(t,l),h=Ng(m,l),j=Cg(a,l),x=Og(y,c),b=c==="all"?N:[],v=Wg(h,c),A=c==="issues"?[]:j,g=Tg({daemonLogs:y,daemonRawLines:N,trace:h,webEvents:j}),M=Dg({daemonLogs:x,daemonRawLines:b,trace:v,webEvents:A}),T=$g(M),k=Ig({daemonLoading:d,traceLoading:f,daemonFetchError:u,traceFetchError:p,daemonLogKind:r,daemonLogsCount:y.length,daemonRawLineCount:N.length,traceCount:h.length,webEventCount:j.length});return{filteredDaemonLogs:y,filteredDaemonRawLines:N,filteredTraceEntries:h,filteredWebEvents:j,visibleDaemonLogs:x,visibleDaemonRawLines:b,visibleTraceEntries:v,visibleWebEvents:A,quickFilterCounts:g,diagnosticEvents:M,diagnosticsSummary:T,sourceStates:k}}function Hg(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function zl(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function Ta(e){return e==="error"?"text-red-300 border-red-500/25 bg-red-500/[0.05]":e==="warn"?"text-amber-200 border-amber-500/25 bg-amber-500/[0.05]":e==="debug"?"text-slate-300 border-slate-500/25 bg-slate-500/[0.05]":"text-text-secondary border-border-subtle bg-bg-primary"}function Xn(e){return e==="good"?"border-emerald-500/20 bg-emerald-500/[0.05]":e==="warning"?"border-amber-500/20 bg-amber-500/[0.05]":e==="danger"?"border-red-500/20 bg-red-500/[0.05]":"border-border-subtle bg-bg-secondary"}function bo(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function Ug({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Ta(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:zl(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:bo(e.source)}),e.category&&e.stage&&s.jsxs("span",{children:[e.category,".",e.stage]}),e.topic&&s.jsxs("span",{children:["topic=",e.topic]}),e.interactionId&&s.jsxs("span",{children:["ix=",e.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:e.message})]})}function zg({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:c,onCopyVisible:l,onToggleAutoRefresh:d,onRefresh:f,onClear:u}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(p=>s.jsx("button",{type:"button",onClick:()=>a(p.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===p.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:p.label},p.id))}),s.jsx("input",{value:r,onChange:p=>o(p.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:l,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:d,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:f,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:u,className:"machine-btn",children:"Clear"})]})]})}function Vg({logLevel:e,traceCategory:t,onLogLevelChange:r,onTraceCategoryChange:n}){return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary p-3",children:s.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wider text-text-muted font-semibold",children:"Advanced source scope"}),["debug","info","warn","error"].map(a=>s.jsxs("button",{onClick:()=>r(a),className:`machine-btn text-[10px] px-2 py-0.5 ${e===a?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:["Daemon ",a.toUpperCase(),"+"]},a))]}),s.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:xg.map(a=>s.jsx("button",{onClick:()=>n(a.value),className:`machine-btn text-[10px] px-2 py-0.5 ${t===a.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:a.label},a.value))})]})})}function Gg({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:c,traceFetchError:l}){var u,p;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((p=e.latestIssue)==null?void 0:p.severity)==="warn"?"warning":"good",f=c||l?"danger":o?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${Xn(e.issueCount>0?"warning":"good")}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Diagnostics timeline"}),s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[t," visible event(s) · ",e.issueCount," issue signal(s)"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:n.trim()?`Filtered by “${n.trim()}”`:"Daemon, trace, and browser signals merged by time"})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Xn(d)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[bo(e.latestIssue.source)," · ",e.latestIssue.severity.toUpperCase()]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:e.latestIssue.message}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2",children:zl(e.latestIssue.ts)})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No visible warn/error signal"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use Issues or All if you need a narrower or rawer view."})]})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Xn(f)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Source status"}),s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:c||l?"Needs attention":o?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",Hg(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(m=>s.jsxs("div",{children:[m.label,": ",m.status]},m.id))})]})]})}function qg({patterns:e}){return e.length===0?null:s.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/[0.04] p-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Repeated issue patterns"}),s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:e.map(t=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary px-3 py-2",children:[s.jsxs("div",{className:"text-[12px] text-text-primary font-medium",children:[t.count,"× ",t.severity.toUpperCase()," · ",bo(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function Yg({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:c,visibleWebEvents:l,quickFilter:d,searchQuery:f}){return s.jsxs("div",{className:"grid gap-3",children:[s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,timeline:!u.timeline})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[n.length," visible diagnostic event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.timeline?"Hide":"Show"})]}),t.timeline&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&n.length===0&&s.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&s.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&s.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),n.map(u=>s.jsx(Ug,{event:u},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,daemon:!u.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${o.length} visible raw line(s) from file fallback`:`${a.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.daemon?"Hide":"Show"})]}),t.daemon&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.daemonLoading&&a.length===0&&o.length===0&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&o.length===0&&e.daemonRawText&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:d==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&a.length===0&&e.daemonLogs.length>0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&o.map((u,p)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${p}`)),e.daemonLogKind!=="text"&&a.map((u,p)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${Ta(u.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(u.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:u.level==="error"?"ERR":u.level==="warn"?"WRN":u.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:u.message})]},`log-${p}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,trace:!u.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.trace?"Hide":"Show"})]}),t.trace&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.traceLoading&&c.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&c.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&c.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:f.trim()?"No trace entries match the current search.":e.traceCategory==="session_host"?"No session_host trace entries yet. This filter uses get_debug_trace(category=session_host).":"No trace entries yet. Run daemon with --dev or --trace."}),c.map(u=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Ta(u.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.level.toUpperCase()}),s.jsxs("span",{children:[u.category,".",u.stage]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:_s(u.payload,360)||"No payload"})]},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,web:!u.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[l.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.web?"Hide":"Show"})]}),t.web&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[l.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:f.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),l.map(u=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.kind}),u.topic&&s.jsxs("span",{children:["topic=",u.topic]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:_s(u.payload,360)||"No payload"})]},u.id))]})]})]})}function Xg({machineId:e,sendDaemonCommand:t}){const r=Ag({machineId:e,sendDaemonCommand:t}),[n,a]=i.useState("info"),[o,c]=i.useState(""),[l,d]=i.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),f=i.useRef(null),u=i.useRef(!1),p=i.useMemo(()=>Fg({daemonLogs:r.daemonLogs,daemonRawText:r.daemonRawText,daemonLogKind:r.daemonLogKind,debugTrace:r.debugTrace,webEvents:r.webEvents,traceCategory:r.traceCategory,quickFilter:n,searchQuery:o,daemonLoading:r.daemonLoading,traceLoading:r.traceLoading,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),[n,o,r.daemonFetchError,r.daemonLoading,r.daemonLogKind,r.daemonLogs,r.daemonRawText,r.debugTrace,r.traceCategory,r.traceFetchError,r.traceLoading,r.webEvents]);i.useEffect(()=>{if(r.autoRefresh&&p.diagnosticEvents.length>0){const N=u.current?"smooth":"instant";setTimeout(()=>{var h;(h=f.current)==null||h.scrollIntoView({behavior:N}),u.current=!0},50)}},[p.diagnosticEvents.length,r.autoRefresh]);const m=i.useCallback(async()=>{var h;const N=Mg({daemonLogs:p.visibleDaemonLogs,daemonRawLines:p.visibleDaemonRawLines,trace:p.visibleTraceEntries,webEvents:p.visibleWebEvents});if(!N.trim()){rt.showToast("No visible logs to copy.","info");return}try{await((h=navigator.clipboard)==null?void 0:h.writeText(N)),rt.showToast("Copied visible logs to clipboard.","success")}catch(j){rt.showToast(j instanceof Error?j.message:"Could not copy visible logs","warning")}},[p.visibleDaemonLogs,p.visibleDaemonRawLines,p.visibleTraceEntries,p.visibleWebEvents]),y=i.useCallback(async()=>{var h;const N=Kg({events:p.diagnosticEvents,summary:p.diagnosticsSummary,sources:p.sourceStates});try{await((h=navigator.clipboard)==null?void 0:h.writeText(N)),rt.showToast("Copied diagnostic bundle to clipboard.","success")}catch(j){rt.showToast(j instanceof Error?j.message:"Could not copy diagnostic bundle","warning")}},[p.diagnosticEvents,p.diagnosticsSummary,p.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(zg,{quickFilter:n,quickFilterCounts:p.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:c,onCopyDiagnostics:()=>{y()},onCopyVisible:()=>{m()},onToggleAutoRefresh:()=>r.setAutoRefresh(N=>!N),onRefresh:r.refresh,onClear:r.clear}),s.jsx(Vg,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(Gg,{diagnosticsSummary:p.diagnosticsSummary,diagnosticEventsCount:p.diagnosticEvents.length,sourceStates:p.sourceStates,searchQuery:o,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(qg,{patterns:p.diagnosticsSummary.repeatedPatterns}),s.jsx(Yg,{streams:r,sectionsOpen:l,setSectionsOpen:d,diagnosticEvents:p.diagnosticEvents,visibleDaemonLogs:p.visibleDaemonLogs,visibleDaemonRawLines:p.visibleDaemonRawLines,visibleTraceEntries:p.visibleTraceEntries,visibleWebEvents:p.visibleWebEvents,quickFilter:n,searchQuery:o}),s.jsx("div",{ref:f})]})}function Jg(e){return e.diagnostics?{label:"Managed",toneClass:"bg-green-500/[0.08] text-green-500"}:e.loading||e.refreshing?{label:"Checking…",toneClass:"bg-sky-500/[0.08] text-sky-400"}:e.error?{label:"Diagnostics issue",toneClass:"bg-amber-500/[0.08] text-amber-400"}:{label:"Unavailable",toneClass:"bg-red-500/[0.08] text-red-400"}}function Vl(e){const t=typeof(e==null?void 0:e.runtimeRecoveryState)=="string"?String(e.runtimeRecoveryState).trim():"";return t?t==="auto_resumed"?"restored after restart":t==="resume_failed"?"restore failed":t==="host_restart_interrupted"?"host restart interrupted":t==="orphan_snapshot"?"snapshot recovered":t.replace(/_/g," "):null}function Qg(e){var a;const t=[],r=[],n=[];for(const o of e||[]){const c=String((o==null?void 0:o.lifecycle)||"").trim(),l=Vl((o==null?void 0:o.meta)||void 0),d=((a=o==null?void 0:o.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(c)?t.push(o):(c==="stopped"||c==="failed")&&(d||l)?r.push(o):n.push(o)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function Zg(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Jn(e){return e==="live"?"These runtimes are live now and are the only attachable targets.":e==="recovery"?"These records were restored from session-host state and are not live attach targets until you explicitly recover or restart them.":"These inactive records are shown for reference and usually need restart before they are useful again."}function Qn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Zn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function _i(e){if(!e)return"unknown";const t=Date.now()-e,r=Math.max(0,Math.round(t/1e3));if(r<60)return`${r}s ago`;const n=Math.round(r/60);if(n<60)return`${n}m ago`;const a=Math.round(n/60);return a<48?`${a}h ago`:`${Math.round(a/24)}d ago`}function ey(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function ty(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 sy(e){var r;const t=new Map;for(const n of e){if(!["starting","running","stopping","interrupted"].includes(n.lifecycle))continue;const a=typeof((r=n.meta)==null?void 0:r.providerSessionId)=="string"?String(n.meta.providerSessionId).trim():"";if(!a)continue;const o=`${n.providerType}::${n.workspace}::${a}`;t.set(o,(t.get(o)||0)+1)}return Array.from(t.values()).filter(n=>n>1).length}function ry({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=i.useState(""),[o,c]=i.useState(null),[l,d]=i.useState(!1),f=wh(e,{enabled:!!e,includeSessions:!0,limit:Uo,intervalMs:bm}),u=f.diagnostics,p=f.loading,m=f.applyDiagnostics,y=i.useMemo(()=>Jg({diagnostics:u,loading:p,refreshing:l,error:n}),[u,p,l,n]),N=i.useMemo(()=>new Map(t.map(R=>[R.sessionId||R.id,R])),[t]),h=i.useCallback(async()=>{if(e){d(!0);try{const R=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Uo}),S=Qn(R);if(!(S!=null&&S.success))throw new Error((S==null?void 0:S.error)||"Could not load hosted runtime diagnostics");m(S.diagnostics||S.result||null),a("")}catch(R){const S=R instanceof Error?R.message:"Could not load hosted runtime diagnostics";a(S)}finally{d(!1)}}},[m,e,r]);i.useEffect(()=>{!e||u||p||l||h()},[u,p,e,h,l]);const j=i.useCallback(async(R,S)=>{const O=`${R}:${S.sessionId}`;if(!(R==="session_host_stop_session"&&!window.confirm(`Stop ${S.displayName}?
|
|
88
88
|
This will terminate the hosted runtime.`))){c(O);try{const H=await r(e,R,{sessionId:S.sessionId}),P=Qn(H);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Session host action failed");const C=R==="session_host_resume_session"?"resumed":R==="session_host_restart_session"?"restarted":"stopped";rt.showToast(`Session host ${C}: ${S.displayName}`,"success"),await h()}catch(H){const P=H instanceof Error?H.message:"Session host action failed";rt.showToast(P,"warning"),a(P)}finally{c(H=>H===O?null:H)}}},[e,h,r]),x=i.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
89
|
-
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 S=await r(e,"session_host_prune_duplicate_sessions",{}),O=Qn(S);if(!(O!=null&&O.success))throw new Error((O==null?void 0:O.error)||"Duplicate prune failed");const H=O.result||{},P=Array.isArray(H.prunedSessionIds)?H.prunedSessionIds.length:0,C=typeof H.duplicateGroupCount=="number"?H.duplicateGroupCount:0;rt.showToast(`Pruned ${P} duplicate runtime(s) across ${C} group(s)`,"success"),await h()}catch(S){const O=S instanceof Error?S.message:"Duplicate prune failed";rt.showToast(O,"warning"),a(O)}finally{c(S=>S==="session_host_prune_duplicate_sessions"?null:S)}}},[e,h,r]),b=i.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((R,S)=>(S.lastActivityAt||0)-(R.lastActivityAt||0)),[u==null?void 0:u.sessions]),v=i.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:Qg(b),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,b]),A=v.liveRuntimes,g=v.recoverySnapshots,M=v.inactiveRecords,T=i.useMemo(()=>sy(A),[A]),k=i.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),w=i.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(R=>R.level==="warn"||R.level==="error")||null,[u==null?void 0:u.recentLogs]),K=(R,S)=>{var z;const O=o===`session_host_resume_session:${R.sessionId}`,H=o===`session_host_restart_session:${R.sessionId}`,P=o===`session_host_stop_session:${R.sessionId}`,C=Vl(R.meta),I=N.get(R.sessionId),W=R.attachedClients.length===1?"1 client":`${R.attachedClients.length} clients`,E=S==="recovery"?"Recover":"Resume",$=Zg(S);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:R.displayName||(I==null?void 0:I.cliName)||R.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${ty(R.lifecycle)}`,children:R.lifecycle}),C&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:C})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:R.workspaceLabel||(I==null?void 0:I.runtimeWorkspaceLabel)||R.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:R.runtimeKey}),R.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",R.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((z=R.writeOwner)==null?void 0:z.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:ey(R.writeOwner)}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[s.jsx(qi,{size:11})," ",W]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",_i(R.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",$]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[S==="recovery"&&(R.lifecycle==="interrupted"||R.lifecycle==="failed"||R.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{j("session_host_resume_session",R)},children:O?`${E}ing…`:E}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{j("session_host_restart_session",R)},children:H?"Restarting…":"Restart"}),S==="live"&&(R.lifecycle==="running"||R.lifecycle==="starting"||R.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!o,onClick:()=>{j("session_host_stop_session",R)},children:P?"Stopping…":"Stop"})]})]})},R.sessionId)};return s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(us,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Tp()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[T>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{x()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${T})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${y.toneClass}`,children:y.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{h()},disabled:p||l,children:[s.jsx(lr,{size:13}),p||l?"Refreshing…":"Refresh"]})]})]}),n&&!u&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(nr,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),u&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:g.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:_i(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Zn(u.hostStartedAt)})]})]}),w&&s.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(nr,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:w.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Zn(w.timestamp),w.sessionId?` · ${w.sessionId}`:""]})]}),s.jsxs("div",{className:"mb-4 space-y-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(Ea,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Jn("live")}),A.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):s.jsx("div",{className:"space-y-2",children:A.map(R=>K(R,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(us,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Jn("recovery")}),g.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:g.map(R=>K(R,"recovery"))})]}),M.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Jn("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:M.map(R=>K(R,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),k.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:k.map(R=>{var O;const S=b.find(H=>H.sessionId===R.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(S==null?void 0:S.displayName)||((O=N.get(R.sessionId))==null?void 0:O.cliName)||R.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[R.action,R.lifecycle?` · ${R.lifecycle}`:"",R.detail?` · ${R.detail}`:"",R.error?` · ${R.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${R.success===!1?"text-red-300":"text-text-secondary"}`,children:Zn(R.timestamp)})]},`${R.sessionId}:${R.timestamp}:${R.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function ny({machine:e,launchPick:t,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return s.jsx("div",{className:"fixed inset-0 z-[100] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(o=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{a(null),n({cliType:t.cliType,workspaceId:o.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:o.label||o.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:o.path})]},o.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),n({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:"Default workspace"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{a(null),n({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:"Home directory"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>a(null),children:"Cancel"})]})]})})}function ea({icon:e,children:t}){return s.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,s.jsx("span",{children:t})]})}function ta({children:e,className:t=""}){return s.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function ay({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:c}){const l=n.slice(0,6),d=r.slice(0,4),u=Zs(e,"0.9.60");return s.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[l.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(ea,{icon:s.jsx(Ut,{size:13}),children:"Current Chats"}),s.jsx(ta,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(p=>{const m=xa(p);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>c(p),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:it(p)}),m>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:ln(m)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:As(p)})]},p.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(ea,{icon:s.jsx(Qi,{size:13}),children:"Recent Launches"}),s.jsx(ta,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(p=>{const{metaText:m,updatedLabel:y}=Nl(p);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>o(p),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:p.label}),y&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:y})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:m})]},p.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(ea,{icon:s.jsx(nr,{size:13}),children:"Daemon Update"}),s.jsx(ta,{className:"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u?"Daemon update required":"Version mismatch detected"}),s.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:u?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),s.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:a,children:[s.jsx(lr,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function oy(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function iy({machine:e,selectedWorkspace:t,resolvedWorkspacePath:r,customPath:n,canBrowse:a,onWorkspaceChange:o,onCustomPathChange:c,onOpenBrowseDialog:l}){return s.jsxs("div",{className:"mb-3",children:[s.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[s.jsx("select",{value:t,onChange:d=>{const f=d.target.value;if(o(f),f==="__custom__"&&a){l();return}f!=="__custom__"&&c("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(e.workspaces||[]).length>0?s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(e.workspaces||[]).map(d=>s.jsxs("option",{value:d.id,children:[d.id===e.defaultWorkspaceId?"⭐ ":"",un(d.path,d.label)]},d.id)),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]})}),t==="__custom__"&&(a?s.jsx("button",{type:"button",className:"px-3 py-1.5 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] hover:border-accent-primary text-text-secondary hover:text-text-primary transition-colors",onClick:l,children:"Select workspace…"}):s.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:n,onChange:d=>c(d.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:t==="__custom__"?r?s.jsx("span",{className:"font-mono truncate block",title:r,children:r}):a?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":r?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:t===e.defaultWorkspaceId?"Default workspace":"Selected workspace"}),s.jsx("span",{className:"font-mono truncate block",title:r,children:r})]}):"No workspace selected. This launches in the home directory."})]})}const cy={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 _r(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function sa({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:o,actions:c,sendDaemonCommand:l,initialWorkspaceId:d,initialWorkspacePath:f,onOpenGitDialog:u}){const p=Ps(),{handleLaunchIde:m,handleStopCli:y,handleRestartIde:N,handleStopIde:h,handleDetectIdes:j,launchingIde:x,launchingAgentType:b,addLog:v}=c,[A,g]=i.useState(null),M=i.useCallback(B=>{B&&p(Yt(B))},[p]),T=cy[e],k=e==="ide",w=e==="acp",K=i.useMemo(()=>n.filter(B=>ps(B,e)),[e,n]),R=i.useMemo(()=>new Map(K.map(B=>[B.type,B.displayName||B.type])),[K]),[S,O]=i.useState(""),[H,P]=i.useState(""),[C,I]=i.useState([]),[W,E]=i.useState(""),[$,z]=i.useState(""),[J,he]=i.useState([]),[ce,te]=i.useState(!1),[ye,fe]=i.useState(!1),[be,X]=i.useState(""),[ae,ge]=i.useState(!1),[ee,de]=i.useState(()=>xt()),[we,ue]=i.useState(null),[xe,se]=i.useState(f?"__custom__":d||t.defaultWorkspaceId||""),[ie,re]=i.useState(f||""),[q,Y]=i.useState([]),[le,ke]=i.useState(!1),[Z,Ce]=i.useState(""),[Ee,We]=i.useState([]),[Fe,D]=i.useState(!1),[Se,Ae]=i.useState(""),Le=i.useRef(null),[Pe,He]=i.useState(null),Ue=i.useRef("__home__"),[Qe,lt]=i.useState("__home__"),[dt,ut]=i.useState(!1),Te=i.useRef(0),Ge=q.filter(B=>!a.some(oe=>oe.type===B&&yt(oe.status)!=="stopped")),Ze=i.useRef({});i.useEffect(()=>{t.defaultWorkspaceId&&!xe&&se(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),i.useEffect(()=>{if(f){se("__custom__"),re(f);return}d&&(se(d),re(""))},[d,f]),i.useEffect(()=>{k||S&&(K.some(B=>B.type===S)||(O(""),z("")))},[K,k,S]);const qe=(()=>{if(xe==="__custom__")return ie.trim();if(!xe)return"";const B=(t.workspaces||[]).find(oe=>oe.id===xe);return(B==null?void 0:B.path)||""})(),tt=i.useCallback(B=>{const oe=Ze.current[B];oe&&(clearTimeout(oe),delete Ze.current[B]),Y(pe=>pe.includes(B)?pe.filter(Ke=>Ke!==B):pe)},[]),F=i.useRef(new Set),V=i.useCallback(async B=>{if(l){D(!0),Ae("");try{const oe=await xn(l,r,B);Ce(oe.path),re(oe.path),We(oe.directories)}catch(oe){Ae(oe instanceof Error?oe.message:"Could not load folder")}finally{D(!1)}}},[r,l]),L=i.useCallback(()=>{if(!l)return;se("__custom__"),ke(!0);const B=a.map(pe=>pe.workspace),oe=hn(t.platform,pn(ie.trim(),qe,f,B,t.defaultWorkspacePath,(t.workspaces||[]).map(pe=>pe.path)));V(oe)},[ie,f,V,t.defaultWorkspacePath,t.platform,t.workspaces,a,qe,l]),G=i.useCallback(B=>{const oe=String(B.workspace||"").trim();if(!oe)return;const pe=(t.workspaces||[]).find(Ke=>_r(Ke.path)===_r(oe));if(pe){se(pe.id),re("");return}se("__custom__"),re(oe)},[t.workspaces]),_=i.useCallback(B=>{const oe=String(B.workspace||"").trim();if(!oe)return{workspaceId:null,workspacePath:"",useHome:!0};const pe=(t.workspaces||[]).find(Ke=>_r(Ke.path)===_r(oe));return pe?{workspaceId:pe.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:oe,useHome:!1}},[t.workspaces]),U=i.useCallback(async B=>{if(!l||!B||e!=="cli"){he([]),te(!1),fe(!1),X("");return}const oe=Te.current+1;Te.current=oe,te(!0),X("");try{const pe=await l(r,"list_saved_sessions",{providerType:B,kind:"cli",limit:30});if(Te.current!==oe)return;const Ke=(pe==null?void 0:pe.result)??pe;he(Array.isArray(Ke==null?void 0:Ke.sessions)?Ke.sessions:[])}catch(pe){if(Te.current!==oe)return;he([]),X(pe instanceof Error?pe.message:"Could not load saved sessions")}finally{Te.current===oe&&(te(!1),fe(!0))}},[e,r,l]),Q=i.useMemo(()=>{if(e!=="cli"||!S)return null;const B=R.get(S)||S;return{routeId:r,daemonId:r,providerSessionId:$||void 0,transport:"pty",mode:"chat",agentName:B,agentType:S,status:"idle",title:B,messages:[],ideType:S,workspaceName:qe,workspacePath:qe,displayPrimary:B,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${S}`}},[e,r,R,qe,$,S]),ne=i.useCallback(B=>{if(e==="ide"||!B){I([]);return}I(Kl(r,B))},[e,r]);i.useEffect(()=>{Te.current+=1,z(""),ne(S),fe(!1),he([]),X(""),te(!1)},[e,ne,U,S]);const ve=i.useMemo(()=>J.find(B=>B.providerSessionId===$)||null,[J,$]);i.useEffect(()=>{if(!$)return;const B=J.find(oe=>oe.providerSessionId===$);B!=null&&B.canResume||z("")},[J,$]);const Me=i.useCallback((B,oe)=>{Le.current=oe,Ue.current=B.selectedWorkspaceKey||"__home__",lt(B.selectedWorkspaceKey||"__home__"),He(B)},[]),_e=i.useCallback(()=>{Le.current&&(ut(!0),Le.current().finally(()=>{Le.current=null,ut(!1),He(null)}))},[]),Ne=i.useCallback(B=>{if(!B)return;Y(pe=>pe.includes(B)?pe:[...pe,B]);const oe=Ze.current[B];oe&&clearTimeout(oe),Ze.current[B]=setTimeout(()=>{Y(pe=>pe.includes(B)?pe.filter(Ke=>Ke!==B):pe),delete Ze.current[B]},2e4)},[]);i.useEffect(()=>{for(const oe of a)yt(oe.status)!=="stopped"&&(q.includes(oe.type)&&!F.current.has(oe.type)&&(F.current.add(oe.type),v("info",`${R.get(oe.type)||oe.type} launched`,!0)),tt(oe.type));const B=new Set(a.filter(oe=>yt(oe.status)!=="stopped").map(oe=>oe.type));F.current.forEach(oe=>{!q.includes(oe)&&!B.has(oe)&&F.current.delete(oe)})},[v,tt,a,q,R]),i.useEffect(()=>()=>{Object.values(Ze.current).forEach(clearTimeout),Ze.current={}},[]);const[De,Be]=i.useState({}),[Re,ze]=i.useState(null);i.useEffect(()=>{if(!k||!r||!l)return;(async()=>{try{const oe=await l(r,"get_ide_extensions",{}),pe=(oe==null?void 0:oe.result)||oe;pe!=null&&pe.success&&(pe!=null&&pe.ideExtensions)&&Be(pe.ideExtensions)}catch{}})()},[k,r,l]);const Je=B=>k?at(B.type):e==="cli"?B.cliName:B.acpName,ft=k?t.detectedIdes||[]:[],pt=i.useCallback(async B=>{const oe=(B==null?void 0:B.type)||S,pe=(B==null?void 0:B.workspacePath)??qe;if(k){await m(oe,pe?{workspace:pe}:void 0)&&Ne(oe);return}const Ke=await c.runLaunchCliCore({cliType:oe,dir:B!=null&&B.workspaceId?void 0:pe||void 0,workspaceId:(B==null?void 0:B.workspaceId)||void 0,useHome:(B==null?void 0:B.useHome)||!(B!=null&&B.workspaceId)&&!pe,argsStr:(B==null?void 0:B.argsStr)??(H||void 0),model:(B==null?void 0:B.model)??(w&&W||void 0),resumeSessionId:(B==null?void 0:B.resumeSessionId)||!w&&e==="cli"&&oe===S&&$||void 0});if(Ke.success||Ke.pending){const Ie=(B==null?void 0:B.argsStr)??H;!k&&(Ie!=null&&Ie.trim())&&(Ol(r,oe,Ie),ne(oe)),Ne(oe),Ke.success&&Ke.sessionId&&M(Ke.sessionId)}},[c,m,w,k,H,W,ne,Ne,r,M,qe,$,S]),ht=Gc(k?"ide":w?"acp":"cli",!k&&!w&&!!$),me=qc(k?"ide":w?"acp":"cli",!k&&!w&&!!$),je=()=>{var Ie;const B=k?at(S):R.get(S)||S,oe=!k&&!w&&!!$,{options:pe,selectedKey:Ke}=cs({machine:t,currentWorkspaceId:xe&&xe!=="__custom__"?xe:null,currentWorkspacePath:qe});Me({title:oe?to(B):ns("start-fresh",B),description:oe?so():as("start-fresh"),confirmLabel:ht,busyLabel:me,workspaceOptions:pe,selectedWorkspaceKey:Ke,details:[{label:"Mode",value:T.label},{label:"Provider",value:B},...!k&&e==="cli"&&$?[{label:"Resume",value:((Ie=J.find($e=>$e.providerSessionId===$))==null?void 0:Ie.title)||$}]:[],...!k&&H.trim()?[{label:"Arguments",value:H.trim()}]:[],...w&&W.trim()?[{label:"Model",value:W.trim()}]:[]]},async()=>{const $e=pe.find(nt=>nt.key===Ue.current);$e!=null&&$e.workspaceId?(se($e.workspaceId),re("")):$e!=null&&$e.workspacePath?(se("__custom__"),re($e.workspacePath)):(se(""),re("")),await pt({workspaceId:($e==null?void 0:$e.workspaceId)??null,workspacePath:($e==null?void 0:$e.workspacePath)??"",useHome:!($e!=null&&$e.workspaceId)&&!($e!=null&&$e.workspacePath)})})},wt=B=>{k?h(B):y(B.type,B.workspace,B.id)},bt=i.useCallback(async(B,oe,pe=!1)=>{if(B.mode===oe){pe&&B.sessionId&&M(B.sessionId);return}if(!l||!B.sessionId){pe&&B.sessionId&&M(B.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:B.sessionId,cliType:B.type,mode:oe}),pe&&M(B.sessionId)}catch(Ke){const Ie=pl(Ke);ml(Ke)?console.warn(Ie?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Ke instanceof Error?Ke.message:String(Ke)):console.error("Failed to switch CLI view mode:",Ke)}},[r,M,l]);return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${T.accent} relative overflow-hidden`,children:[s.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",T.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:k?ft.length>0?ft.map(B=>{const oe=a.find(nt=>(nt.type||"").toLowerCase()===(B.type||"").toLowerCase()&&yt(nt.status)!=="stopped"),pe=B.running||!!oe,Ke=!!oe&&oe.cdpConnected,Ie=q.includes(B.type||B.id||""),$e=S===(B.type||"");return s.jsxs("button",{onClick:()=>{if(Ke&&oe){const nt=oe.sessionId;nt?p(Yt(nt),{state:{openRemoteForTabKey:nt}}):p("/dashboard",{state:{openRemoteForTabKey:oe.id}});return}Ie||O(nt=>nt===(B.type||"")?"":B.type||"")},disabled:!!x||Ie,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Ke?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":$e?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:x&&x!==B.type?.4:1},children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:o(B.type)}),pe&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Ke?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:B.name||at(B.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Ke?"text-green-400":Ie?"text-orange-400":$e?"text-accent-primary":"text-text-muted"}`,children:Ke?"Open Session":Ie?"Starting...":$e?"Configure":"Select"})]})]},B.type)}):s.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",s.jsxs("button",{onClick:j,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[s.jsx(nu,{size:14})," Scan System"]})]}):K.length>0?K.map(B=>{const oe=S===B.type,pe=q.includes(B.type),Ie=!!a.find($e=>$e.type===B.type&&yt($e.status)!=="stopped");return s.jsxs("button",{onClick:()=>O($e=>$e===B.type?"":B.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${oe?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:B.icon}),Ie&&s.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:B.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${pe?"text-orange-400":oe?"text-accent-primary":"text-text-muted"}`,children:pe?"Starting...":oe?"Configure":"Select"})]})]},B.type)}):s.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),S&&(k?ft.find(B=>B.type===S):K.find(B=>B.type===S))&&s.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[s.jsx("span",{children:"Launch Settings"}),s.jsx("span",{className:"text-accent-primary font-bold",children:k?at(S):R.get(S)||S})]}),s.jsx(iy,{machine:t,selectedWorkspace:xe,resolvedWorkspacePath:qe,customPath:ie,canBrowse:!!l,onWorkspaceChange:se,onCustomPathChange:re,onOpenBrowseDialog:L}),!k&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!w&&e==="cli"&&s.jsx(Fl,{busy:!!b||!!x||q.includes(S),savedSessionsLoading:ce,savedSessionsError:be,savedSessionsLoaded:ye,savedSessionsCount:J.length,selectedSession:ve,onRefresh:()=>void U(S),onOpenHistory:()=>{S&&(ge(!0),Wl({hasLoadedInitialResults:ye,isLoading:ce})&&U(S))},onClearSelection:()=>z("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[w&&s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),s.jsx("input",{type:"text",placeholder:"Leave empty for default",value:W,onChange:B=>E(B.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"})]}),s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),s.jsx("input",{type:"text",placeholder:"Optional flags...",value:H,onChange:B=>P(B.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),C.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:C.map(B=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>P(B),title:B,children:B},B))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:je,disabled:!!b||!!x||q.includes(S),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:b===S||x===S?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+q.filter(B=>!a.some(oe=>oe.type===B&&yt(oe.status)!=="stopped")).length,")"]}),a.length===0&&Ge.length===0?s.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",T.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Ge.map(B=>s.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:o(B)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:k?at(B):R.get(B)||B}),s.jsx("div",{className:"text-[11px] text-text-muted",children:b===B?"Launching process...":"Waiting for process and session to register..."})]})]}),s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:"var(--status-warning)"},children:"starting"})]})},`pending:${B}`)),a.map(B=>{const oe=k?B:null,pe=!k&&!w?B:null,Ke=yt(B.status);return s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:o(B.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Je(B),(oe==null?void 0:oe.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",oe.version]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted flex min-w-0 flex-wrap items-center gap-2",children:[s.jsx("span",{className:"truncate",children:B.workspace||"—"}),u&&B.git&&B.workspace?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:Ie=>{Ie.stopPropagation(),u(B.daemonId??r,B.workspace)},children:s.jsx(Is,{git:B.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(Is,{git:B.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(pe==null?void 0:pe.mode)&&s.jsx("span",{className:pe.mode==="chat"?"text-violet-400":"text-text-secondary",children:pe.mode==="chat"?"Chat view":"Terminal view"})]}),pe&&(pe.runtimeKey||pe.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[pe.runtimeKey&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),s.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",pe.runtimeKey]}),s.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var Ie;(Ie=navigator.clipboard)==null||Ie.writeText(`adhdev attach ${pe.runtimeKey}`),g(pe.runtimeKey||null),window.setTimeout(()=>{g($e=>$e===pe.runtimeKey?null:$e)},1200)},children:A===pe.runtimeKey?"Copied":"Copy"})]}),pe.runtimeWriteOwner&&s.jsx("span",{style:{color:pe.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:pe.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:oy(pe.runtimeWriteOwner)})]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Ke==="stopped"?"bg-red-500/[0.08] text-red-500":Ke==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Ke}),k&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const Ie=B.sessionId;if(Ie){p(Yt(Ie),{state:{openRemoteForTabKey:Ie}});return}p("/dashboard",{state:{openRemoteForTabKey:B.id}})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-primary transition-colors cursor-pointer",title:"Open remote control",children:s.jsx(Tt,{size:13})}),s.jsx("button",{onClick:()=>{const Ie=B.workspace||"",{options:$e,selectedKey:nt}=cs({machine:t,currentWorkspacePath:Ie});Me({title:ns("restart-ide",at(B.type)),description:as("restart-ide"),confirmLabel:Ls("restart-ide"),busyLabel:Rs("restart-ide"),workspaceOptions:$e,selectedWorkspaceKey:nt,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:at(B.type)}]},async()=>{const jt=$e.find(Vt=>Vt.key===Ue.current),ct=(jt==null?void 0:jt.workspacePath)??"";if(ct&&ct!==Ie){await pt({type:B.type,workspacePath:ct});return}await N(B)})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-orange-500/20 text-orange-400 transition-colors cursor-pointer",title:"Restart",children:s.jsx(lr,{size:14})})]}),w&&s.jsx("button",{onClick:()=>{const Ie=B.sessionId;Ie&&M(Ie)},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:!B.sessionId,children:s.jsx(Ut,{size:14})}),pe&&Ke!=="stopped"&&s.jsxs(s.Fragment,{children:[pe.mode&&s.jsx(Qa,{mode:pe.mode,onChange:Ie=>void bt(pe,Ie,!1),compact:!0}),s.jsx("button",{onClick:()=>{const Ie=B.sessionId;Ie&&M(Ie)},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:!B.sessionId,children:pe.mode==="chat"?s.jsx(Ut,{size:14}):s.jsx(Tt,{size:13})})]}),Ke==="stopped"?s.jsx("button",{onClick:()=>{const Ie=B.workspace||"",$e=k?at(B.type):Je(B),{options:nt,selectedKey:jt}=cs({machine:t,currentWorkspacePath:Ie});Me({title:ns("restart-stopped",$e),description:as("restart-stopped"),confirmLabel:Ls("restart-stopped"),busyLabel:Rs("restart-stopped"),workspaceOptions:nt,selectedWorkspaceKey:jt,details:[{label:"Mode",value:T.label},{label:"Provider",value:$e}]},async()=>{const ct=nt.find(Vt=>Vt.key===Ue.current);await pt({type:B.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:q.includes(B.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:q.includes(B.type)?"⏳":s.jsx($a,{size:14})}):s.jsx("button",{onClick:()=>wt(B),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-red-500/20 text-red-400 transition-colors cursor-pointer",title:"Stop",children:s.jsx(St,{size:14})})]})]}),oe&&oe.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:oe.aiAgents.map(Ie=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${cc(Ie.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Ie.name," · ",yt(Ie.status)]},Ie.id))}),oe&&(De[oe.type]||[]).length>0&&l&&s.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[s.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:(De[oe.type]||[]).map(Ie=>s.jsxs("button",{disabled:Re===`${oe.type}.${Ie.type}`,onClick:async()=>{const $e=`${oe.type}.${Ie.type}`;ze($e);try{await l(r,"set_ide_extension",{ideType:oe.type,extensionType:Ie.type,enabled:!Ie.enabled}),Be(nt=>({...nt,[oe.type]:(nt[oe.type]||[]).map(jt=>jt.type===Ie.type?{...jt,enabled:!jt.enabled}:jt)}))}catch(nt){console.error("Extension toggle failed:",nt)}finally{ze(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 ${Ie.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Ie.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Ie.name,s.jsx("span",{className:"text-[9px] font-normal",children:Ie.enabled?"ON":"OFF"})]},Ie.type))})]})]},B.id)})]}),le&&l&&s.jsx(bn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:Z,directories:Ee,busy:Fe,error:Se,confirmLabel:"Use this folder",onClose:()=>ke(!1),onNavigate:B=>{V(B)},onConfirm:B=>{re(B),se("__custom__"),ke(!1)}}),Pe&&s.jsx(mo,{title:Pe.title,description:Pe.description,details:Pe.details,workspaceOptions:Pe.workspaceOptions,selectedWorkspaceKey:Qe,onWorkspaceChange:B=>{Ue.current=B,lt(B)},confirmLabel:Pe.confirmLabel,busyLabel:Pe.busyLabel,busy:dt,onConfirm:_e,onCancel:()=>{Le.current=null,He(null)}}),ae&&Q&&s.jsx(ro,{activeConv:Q,ides:[],isCreatingChat:!1,isRefreshingHistory:ce,savedSessions:J,isSavedSessionsLoading:ce,isResumingSavedSessionId:we,savedHistoryFilters:ee,missingWorkspaceResumePath:qe||null,onSavedHistoryFiltersChange:de,onClose:()=>ge(!1),onNewChat:()=>{z(""),ge(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{U(S)},onResumeSavedSession:B=>{if(!B.canResume||we)return;const oe=_(B);z(B.providerSessionId),G(B),ue(B.providerSessionId),ge(!1),pt({type:B.providerType,workspaceId:oe.workspaceId,workspacePath:oe.workspacePath,useHome:oe.useHome,resumeSessionId:B.providerSessionId}).finally(()=>{ue(pe=>pe===B.providerSessionId?null:pe)})}})]})}const Pi=[{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 ly({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:o,actions:c,getIcon:l,initialCategory:d="ide",initialWorkspaceId:f,initialWorkspacePath:u,sendDaemonCommand:p,onOpenGitDialog:m}){var j;const[y,N]=i.useState(d);i.useEffect(()=>{N(d)},[d]);const h=i.useMemo(()=>({ide:n.length,cli:a.length,acp:o.length}),[n.length,a.length,o.length]);return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),s.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[s.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:Pi.map(x=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${y===x.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>N(x.id),children:[s.jsx("span",{children:x.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${y===x.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:h[x.id]})]},x.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(j=Pi.find(x=>x.id===y))==null?void 0:j.helper})]}),y==="ide"&&s.jsx(sa,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:p,initialWorkspaceId:f,initialWorkspacePath:u,onOpenGitDialog:m}),y==="cli"&&s.jsx(sa,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:p,initialWorkspaceId:f,initialWorkspacePath:u,onOpenGitDialog:m}),y==="acp"&&s.jsx(sa,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:o,getIcon:l,actions:c,sendDaemonCommand:p,initialWorkspaceId:f,initialWorkspacePath:u,onOpenGitDialog:m})]})}function dy({onNicknameSynced:e}={}){var re,q,Y,le,ke,Z,Ce,Ee,We,Fe;const{id:t}=Md(),r=Ps(),n=La(),{sendCommand:a}=mt(),o=fr(),c=ll(),l=Kc(),d=l.ides||[],f=l.initialLoaded??!0,u=d.find(D=>D.id===t&&D.type==="adhdev-daemon"),p=d.some(D=>D.type==="adhdev-daemon"),m=t?(re=l.connectionRetryStatuses)==null?void 0:re[t]:void 0,y=!!(m!=null&&m.blocked),[N,h]=i.useState("workspace"),[j,x]=i.useState(null),b=i.useCallback((D,Se)=>{x({daemonId:D,workspace:Se})},[]),[v,A]=i.useState("ide"),g=i.useRef(null),[M,T]=i.useState(null),k=i.useRef("__home__"),[w,K]=i.useState("__home__"),[R,S]=i.useState(!1),O=i.useRef(null);i.useEffect(()=>{!t||!u||!(!u.workspaces||!u.availableProviders||!u.detectedIdes||!u.recentLaunches)||o(t,{minFreshMs:3e4}).catch(()=>{})},[o,u,t]),i.useEffect(()=>{if(!t||!u||N!=="overview")return;const D=u.machine;(typeof(D==null?void 0:D.cpus)!="number"||typeof(D==null?void 0:D.totalMem)!="number"||typeof(D==null?void 0:D.arch)!="string"||typeof(D==null?void 0:D.release)!="string")&&c(t,{minFreshMs:3e4}).catch(()=>{})},[N,c,u,t]),vh(t&&N==="overview"?[t]:[],{enabled:N==="overview",intervalMs:mm});const H=()=>{if(p){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},P=ag({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:O});i.useEffect(()=>rt.onToast(Se=>{l.setToasts(Le=>{if(Le.some(Ue=>Ue.message===Se.message&&Se.timestamp-Ue.timestamp<3e3))return Le;const He={id:Se.id,message:Se.message,type:Se.type,timestamp:Se.timestamp,targetKey:Se.targetKey,actions:Se.actions};return[...Le.slice(-4),He]});const Ae=Se.duration||5e3;setTimeout(()=>l.setToasts(Le=>Le.filter(Pe=>Pe.id!==Se.id)),Ae)}),[l]);const C=(u==null?void 0:u.availableProviders)||[],I={};for(const D of C)I[D.type]=D.icon;const W=D=>I[D]||"",E=u?{id:u.id,hostname:lc(u,{fallbackId:u.id}),platform:((q=u.machine)==null?void 0:q.platform)||"unknown",arch:((Y=u.machine)==null?void 0:Y.arch)||"",cpus:((le=u.machine)==null?void 0:le.cpus)||0,totalMem:((ke=u.machine)==null?void 0:ke.totalMem)||0,freeMem:(Z=u.machine)==null?void 0:Z.freeMem,availableMem:(Ce=u.machine)==null?void 0:Ce.availableMem,loadavg:(Ee=u.machine)==null?void 0:Ee.loadavg,uptime:(We=u.machine)==null?void 0:We.uptime,release:((Fe=u.machine)==null?void 0:Fe.release)||"",cdpConnected:!!u.cdpConnected,machineNickname:u.machineNickname||null,p2p:u.p2p?{screenshotActive:!1,...u.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:u.detectedIdes||[],workspaces:u.workspaces||[],defaultWorkspaceId:u.defaultWorkspaceId??u.activeWorkspaceId??null,defaultWorkspacePath:u.defaultWorkspacePath??u.activeWorkspacePath??null}:null,$=d.filter(D=>D.daemonId===t&&D.type!=="adhdev-daemon").filter(D=>!or(D)&&!js(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,version:D.version||"",instanceId:D.instanceId||"",status:D.status,workspace:D.workspace||null,terminals:D.terminals||0,aiAgents:of(D.aiAgents||(D.agents||[]).map(Se=>({id:Se.name,name:Se.name,status:Se.status,version:Se.version}))),activeChat:D.activeChat||null,chats:D.chats||[],childSessions:D.childSessions||[],cdpConnected:D.cdpConnected||!1,daemonId:t})),z=d.filter(D=>D.daemonId===t&&or(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,cliName:D.cliName||D.type,status:D.status,workspace:D.workspace||"",activeChat:D.activeChat||null,providerSessionId:D.providerSessionId,mode:D.mode,runtimeKey:D.runtimeKey,runtimeDisplayName:D.runtimeDisplayName,runtimeWorkspaceLabel:D.runtimeWorkspaceLabel,runtimeWriteOwner:D.runtimeWriteOwner||null,runtimeAttachedClients:D.runtimeAttachedClients||[],daemonId:t})),J=d.filter(D=>D.daemonId===t&&js(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,acpName:D.cliName||D.type,status:D.status,workspace:D.workspace||"",activeChat:D.activeChat||null,providerSessionId:D.providerSessionId,daemonId:t})),he=u?Ct(u,{fallbackId:t}):"",ce="workspace",te=n.state,ye=te==null?void 0:te.initialMachineTab,fe=te==null?void 0:te.initialWorkspaceCategory,be=te==null?void 0:te.initialWorkspaceId,X=te==null?void 0:te.initialWorkspacePath,ae=ye==="ides"||ye==="clis"||ye==="acps"?"workspace":ye||ce,ge=ye==="ides"?"ide":ye==="clis"?"cli":ye==="acps"?"acp":fe,ee=[...$.map(D=>{var Se,Ae,Le,Pe,He;return{id:`ide:${D.type}:${D.workspace||""}`,label:((Se=D.activeChat)==null?void 0:Se.title)||D.type,kind:"ide",providerType:D.type,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((He=(Pe=(Le=(Ae=D.activeChat)==null?void 0:Ae.messages)==null?void 0:Le.at)==null?void 0:Pe.call(Le,-1))==null?void 0:He.timestamp)||0}}),...z.map(D=>{var Se,Ae,Le,Pe,He;return{id:`cli:${D.type}:${D.workspace||""}`,label:((Se=D.activeChat)==null?void 0:Se.title)||D.cliName,kind:"cli",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((He=(Pe=(Le=(Ae=D.activeChat)==null?void 0:Ae.messages)==null?void 0:Le.at)==null?void 0:Pe.call(Le,-1))==null?void 0:He.timestamp)||0}}),...J.map(D=>{var Se,Ae,Le,Pe,He;return{id:`acp:${D.type}:${D.workspace||""}`,label:((Se=D.activeChat)==null?void 0:Se.title)||D.acpName,kind:"acp",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:fs(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((He=(Pe=(Le=(Ae=D.activeChat)==null?void 0:Ae.messages)==null?void 0:Le.at)==null?void 0:Pe.call(Le,-1))==null?void 0:He.timestamp)||0}})].sort((D,Se)=>(Se.lastLaunchedAt||0)-(D.lastLaunchedAt||0)),de=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(D=>({id:D.id,label:D.title||D.providerName||D.providerType,kind:D.kind,providerType:D.providerType,providerSessionId:D.providerSessionId,subtitle:fs(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace,summaryMetadata:D.summaryMetadata,lastLaunchedAt:D.lastLaunchedAt})):ee,we=i.useMemo(()=>{var Se;const D=((Se=l.connectionStates)==null?void 0:Se[t||""])||void 0;return d.filter(Ae=>Ae.daemonId===t&&Ae.type!=="adhdev-daemon").flatMap(Ae=>no(Ae,{connectionStates:t&&D?{[t]:D}:void 0,defaultConnectionState:D})).filter(Ae=>!(Ae.transport==="pty"&&Ae.mode==="terminal")).sort((Ae,Le)=>xa(Le)-xa(Ae))},[d,l.connectionStates,t]),ue=i.useCallback(D=>{const Se=Ya(D);Se&&r(Yt(Se))},[r]),xe=i.useCallback(()=>{g.current&&(S(!0),g.current().finally(()=>{g.current=null,S(!1),T(null)}))},[]),se=i.useCallback(D=>{if(!E)return;const{options:Se,selectedKey:Ae}=cs({machine:E,currentWorkspacePath:D.workspace}),Le=async()=>{A(D.kind),h("workspace")};g.current=async()=>{const Pe=Se.find(Qe=>Qe.key===k.current),He=(Pe==null?void 0:Pe.workspacePath)??null,Ue=(Pe==null?void 0:Pe.workspaceId)??null;if(D.kind==="ide"&&D.providerType){await P.handleLaunchIde(D.providerType,He?{workspace:He}:void 0);return}if((D.kind==="cli"||D.kind==="acp")&&D.providerType){await P.runLaunchCliCore({cliType:D.providerType,dir:Ue?void 0:He||"",workspaceId:Ue||void 0,model:D.kind==="acp"&&uc(D.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:D.providerSessionId});return}await Le()},k.current=Ae,K(Ae),T({title:D.kind==="ide"?ns("restart-ide",D.label):D.providerSessionId?to(D.label):ns("start-fresh",D.label),description:D.kind==="ide"?as("restart-ide"):D.providerSessionId?so():as("start-fresh"),confirmLabel:D.kind==="ide"?Ls("restart-ide"):D.providerSessionId?tn(!0):Ls("start-fresh"),busyLabel:D.kind==="ide"?Rs("restart-ide"):D.providerSessionId?Za(!0):Rs("start-fresh"),workspaceOptions:Se,details:[{label:"Mode",value:D.kind.toUpperCase()},...D.providerType?[{label:"Provider",value:D.providerType}]:[]]})},[P,E]);if(i.useEffect(()=>{h(ae)},[ce,ae,t]),i.useEffect(()=>{ge&&A(ge)},[ge,t]),!E)return f?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),s.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),s.jsx("button",{onClick:H,className:"machine-btn-back",children:"← Back"})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:"⏳ Loading machine..."})});const ie=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Tt,{size:14})," Workspace"]}),count:$.length+z.length+J.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(on,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(au,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(su,{size:14})," Logs"]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:H,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[P.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:P.nicknameInput,onChange:D=>P.setNicknameInput(D.target.value),onKeyDown:D=>{D.key==="Enter"&&P.handleSaveNickname(),D.key==="Escape"&&P.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:P.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),s.jsx("button",{onClick:()=>P.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{P.setEditingNickname(!0),P.setNicknameInput(E.machineNickname||"")},title:"Click to set nickname",children:he}),y?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),l.retryConnection&&t&&s.jsx("button",{onClick:()=>l.retryConnection(t),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:"Reconnect"})]}):s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[E.platform," · ",E.arch]}),s.jsxs("span",{children:[E.cpus," cores"]}),(u==null?void 0:u.version)&&s.jsxs("span",{children:["v",u.version]}),E.p2p.available&&s.jsxs("span",{children:["P2P ",E.p2p.state==="connected"?"connected":E.p2p.state]}),E.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:E.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ie.map(D=>s.jsxs("button",{onClick:()=>h(D.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${N===D.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[D.label,D.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${N===D.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:D.count})]},D.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[N==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(ay,{machineEntry:u,providers:C,recentLaunches:de,currentConversations:we,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",{})}catch{}},onOpenRecent:se,onOpenConversation:ue}),s.jsx(ly,{machine:E,machineId:t,providers:C,ideSessions:$,cliSessions:z,acpSessions:J,actions:P,getIcon:W,initialCategory:v,initialWorkspaceId:be,initialWorkspacePath:X,sendDaemonCommand:a,onOpenGitDialog:b})]}),N==="providers"&&s.jsx(hg,{machineId:t,providers:C,sendDaemonCommand:a}),N==="overview"&&s.jsx(og,{machineId:t,machine:E,ideSessions:$,cliSessions:z,acpSessions:J,actions:P,sendDaemonCommand:a}),N==="session-host"&&s.jsx(ry,{machineId:t,cliSessions:z,sendDaemonCommand:a}),N==="logs"&&s.jsx(Xg,{machineId:t,sendDaemonCommand:a})]})})}),P.launchPick&&E&&s.jsx(ny,{machine:E,launchPick:P.launchPick,actions:P}),M&&s.jsx(mo,{title:M.title,description:M.description,details:M.details,workspaceOptions:M.workspaceOptions,selectedWorkspaceKey:w,onWorkspaceChange:D=>{k.current=D,K(D)},confirmLabel:M.confirmLabel,busyLabel:M.busyLabel,busy:R,onConfirm:xe,onCancel:()=>{g.current=null,T(null)}}),j&&s.jsx(Ul,{daemonId:j.daemonId,workspace:j.workspace,onClose:()=>x(null)}),s.jsx(Yc,{toasts:l.toasts||[],onDismiss:D=>l.setToasts(Se=>Se.filter(Ae=>Ae.id!==D)),onClickToast:D=>{D.targetKey&&r(Yt(D.targetKey))}}),s.jsx("style",{children:`
|
|
89
|
+
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 S=await r(e,"session_host_prune_duplicate_sessions",{}),O=Qn(S);if(!(O!=null&&O.success))throw new Error((O==null?void 0:O.error)||"Duplicate prune failed");const H=O.result||{},P=Array.isArray(H.prunedSessionIds)?H.prunedSessionIds.length:0,C=typeof H.duplicateGroupCount=="number"?H.duplicateGroupCount:0;rt.showToast(`Pruned ${P} duplicate runtime(s) across ${C} group(s)`,"success"),await h()}catch(S){const O=S instanceof Error?S.message:"Duplicate prune failed";rt.showToast(O,"warning"),a(O)}finally{c(S=>S==="session_host_prune_duplicate_sessions"?null:S)}}},[e,h,r]),b=i.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((R,S)=>(S.lastActivityAt||0)-(R.lastActivityAt||0)),[u==null?void 0:u.sessions]),v=i.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:Qg(b),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,b]),A=v.liveRuntimes,g=v.recoverySnapshots,M=v.inactiveRecords,T=i.useMemo(()=>sy(A),[A]),k=i.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),w=i.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(R=>R.level==="warn"||R.level==="error")||null,[u==null?void 0:u.recentLogs]),K=(R,S)=>{var z;const O=o===`session_host_resume_session:${R.sessionId}`,H=o===`session_host_restart_session:${R.sessionId}`,P=o===`session_host_stop_session:${R.sessionId}`,C=Vl(R.meta),I=N.get(R.sessionId),W=R.attachedClients.length===1?"1 client":`${R.attachedClients.length} clients`,E=S==="recovery"?"Recover":"Resume",$=Zg(S);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:R.displayName||(I==null?void 0:I.cliName)||R.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${ty(R.lifecycle)}`,children:R.lifecycle}),C&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:C})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:R.workspaceLabel||(I==null?void 0:I.runtimeWorkspaceLabel)||R.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:R.runtimeKey}),R.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",R.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((z=R.writeOwner)==null?void 0:z.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:ey(R.writeOwner)}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[s.jsx(qi,{size:11})," ",W]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",_i(R.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",$]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[S==="recovery"&&(R.lifecycle==="interrupted"||R.lifecycle==="failed"||R.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{j("session_host_resume_session",R)},children:O?`${E}ing…`:E}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{j("session_host_restart_session",R)},children:H?"Restarting…":"Restart"}),S==="live"&&(R.lifecycle==="running"||R.lifecycle==="starting"||R.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!o,onClick:()=>{j("session_host_stop_session",R)},children:P?"Stopping…":"Stop"})]})]})},R.sessionId)};return s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(us,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Tp()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[T>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{x()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${T})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${y.toneClass}`,children:y.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{h()},disabled:p||l,children:[s.jsx(lr,{size:13}),p||l?"Refreshing…":"Refresh"]})]})]}),n&&!u&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(nr,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),u&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:g.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:_i(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Zn(u.hostStartedAt)})]})]}),w&&s.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(nr,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:w.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Zn(w.timestamp),w.sessionId?` · ${w.sessionId}`:""]})]}),s.jsxs("div",{className:"mb-4 space-y-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(Ea,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Jn("live")}),A.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):s.jsx("div",{className:"space-y-2",children:A.map(R=>K(R,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(us,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Jn("recovery")}),g.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:g.map(R=>K(R,"recovery"))})]}),M.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Jn("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:M.map(R=>K(R,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),k.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:k.map(R=>{var O;const S=b.find(H=>H.sessionId===R.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(S==null?void 0:S.displayName)||((O=N.get(R.sessionId))==null?void 0:O.cliName)||R.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[R.action,R.lifecycle?` · ${R.lifecycle}`:"",R.detail?` · ${R.detail}`:"",R.error?` · ${R.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${R.success===!1?"text-red-300":"text-text-secondary"}`,children:Zn(R.timestamp)})]},`${R.sessionId}:${R.timestamp}:${R.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function ny({machine:e,launchPick:t,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return s.jsx("div",{className:"fixed inset-0 z-[100] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(o=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{a(null),n({cliType:t.cliType,workspaceId:o.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:o.label||o.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:o.path})]},o.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),n({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:"Default workspace"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{a(null),n({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:"Home directory"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>a(null),children:"Cancel"})]})]})})}function ea({icon:e,children:t}){return s.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,s.jsx("span",{children:t})]})}function ta({children:e,className:t=""}){return s.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function ay({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:c}){const l=n.slice(0,6),d=r.slice(0,4),u=Zs(e,"0.9.61");return s.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[l.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(ea,{icon:s.jsx(Ut,{size:13}),children:"Current Chats"}),s.jsx(ta,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(p=>{const m=xa(p);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>c(p),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:it(p)}),m>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:ln(m)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:As(p)})]},p.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(ea,{icon:s.jsx(Qi,{size:13}),children:"Recent Launches"}),s.jsx(ta,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(p=>{const{metaText:m,updatedLabel:y}=Nl(p);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>o(p),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:p.label}),y&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:y})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:m})]},p.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(ea,{icon:s.jsx(nr,{size:13}),children:"Daemon Update"}),s.jsx(ta,{className:"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u?"Daemon update required":"Version mismatch detected"}),s.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:u?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),s.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:a,children:[s.jsx(lr,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function oy(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function iy({machine:e,selectedWorkspace:t,resolvedWorkspacePath:r,customPath:n,canBrowse:a,onWorkspaceChange:o,onCustomPathChange:c,onOpenBrowseDialog:l}){return s.jsxs("div",{className:"mb-3",children:[s.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[s.jsx("select",{value:t,onChange:d=>{const f=d.target.value;if(o(f),f==="__custom__"&&a){l();return}f!=="__custom__"&&c("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(e.workspaces||[]).length>0?s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(e.workspaces||[]).map(d=>s.jsxs("option",{value:d.id,children:[d.id===e.defaultWorkspaceId?"⭐ ":"",un(d.path,d.label)]},d.id)),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]})}),t==="__custom__"&&(a?s.jsx("button",{type:"button",className:"px-3 py-1.5 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] hover:border-accent-primary text-text-secondary hover:text-text-primary transition-colors",onClick:l,children:"Select workspace…"}):s.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:n,onChange:d=>c(d.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:t==="__custom__"?r?s.jsx("span",{className:"font-mono truncate block",title:r,children:r}):a?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":r?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:t===e.defaultWorkspaceId?"Default workspace":"Selected workspace"}),s.jsx("span",{className:"font-mono truncate block",title:r,children:r})]}):"No workspace selected. This launches in the home directory."})]})}const cy={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 _r(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function sa({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:o,actions:c,sendDaemonCommand:l,initialWorkspaceId:d,initialWorkspacePath:f,onOpenGitDialog:u}){const p=Ps(),{handleLaunchIde:m,handleStopCli:y,handleRestartIde:N,handleStopIde:h,handleDetectIdes:j,launchingIde:x,launchingAgentType:b,addLog:v}=c,[A,g]=i.useState(null),M=i.useCallback(B=>{B&&p(Yt(B))},[p]),T=cy[e],k=e==="ide",w=e==="acp",K=i.useMemo(()=>n.filter(B=>ps(B,e)),[e,n]),R=i.useMemo(()=>new Map(K.map(B=>[B.type,B.displayName||B.type])),[K]),[S,O]=i.useState(""),[H,P]=i.useState(""),[C,I]=i.useState([]),[W,E]=i.useState(""),[$,z]=i.useState(""),[J,he]=i.useState([]),[ce,te]=i.useState(!1),[ye,fe]=i.useState(!1),[be,X]=i.useState(""),[ae,ge]=i.useState(!1),[ee,de]=i.useState(()=>xt()),[we,ue]=i.useState(null),[xe,se]=i.useState(f?"__custom__":d||t.defaultWorkspaceId||""),[ie,re]=i.useState(f||""),[q,Y]=i.useState([]),[le,ke]=i.useState(!1),[Z,Ce]=i.useState(""),[Ee,We]=i.useState([]),[Fe,D]=i.useState(!1),[Se,Ae]=i.useState(""),Le=i.useRef(null),[Pe,He]=i.useState(null),Ue=i.useRef("__home__"),[Qe,lt]=i.useState("__home__"),[dt,ut]=i.useState(!1),Te=i.useRef(0),Ge=q.filter(B=>!a.some(oe=>oe.type===B&&yt(oe.status)!=="stopped")),Ze=i.useRef({});i.useEffect(()=>{t.defaultWorkspaceId&&!xe&&se(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),i.useEffect(()=>{if(f){se("__custom__"),re(f);return}d&&(se(d),re(""))},[d,f]),i.useEffect(()=>{k||S&&(K.some(B=>B.type===S)||(O(""),z("")))},[K,k,S]);const qe=(()=>{if(xe==="__custom__")return ie.trim();if(!xe)return"";const B=(t.workspaces||[]).find(oe=>oe.id===xe);return(B==null?void 0:B.path)||""})(),tt=i.useCallback(B=>{const oe=Ze.current[B];oe&&(clearTimeout(oe),delete Ze.current[B]),Y(pe=>pe.includes(B)?pe.filter(Ke=>Ke!==B):pe)},[]),F=i.useRef(new Set),V=i.useCallback(async B=>{if(l){D(!0),Ae("");try{const oe=await xn(l,r,B);Ce(oe.path),re(oe.path),We(oe.directories)}catch(oe){Ae(oe instanceof Error?oe.message:"Could not load folder")}finally{D(!1)}}},[r,l]),L=i.useCallback(()=>{if(!l)return;se("__custom__"),ke(!0);const B=a.map(pe=>pe.workspace),oe=hn(t.platform,pn(ie.trim(),qe,f,B,t.defaultWorkspacePath,(t.workspaces||[]).map(pe=>pe.path)));V(oe)},[ie,f,V,t.defaultWorkspacePath,t.platform,t.workspaces,a,qe,l]),G=i.useCallback(B=>{const oe=String(B.workspace||"").trim();if(!oe)return;const pe=(t.workspaces||[]).find(Ke=>_r(Ke.path)===_r(oe));if(pe){se(pe.id),re("");return}se("__custom__"),re(oe)},[t.workspaces]),_=i.useCallback(B=>{const oe=String(B.workspace||"").trim();if(!oe)return{workspaceId:null,workspacePath:"",useHome:!0};const pe=(t.workspaces||[]).find(Ke=>_r(Ke.path)===_r(oe));return pe?{workspaceId:pe.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:oe,useHome:!1}},[t.workspaces]),U=i.useCallback(async B=>{if(!l||!B||e!=="cli"){he([]),te(!1),fe(!1),X("");return}const oe=Te.current+1;Te.current=oe,te(!0),X("");try{const pe=await l(r,"list_saved_sessions",{providerType:B,kind:"cli",limit:30});if(Te.current!==oe)return;const Ke=(pe==null?void 0:pe.result)??pe;he(Array.isArray(Ke==null?void 0:Ke.sessions)?Ke.sessions:[])}catch(pe){if(Te.current!==oe)return;he([]),X(pe instanceof Error?pe.message:"Could not load saved sessions")}finally{Te.current===oe&&(te(!1),fe(!0))}},[e,r,l]),Q=i.useMemo(()=>{if(e!=="cli"||!S)return null;const B=R.get(S)||S;return{routeId:r,daemonId:r,providerSessionId:$||void 0,transport:"pty",mode:"chat",agentName:B,agentType:S,status:"idle",title:B,messages:[],ideType:S,workspaceName:qe,workspacePath:qe,displayPrimary:B,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${S}`}},[e,r,R,qe,$,S]),ne=i.useCallback(B=>{if(e==="ide"||!B){I([]);return}I(Kl(r,B))},[e,r]);i.useEffect(()=>{Te.current+=1,z(""),ne(S),fe(!1),he([]),X(""),te(!1)},[e,ne,U,S]);const ve=i.useMemo(()=>J.find(B=>B.providerSessionId===$)||null,[J,$]);i.useEffect(()=>{if(!$)return;const B=J.find(oe=>oe.providerSessionId===$);B!=null&&B.canResume||z("")},[J,$]);const Me=i.useCallback((B,oe)=>{Le.current=oe,Ue.current=B.selectedWorkspaceKey||"__home__",lt(B.selectedWorkspaceKey||"__home__"),He(B)},[]),_e=i.useCallback(()=>{Le.current&&(ut(!0),Le.current().finally(()=>{Le.current=null,ut(!1),He(null)}))},[]),Ne=i.useCallback(B=>{if(!B)return;Y(pe=>pe.includes(B)?pe:[...pe,B]);const oe=Ze.current[B];oe&&clearTimeout(oe),Ze.current[B]=setTimeout(()=>{Y(pe=>pe.includes(B)?pe.filter(Ke=>Ke!==B):pe),delete Ze.current[B]},2e4)},[]);i.useEffect(()=>{for(const oe of a)yt(oe.status)!=="stopped"&&(q.includes(oe.type)&&!F.current.has(oe.type)&&(F.current.add(oe.type),v("info",`${R.get(oe.type)||oe.type} launched`,!0)),tt(oe.type));const B=new Set(a.filter(oe=>yt(oe.status)!=="stopped").map(oe=>oe.type));F.current.forEach(oe=>{!q.includes(oe)&&!B.has(oe)&&F.current.delete(oe)})},[v,tt,a,q,R]),i.useEffect(()=>()=>{Object.values(Ze.current).forEach(clearTimeout),Ze.current={}},[]);const[De,Be]=i.useState({}),[Re,ze]=i.useState(null);i.useEffect(()=>{if(!k||!r||!l)return;(async()=>{try{const oe=await l(r,"get_ide_extensions",{}),pe=(oe==null?void 0:oe.result)||oe;pe!=null&&pe.success&&(pe!=null&&pe.ideExtensions)&&Be(pe.ideExtensions)}catch{}})()},[k,r,l]);const Je=B=>k?at(B.type):e==="cli"?B.cliName:B.acpName,ft=k?t.detectedIdes||[]:[],pt=i.useCallback(async B=>{const oe=(B==null?void 0:B.type)||S,pe=(B==null?void 0:B.workspacePath)??qe;if(k){await m(oe,pe?{workspace:pe}:void 0)&&Ne(oe);return}const Ke=await c.runLaunchCliCore({cliType:oe,dir:B!=null&&B.workspaceId?void 0:pe||void 0,workspaceId:(B==null?void 0:B.workspaceId)||void 0,useHome:(B==null?void 0:B.useHome)||!(B!=null&&B.workspaceId)&&!pe,argsStr:(B==null?void 0:B.argsStr)??(H||void 0),model:(B==null?void 0:B.model)??(w&&W||void 0),resumeSessionId:(B==null?void 0:B.resumeSessionId)||!w&&e==="cli"&&oe===S&&$||void 0});if(Ke.success||Ke.pending){const Ie=(B==null?void 0:B.argsStr)??H;!k&&(Ie!=null&&Ie.trim())&&(Ol(r,oe,Ie),ne(oe)),Ne(oe),Ke.success&&Ke.sessionId&&M(Ke.sessionId)}},[c,m,w,k,H,W,ne,Ne,r,M,qe,$,S]),ht=Gc(k?"ide":w?"acp":"cli",!k&&!w&&!!$),me=qc(k?"ide":w?"acp":"cli",!k&&!w&&!!$),je=()=>{var Ie;const B=k?at(S):R.get(S)||S,oe=!k&&!w&&!!$,{options:pe,selectedKey:Ke}=cs({machine:t,currentWorkspaceId:xe&&xe!=="__custom__"?xe:null,currentWorkspacePath:qe});Me({title:oe?to(B):ns("start-fresh",B),description:oe?so():as("start-fresh"),confirmLabel:ht,busyLabel:me,workspaceOptions:pe,selectedWorkspaceKey:Ke,details:[{label:"Mode",value:T.label},{label:"Provider",value:B},...!k&&e==="cli"&&$?[{label:"Resume",value:((Ie=J.find($e=>$e.providerSessionId===$))==null?void 0:Ie.title)||$}]:[],...!k&&H.trim()?[{label:"Arguments",value:H.trim()}]:[],...w&&W.trim()?[{label:"Model",value:W.trim()}]:[]]},async()=>{const $e=pe.find(nt=>nt.key===Ue.current);$e!=null&&$e.workspaceId?(se($e.workspaceId),re("")):$e!=null&&$e.workspacePath?(se("__custom__"),re($e.workspacePath)):(se(""),re("")),await pt({workspaceId:($e==null?void 0:$e.workspaceId)??null,workspacePath:($e==null?void 0:$e.workspacePath)??"",useHome:!($e!=null&&$e.workspaceId)&&!($e!=null&&$e.workspacePath)})})},wt=B=>{k?h(B):y(B.type,B.workspace,B.id)},bt=i.useCallback(async(B,oe,pe=!1)=>{if(B.mode===oe){pe&&B.sessionId&&M(B.sessionId);return}if(!l||!B.sessionId){pe&&B.sessionId&&M(B.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:B.sessionId,cliType:B.type,mode:oe}),pe&&M(B.sessionId)}catch(Ke){const Ie=pl(Ke);ml(Ke)?console.warn(Ie?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Ke instanceof Error?Ke.message:String(Ke)):console.error("Failed to switch CLI view mode:",Ke)}},[r,M,l]);return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${T.accent} relative overflow-hidden`,children:[s.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",T.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:k?ft.length>0?ft.map(B=>{const oe=a.find(nt=>(nt.type||"").toLowerCase()===(B.type||"").toLowerCase()&&yt(nt.status)!=="stopped"),pe=B.running||!!oe,Ke=!!oe&&oe.cdpConnected,Ie=q.includes(B.type||B.id||""),$e=S===(B.type||"");return s.jsxs("button",{onClick:()=>{if(Ke&&oe){const nt=oe.sessionId;nt?p(Yt(nt),{state:{openRemoteForTabKey:nt}}):p("/dashboard",{state:{openRemoteForTabKey:oe.id}});return}Ie||O(nt=>nt===(B.type||"")?"":B.type||"")},disabled:!!x||Ie,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Ke?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":$e?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:x&&x!==B.type?.4:1},children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:o(B.type)}),pe&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Ke?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:B.name||at(B.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Ke?"text-green-400":Ie?"text-orange-400":$e?"text-accent-primary":"text-text-muted"}`,children:Ke?"Open Session":Ie?"Starting...":$e?"Configure":"Select"})]})]},B.type)}):s.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",s.jsxs("button",{onClick:j,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[s.jsx(nu,{size:14})," Scan System"]})]}):K.length>0?K.map(B=>{const oe=S===B.type,pe=q.includes(B.type),Ie=!!a.find($e=>$e.type===B.type&&yt($e.status)!=="stopped");return s.jsxs("button",{onClick:()=>O($e=>$e===B.type?"":B.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${oe?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:B.icon}),Ie&&s.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:B.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${pe?"text-orange-400":oe?"text-accent-primary":"text-text-muted"}`,children:pe?"Starting...":oe?"Configure":"Select"})]})]},B.type)}):s.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),S&&(k?ft.find(B=>B.type===S):K.find(B=>B.type===S))&&s.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[s.jsx("span",{children:"Launch Settings"}),s.jsx("span",{className:"text-accent-primary font-bold",children:k?at(S):R.get(S)||S})]}),s.jsx(iy,{machine:t,selectedWorkspace:xe,resolvedWorkspacePath:qe,customPath:ie,canBrowse:!!l,onWorkspaceChange:se,onCustomPathChange:re,onOpenBrowseDialog:L}),!k&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!w&&e==="cli"&&s.jsx(Fl,{busy:!!b||!!x||q.includes(S),savedSessionsLoading:ce,savedSessionsError:be,savedSessionsLoaded:ye,savedSessionsCount:J.length,selectedSession:ve,onRefresh:()=>void U(S),onOpenHistory:()=>{S&&(ge(!0),Wl({hasLoadedInitialResults:ye,isLoading:ce})&&U(S))},onClearSelection:()=>z("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[w&&s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),s.jsx("input",{type:"text",placeholder:"Leave empty for default",value:W,onChange:B=>E(B.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"})]}),s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),s.jsx("input",{type:"text",placeholder:"Optional flags...",value:H,onChange:B=>P(B.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),C.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:C.map(B=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>P(B),title:B,children:B},B))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:je,disabled:!!b||!!x||q.includes(S),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:b===S||x===S?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+q.filter(B=>!a.some(oe=>oe.type===B&&yt(oe.status)!=="stopped")).length,")"]}),a.length===0&&Ge.length===0?s.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",T.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Ge.map(B=>s.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:o(B)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:k?at(B):R.get(B)||B}),s.jsx("div",{className:"text-[11px] text-text-muted",children:b===B?"Launching process...":"Waiting for process and session to register..."})]})]}),s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:"var(--status-warning)"},children:"starting"})]})},`pending:${B}`)),a.map(B=>{const oe=k?B:null,pe=!k&&!w?B:null,Ke=yt(B.status);return s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:o(B.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Je(B),(oe==null?void 0:oe.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",oe.version]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted flex min-w-0 flex-wrap items-center gap-2",children:[s.jsx("span",{className:"truncate",children:B.workspace||"—"}),u&&B.git&&B.workspace?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:Ie=>{Ie.stopPropagation(),u(B.daemonId??r,B.workspace)},children:s.jsx(Is,{git:B.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(Is,{git:B.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(pe==null?void 0:pe.mode)&&s.jsx("span",{className:pe.mode==="chat"?"text-violet-400":"text-text-secondary",children:pe.mode==="chat"?"Chat view":"Terminal view"})]}),pe&&(pe.runtimeKey||pe.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[pe.runtimeKey&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),s.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",pe.runtimeKey]}),s.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var Ie;(Ie=navigator.clipboard)==null||Ie.writeText(`adhdev attach ${pe.runtimeKey}`),g(pe.runtimeKey||null),window.setTimeout(()=>{g($e=>$e===pe.runtimeKey?null:$e)},1200)},children:A===pe.runtimeKey?"Copied":"Copy"})]}),pe.runtimeWriteOwner&&s.jsx("span",{style:{color:pe.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:pe.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:oy(pe.runtimeWriteOwner)})]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Ke==="stopped"?"bg-red-500/[0.08] text-red-500":Ke==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Ke}),k&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const Ie=B.sessionId;if(Ie){p(Yt(Ie),{state:{openRemoteForTabKey:Ie}});return}p("/dashboard",{state:{openRemoteForTabKey:B.id}})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-primary transition-colors cursor-pointer",title:"Open remote control",children:s.jsx(Tt,{size:13})}),s.jsx("button",{onClick:()=>{const Ie=B.workspace||"",{options:$e,selectedKey:nt}=cs({machine:t,currentWorkspacePath:Ie});Me({title:ns("restart-ide",at(B.type)),description:as("restart-ide"),confirmLabel:Ls("restart-ide"),busyLabel:Rs("restart-ide"),workspaceOptions:$e,selectedWorkspaceKey:nt,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:at(B.type)}]},async()=>{const jt=$e.find(Vt=>Vt.key===Ue.current),ct=(jt==null?void 0:jt.workspacePath)??"";if(ct&&ct!==Ie){await pt({type:B.type,workspacePath:ct});return}await N(B)})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-orange-500/20 text-orange-400 transition-colors cursor-pointer",title:"Restart",children:s.jsx(lr,{size:14})})]}),w&&s.jsx("button",{onClick:()=>{const Ie=B.sessionId;Ie&&M(Ie)},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:!B.sessionId,children:s.jsx(Ut,{size:14})}),pe&&Ke!=="stopped"&&s.jsxs(s.Fragment,{children:[pe.mode&&s.jsx(Qa,{mode:pe.mode,onChange:Ie=>void bt(pe,Ie,!1),compact:!0}),s.jsx("button",{onClick:()=>{const Ie=B.sessionId;Ie&&M(Ie)},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:!B.sessionId,children:pe.mode==="chat"?s.jsx(Ut,{size:14}):s.jsx(Tt,{size:13})})]}),Ke==="stopped"?s.jsx("button",{onClick:()=>{const Ie=B.workspace||"",$e=k?at(B.type):Je(B),{options:nt,selectedKey:jt}=cs({machine:t,currentWorkspacePath:Ie});Me({title:ns("restart-stopped",$e),description:as("restart-stopped"),confirmLabel:Ls("restart-stopped"),busyLabel:Rs("restart-stopped"),workspaceOptions:nt,selectedWorkspaceKey:jt,details:[{label:"Mode",value:T.label},{label:"Provider",value:$e}]},async()=>{const ct=nt.find(Vt=>Vt.key===Ue.current);await pt({type:B.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:q.includes(B.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:q.includes(B.type)?"⏳":s.jsx($a,{size:14})}):s.jsx("button",{onClick:()=>wt(B),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-red-500/20 text-red-400 transition-colors cursor-pointer",title:"Stop",children:s.jsx(St,{size:14})})]})]}),oe&&oe.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:oe.aiAgents.map(Ie=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${cc(Ie.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Ie.name," · ",yt(Ie.status)]},Ie.id))}),oe&&(De[oe.type]||[]).length>0&&l&&s.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[s.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:(De[oe.type]||[]).map(Ie=>s.jsxs("button",{disabled:Re===`${oe.type}.${Ie.type}`,onClick:async()=>{const $e=`${oe.type}.${Ie.type}`;ze($e);try{await l(r,"set_ide_extension",{ideType:oe.type,extensionType:Ie.type,enabled:!Ie.enabled}),Be(nt=>({...nt,[oe.type]:(nt[oe.type]||[]).map(jt=>jt.type===Ie.type?{...jt,enabled:!jt.enabled}:jt)}))}catch(nt){console.error("Extension toggle failed:",nt)}finally{ze(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 ${Ie.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Ie.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Ie.name,s.jsx("span",{className:"text-[9px] font-normal",children:Ie.enabled?"ON":"OFF"})]},Ie.type))})]})]},B.id)})]}),le&&l&&s.jsx(bn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:Z,directories:Ee,busy:Fe,error:Se,confirmLabel:"Use this folder",onClose:()=>ke(!1),onNavigate:B=>{V(B)},onConfirm:B=>{re(B),se("__custom__"),ke(!1)}}),Pe&&s.jsx(mo,{title:Pe.title,description:Pe.description,details:Pe.details,workspaceOptions:Pe.workspaceOptions,selectedWorkspaceKey:Qe,onWorkspaceChange:B=>{Ue.current=B,lt(B)},confirmLabel:Pe.confirmLabel,busyLabel:Pe.busyLabel,busy:dt,onConfirm:_e,onCancel:()=>{Le.current=null,He(null)}}),ae&&Q&&s.jsx(ro,{activeConv:Q,ides:[],isCreatingChat:!1,isRefreshingHistory:ce,savedSessions:J,isSavedSessionsLoading:ce,isResumingSavedSessionId:we,savedHistoryFilters:ee,missingWorkspaceResumePath:qe||null,onSavedHistoryFiltersChange:de,onClose:()=>ge(!1),onNewChat:()=>{z(""),ge(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{U(S)},onResumeSavedSession:B=>{if(!B.canResume||we)return;const oe=_(B);z(B.providerSessionId),G(B),ue(B.providerSessionId),ge(!1),pt({type:B.providerType,workspaceId:oe.workspaceId,workspacePath:oe.workspacePath,useHome:oe.useHome,resumeSessionId:B.providerSessionId}).finally(()=>{ue(pe=>pe===B.providerSessionId?null:pe)})}})]})}const Pi=[{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 ly({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:o,actions:c,getIcon:l,initialCategory:d="ide",initialWorkspaceId:f,initialWorkspacePath:u,sendDaemonCommand:p,onOpenGitDialog:m}){var j;const[y,N]=i.useState(d);i.useEffect(()=>{N(d)},[d]);const h=i.useMemo(()=>({ide:n.length,cli:a.length,acp:o.length}),[n.length,a.length,o.length]);return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),s.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[s.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:Pi.map(x=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${y===x.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>N(x.id),children:[s.jsx("span",{children:x.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${y===x.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:h[x.id]})]},x.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(j=Pi.find(x=>x.id===y))==null?void 0:j.helper})]}),y==="ide"&&s.jsx(sa,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:p,initialWorkspaceId:f,initialWorkspacePath:u,onOpenGitDialog:m}),y==="cli"&&s.jsx(sa,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:p,initialWorkspaceId:f,initialWorkspacePath:u,onOpenGitDialog:m}),y==="acp"&&s.jsx(sa,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:o,getIcon:l,actions:c,sendDaemonCommand:p,initialWorkspaceId:f,initialWorkspacePath:u,onOpenGitDialog:m})]})}function dy({onNicknameSynced:e}={}){var re,q,Y,le,ke,Z,Ce,Ee,We,Fe;const{id:t}=Md(),r=Ps(),n=La(),{sendCommand:a}=mt(),o=fr(),c=ll(),l=Kc(),d=l.ides||[],f=l.initialLoaded??!0,u=d.find(D=>D.id===t&&D.type==="adhdev-daemon"),p=d.some(D=>D.type==="adhdev-daemon"),m=t?(re=l.connectionRetryStatuses)==null?void 0:re[t]:void 0,y=!!(m!=null&&m.blocked),[N,h]=i.useState("workspace"),[j,x]=i.useState(null),b=i.useCallback((D,Se)=>{x({daemonId:D,workspace:Se})},[]),[v,A]=i.useState("ide"),g=i.useRef(null),[M,T]=i.useState(null),k=i.useRef("__home__"),[w,K]=i.useState("__home__"),[R,S]=i.useState(!1),O=i.useRef(null);i.useEffect(()=>{!t||!u||!(!u.workspaces||!u.availableProviders||!u.detectedIdes||!u.recentLaunches)||o(t,{minFreshMs:3e4}).catch(()=>{})},[o,u,t]),i.useEffect(()=>{if(!t||!u||N!=="overview")return;const D=u.machine;(typeof(D==null?void 0:D.cpus)!="number"||typeof(D==null?void 0:D.totalMem)!="number"||typeof(D==null?void 0:D.arch)!="string"||typeof(D==null?void 0:D.release)!="string")&&c(t,{minFreshMs:3e4}).catch(()=>{})},[N,c,u,t]),vh(t&&N==="overview"?[t]:[],{enabled:N==="overview",intervalMs:mm});const H=()=>{if(p){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},P=ag({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:O});i.useEffect(()=>rt.onToast(Se=>{l.setToasts(Le=>{if(Le.some(Ue=>Ue.message===Se.message&&Se.timestamp-Ue.timestamp<3e3))return Le;const He={id:Se.id,message:Se.message,type:Se.type,timestamp:Se.timestamp,targetKey:Se.targetKey,actions:Se.actions};return[...Le.slice(-4),He]});const Ae=Se.duration||5e3;setTimeout(()=>l.setToasts(Le=>Le.filter(Pe=>Pe.id!==Se.id)),Ae)}),[l]);const C=(u==null?void 0:u.availableProviders)||[],I={};for(const D of C)I[D.type]=D.icon;const W=D=>I[D]||"",E=u?{id:u.id,hostname:lc(u,{fallbackId:u.id}),platform:((q=u.machine)==null?void 0:q.platform)||"unknown",arch:((Y=u.machine)==null?void 0:Y.arch)||"",cpus:((le=u.machine)==null?void 0:le.cpus)||0,totalMem:((ke=u.machine)==null?void 0:ke.totalMem)||0,freeMem:(Z=u.machine)==null?void 0:Z.freeMem,availableMem:(Ce=u.machine)==null?void 0:Ce.availableMem,loadavg:(Ee=u.machine)==null?void 0:Ee.loadavg,uptime:(We=u.machine)==null?void 0:We.uptime,release:((Fe=u.machine)==null?void 0:Fe.release)||"",cdpConnected:!!u.cdpConnected,machineNickname:u.machineNickname||null,p2p:u.p2p?{screenshotActive:!1,...u.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:u.detectedIdes||[],workspaces:u.workspaces||[],defaultWorkspaceId:u.defaultWorkspaceId??u.activeWorkspaceId??null,defaultWorkspacePath:u.defaultWorkspacePath??u.activeWorkspacePath??null}:null,$=d.filter(D=>D.daemonId===t&&D.type!=="adhdev-daemon").filter(D=>!or(D)&&!js(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,version:D.version||"",instanceId:D.instanceId||"",status:D.status,workspace:D.workspace||null,terminals:D.terminals||0,aiAgents:of(D.aiAgents||(D.agents||[]).map(Se=>({id:Se.name,name:Se.name,status:Se.status,version:Se.version}))),activeChat:D.activeChat||null,chats:D.chats||[],childSessions:D.childSessions||[],cdpConnected:D.cdpConnected||!1,daemonId:t})),z=d.filter(D=>D.daemonId===t&&or(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,cliName:D.cliName||D.type,status:D.status,workspace:D.workspace||"",activeChat:D.activeChat||null,providerSessionId:D.providerSessionId,mode:D.mode,runtimeKey:D.runtimeKey,runtimeDisplayName:D.runtimeDisplayName,runtimeWorkspaceLabel:D.runtimeWorkspaceLabel,runtimeWriteOwner:D.runtimeWriteOwner||null,runtimeAttachedClients:D.runtimeAttachedClients||[],daemonId:t})),J=d.filter(D=>D.daemonId===t&&js(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,acpName:D.cliName||D.type,status:D.status,workspace:D.workspace||"",activeChat:D.activeChat||null,providerSessionId:D.providerSessionId,daemonId:t})),he=u?Ct(u,{fallbackId:t}):"",ce="workspace",te=n.state,ye=te==null?void 0:te.initialMachineTab,fe=te==null?void 0:te.initialWorkspaceCategory,be=te==null?void 0:te.initialWorkspaceId,X=te==null?void 0:te.initialWorkspacePath,ae=ye==="ides"||ye==="clis"||ye==="acps"?"workspace":ye||ce,ge=ye==="ides"?"ide":ye==="clis"?"cli":ye==="acps"?"acp":fe,ee=[...$.map(D=>{var Se,Ae,Le,Pe,He;return{id:`ide:${D.type}:${D.workspace||""}`,label:((Se=D.activeChat)==null?void 0:Se.title)||D.type,kind:"ide",providerType:D.type,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((He=(Pe=(Le=(Ae=D.activeChat)==null?void 0:Ae.messages)==null?void 0:Le.at)==null?void 0:Pe.call(Le,-1))==null?void 0:He.timestamp)||0}}),...z.map(D=>{var Se,Ae,Le,Pe,He;return{id:`cli:${D.type}:${D.workspace||""}`,label:((Se=D.activeChat)==null?void 0:Se.title)||D.cliName,kind:"cli",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((He=(Pe=(Le=(Ae=D.activeChat)==null?void 0:Ae.messages)==null?void 0:Le.at)==null?void 0:Pe.call(Le,-1))==null?void 0:He.timestamp)||0}}),...J.map(D=>{var Se,Ae,Le,Pe,He;return{id:`acp:${D.type}:${D.workspace||""}`,label:((Se=D.activeChat)==null?void 0:Se.title)||D.acpName,kind:"acp",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:fs(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((He=(Pe=(Le=(Ae=D.activeChat)==null?void 0:Ae.messages)==null?void 0:Le.at)==null?void 0:Pe.call(Le,-1))==null?void 0:He.timestamp)||0}})].sort((D,Se)=>(Se.lastLaunchedAt||0)-(D.lastLaunchedAt||0)),de=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(D=>({id:D.id,label:D.title||D.providerName||D.providerType,kind:D.kind,providerType:D.providerType,providerSessionId:D.providerSessionId,subtitle:fs(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace,summaryMetadata:D.summaryMetadata,lastLaunchedAt:D.lastLaunchedAt})):ee,we=i.useMemo(()=>{var Se;const D=((Se=l.connectionStates)==null?void 0:Se[t||""])||void 0;return d.filter(Ae=>Ae.daemonId===t&&Ae.type!=="adhdev-daemon").flatMap(Ae=>no(Ae,{connectionStates:t&&D?{[t]:D}:void 0,defaultConnectionState:D})).filter(Ae=>!(Ae.transport==="pty"&&Ae.mode==="terminal")).sort((Ae,Le)=>xa(Le)-xa(Ae))},[d,l.connectionStates,t]),ue=i.useCallback(D=>{const Se=Ya(D);Se&&r(Yt(Se))},[r]),xe=i.useCallback(()=>{g.current&&(S(!0),g.current().finally(()=>{g.current=null,S(!1),T(null)}))},[]),se=i.useCallback(D=>{if(!E)return;const{options:Se,selectedKey:Ae}=cs({machine:E,currentWorkspacePath:D.workspace}),Le=async()=>{A(D.kind),h("workspace")};g.current=async()=>{const Pe=Se.find(Qe=>Qe.key===k.current),He=(Pe==null?void 0:Pe.workspacePath)??null,Ue=(Pe==null?void 0:Pe.workspaceId)??null;if(D.kind==="ide"&&D.providerType){await P.handleLaunchIde(D.providerType,He?{workspace:He}:void 0);return}if((D.kind==="cli"||D.kind==="acp")&&D.providerType){await P.runLaunchCliCore({cliType:D.providerType,dir:Ue?void 0:He||"",workspaceId:Ue||void 0,model:D.kind==="acp"&&uc(D.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:D.providerSessionId});return}await Le()},k.current=Ae,K(Ae),T({title:D.kind==="ide"?ns("restart-ide",D.label):D.providerSessionId?to(D.label):ns("start-fresh",D.label),description:D.kind==="ide"?as("restart-ide"):D.providerSessionId?so():as("start-fresh"),confirmLabel:D.kind==="ide"?Ls("restart-ide"):D.providerSessionId?tn(!0):Ls("start-fresh"),busyLabel:D.kind==="ide"?Rs("restart-ide"):D.providerSessionId?Za(!0):Rs("start-fresh"),workspaceOptions:Se,details:[{label:"Mode",value:D.kind.toUpperCase()},...D.providerType?[{label:"Provider",value:D.providerType}]:[]]})},[P,E]);if(i.useEffect(()=>{h(ae)},[ce,ae,t]),i.useEffect(()=>{ge&&A(ge)},[ge,t]),!E)return f?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),s.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),s.jsx("button",{onClick:H,className:"machine-btn-back",children:"← Back"})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:"⏳ Loading machine..."})});const ie=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Tt,{size:14})," Workspace"]}),count:$.length+z.length+J.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(on,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(au,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(su,{size:14})," Logs"]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:H,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[P.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:P.nicknameInput,onChange:D=>P.setNicknameInput(D.target.value),onKeyDown:D=>{D.key==="Enter"&&P.handleSaveNickname(),D.key==="Escape"&&P.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:P.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),s.jsx("button",{onClick:()=>P.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{P.setEditingNickname(!0),P.setNicknameInput(E.machineNickname||"")},title:"Click to set nickname",children:he}),y?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),l.retryConnection&&t&&s.jsx("button",{onClick:()=>l.retryConnection(t),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:"Reconnect"})]}):s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[E.platform," · ",E.arch]}),s.jsxs("span",{children:[E.cpus," cores"]}),(u==null?void 0:u.version)&&s.jsxs("span",{children:["v",u.version]}),E.p2p.available&&s.jsxs("span",{children:["P2P ",E.p2p.state==="connected"?"connected":E.p2p.state]}),E.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:E.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ie.map(D=>s.jsxs("button",{onClick:()=>h(D.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${N===D.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[D.label,D.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${N===D.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:D.count})]},D.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[N==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(ay,{machineEntry:u,providers:C,recentLaunches:de,currentConversations:we,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",{})}catch{}},onOpenRecent:se,onOpenConversation:ue}),s.jsx(ly,{machine:E,machineId:t,providers:C,ideSessions:$,cliSessions:z,acpSessions:J,actions:P,getIcon:W,initialCategory:v,initialWorkspaceId:be,initialWorkspacePath:X,sendDaemonCommand:a,onOpenGitDialog:b})]}),N==="providers"&&s.jsx(hg,{machineId:t,providers:C,sendDaemonCommand:a}),N==="overview"&&s.jsx(og,{machineId:t,machine:E,ideSessions:$,cliSessions:z,acpSessions:J,actions:P,sendDaemonCommand:a}),N==="session-host"&&s.jsx(ry,{machineId:t,cliSessions:z,sendDaemonCommand:a}),N==="logs"&&s.jsx(Xg,{machineId:t,sendDaemonCommand:a})]})})}),P.launchPick&&E&&s.jsx(ny,{machine:E,launchPick:P.launchPick,actions:P}),M&&s.jsx(mo,{title:M.title,description:M.description,details:M.details,workspaceOptions:M.workspaceOptions,selectedWorkspaceKey:w,onWorkspaceChange:D=>{k.current=D,K(D)},confirmLabel:M.confirmLabel,busyLabel:M.busyLabel,busy:R,onConfirm:xe,onCancel:()=>{g.current=null,T(null)}}),j&&s.jsx(Ul,{daemonId:j.daemonId,workspace:j.workspace,onClose:()=>x(null)}),s.jsx(Yc,{toasts:l.toasts||[],onDismiss:D=>l.setToasts(Se=>Se.filter(Ae=>Ae.id!==D)),onClickToast:D=>{D.targetKey&&r(Yt(D.targetKey))}}),s.jsx("style",{children:`
|
|
90
90
|
@keyframes toast-in {
|
|
91
91
|
from { opacity: 0; transform: translateX(40px); }
|
|
92
92
|
to { opacity: 1; transform: translateX(0); }
|
|
93
93
|
}
|
|
94
|
-
`})]})}function go(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function uy(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),r=go();return r&&!t.searchParams.has("token")&&t.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function Dt(e,t){return await fetch(uy(e),{credentials:"same-origin",...t})}function Gl(){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 fy{constructor(){Ye(this,"adapters",new Map);Ye(this,"states",new Map);Ye(this,"runtimeListeners",new Map);Ye(this,"screenshotCallbacks",new Map);Ye(this,"statusCallbacks",new Set)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(t,r){this.adapters.set(t,r),this.states.set(t,r.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,r){this.states.set(t,r)}retryConnection(t){}get(t){const r=this.resolveDaemonId(t);return r?this.adapters.get(r):void 0}getState(t){const r=this.resolveDaemonId(t);return r&&this.states.get(r)||"disconnected"}sendData(t,r){return!1}sendPtyInput(t,r,n){return!1}onScreenshot(t,r){return this.screenshotCallbacks.set(t,r),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,r){this.screenshotCallbacks.forEach(n=>n(t,r))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,r){this.statusCallbacks.forEach(n=>n(t,r))}emitRuntimeSnapshot(t,r,n=0,a=!1,o,c){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:o,rows:c})}emitSessionOutput(t,r,n){!t||typeof r!="string"||!r||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(t,r){const n=this.runtimeListeners.get(t)||new Set;return n.add(r),this.runtimeListeners.set(t,n),()=>{const a=this.runtimeListeners.get(t);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,r,n){if(!r)return{success:!1,error:"sessionId is required"};const a=new URL(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`,window.location.origin);typeof(n==null?void 0:n.sinceSeq)=="number"&&a.searchParams.set("sinceSeq",String(n.sinceSeq));const o=await Dt(`${a.pathname}${a.search}`);if(!o.ok){let l=`Runtime snapshot unavailable (${o.status})`;try{const d=await o.json();d!=null&&d.error&&(l=d.error)}catch{}return{success:!1,error:l}}const c=await o.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof c.seq=="number"?c.seq:0,text:typeof c.text=="string"?c.text:"",truncated:!!c.truncated,cols:typeof c.cols=="number"?c.cols:void 0,rows:typeof c.rows=="number"?c.rows:void 0,force:!!(n!=null&&n.force)}),{success:!0}}emitRuntimeEvent(t,r){var n;(n=this.runtimeListeners.get(t))==null||n.forEach(a=>a(r))}}const Ot=new fy;function my(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=go();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Pr=my(),Di=3e3,py=3e4;let Rt=null,hy=0;const an=new Map;let Qt=null,tr=null;function Ei(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Vs(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function xy(e){return e==="connected"?"connected":e}async function Ur(e,t,r){const n=Qc(e,r||{}),a=Rt;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++hy}_${Date.now()}`;return new Promise((c,l)=>{const d=setTimeout(()=>{an.delete(o),l(new Error(`WS command timeout: ${t}`))},3e4);an.set(o,{resolve:f=>{clearTimeout(d),c(f)},reject:f=>{clearTimeout(d),l(f)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Ma(e,t){const r=Rt;if(!r||r.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(t)),!0}catch{return!1}}function by(e,t,r){const n=Rt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=Qc(e,{sessionId:t,targetSessionId:t,data:r});try{return n.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}class gy{constructor(t){Ye(this,"daemonId");Ye(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN}get connectionState(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return Ur(this.daemonId,t,r)}async sendInput(t,r){return Ur(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Qt&&(clearInterval(Qt),Qt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Ur(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(o=>o.blob());Ot.emitScreenshot(this.daemonId,a)}}catch{}};r(),Qt=setInterval(r,2e3)}stopScreenshots(t){Qt&&(clearInterval(Qt),Qt=null)}}let At=null;function yy(e){return(!At||At.daemonId!==e)&&(At=new gy(e)),At}function vy({children:e}){const t=i.useRef(rr()),r=rr();t.current=r;const{setUserName:n}=ds(),a=i.useRef(n);a.current=n;const o=i.useRef(null),c=i.useRef(null),[,l]=i.useState("disconnected"),d=i.useCallback((h,j)=>{l(h),tr==null||tr(h,j)},[]),f=i.useRef(null),u=i.useRef(),p=i.useRef(Di),m=i.useRef(!0),y=i.useRef(!1),N=i.useRef("initial_connect");return i.useEffect(()=>{m.current=!0,y.current=!1;function h(){var b,v;if(!m.current||((b=f.current)==null?void 0:b.readyState)===WebSocket.OPEN||((v=f.current)==null?void 0:v.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Pr}...`),Vs("connect_attempt",{url:Pr,reason:N.current,delayMs:p.current});let x;try{x=new WebSocket(Pr)}catch(A){console.error("[Standalone WS] Failed to create WebSocket:",A),j();return}f.current=x,x.onopen=()=>{if(!m.current){x.close();return}d("connected"),p.current=Di,Vs("open",{url:Pr,reason:N.current}),Ht.resubscribeAll({sendData:Ma}),console.log("[Standalone WS] Connected")},Rt=x,x.onmessage=A=>{var g,M;try{const T=JSON.parse(A.data);if((T.type==="command_result"||T.type==="error")&&T.requestId){const k=an.get(T.requestId);k&&(an.delete(T.requestId),T.type==="error"?k.reject(new Error(((g=T.data)==null?void 0:g.message)||"Command failed")):k.resolve(T.data));return}if(T.type==="session_output"){const k=T.sessionId||T.cliId||T.cliType;k&&Ot.emitSessionOutput(k,typeof T.data=="string"?T.data:"",typeof T.seq=="number"?T.seq:void 0);return}if(T.type==="runtime_snapshot"){Ot.emitRuntimeSnapshot(T.sessionId,typeof T.text=="string"?T.text:"",typeof T.seq=="number"?T.seq:0,!!T.truncated,typeof T.cols=="number"?T.cols:void 0,typeof T.rows=="number"?T.rows:void 0);return}if(T.type==="topic_update"){const k=T.update;k&&Ht.publish(k);return}if(T.type==="status"||T.type==="initial_state"){const k=T.data;if(!k)return;const{injectEntries:w,markLoaded:K,getIdes:R}=t.current,S=k.instanceId||"standalone",O=R().find(C=>C.id===S),H=yy(S);Ot.register(S,H),Ot.setState(S,"connected"),d("connected",S),Ot.emitStatus(S,k);const P=Zr(k,{daemonId:S,existingDaemon:O,existingEntries:R()});Ei("ws_status",{type:T.type,daemonId:S,sessions:(k.sessions||[]).map(C=>({id:C.id,parentId:C.parentId,providerType:C.providerType,kind:C.kind,transport:C.transport,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,title:C.title})),recentLaunches:(k.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),Ei("entries",{daemonId:S,entries:P.filter(C=>C.type!=="adhdev-daemon").map(C=>({id:C.id,type:C.type,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,sessionId:C.sessionId}))}),P.length>0&&w(P,{authoritativeDaemonIds:[S]}),K(),c.current!==S&&((M=o.current)==null||M.call(o),c.current=S,o.current=Ht.subscribe({sendData:Ma},S,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${S}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const I=t.current.getIdes(),W=I.find($=>$.id===S),E=Zr(C.status,{daemonId:S,existingDaemon:W,existingEntries:I,timestamp:C.timestamp});E.length>0&&t.current.injectEntries(E,{authoritativeDaemonIds:[S]}),C.userName&&a.current&&a.current(C.userName)}))}}catch(T){console.error("[Standalone WS] Parse error:",T)}},x.onclose=A=>{m.current&&(At==null||At.stopScreenshots(),At&&Ot.setState(At.daemonId,"disconnected"),d("disconnected"),f.current=null,N.current=`close:${A.code}${A.wasClean?":clean":":unclean"}`,Vs("close",{code:A.code,reason:A.reason||"",wasClean:A.wasClean}),j())},x.onerror=A=>{y.current||!m.current||(N.current="error",Vs("error",{message:A instanceof Event?"event":String(A),readyState:x.readyState}),console.warn("[Standalone WS] Error, will reconnect:",A))}}function j(){if(!m.current)return;clearTimeout(u.current);const x=p.current;console.log(`[Standalone WS] Reconnecting in ${x}ms...`),Vs("schedule_reconnect",{reason:N.current,delayMs:x}),u.current=setTimeout(()=>{p.current=Math.min(p.current*1.5,py),h()},x)}return h(),()=>{var x;m.current=!1,y.current=!0,(x=o.current)==null||x.call(o),o.current=null,c.current=null,clearTimeout(u.current),f.current&&(f.current.onerror=null,f.current.onclose=null,f.current.close(),f.current=null,Rt=null),At&&(At.stopScreenshots(),Ot.unregister(At.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function wy({children:e}){const[t,r]=i.useState("disconnected"),[n,a]=i.useState(null);i.useEffect(()=>(tr=(c,l)=>{r(c),l&&a(l)},()=>{tr=null}),[]);const o=i.useMemo(()=>{const c=t==="connected",l=xy(t),d={};return n&&(d[n]=l),d.standalone=l,{wsStatus:t,isConnected:c,connectionStates:d}},[t,n]);return s.jsx(Vd,{connectionOverrides:o,children:s.jsx(vy,{children:e})})}const ql="adhdev_standalone_font_preferences",ls={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},vn=[{id:"default",label:"Default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS font-family stack"}],cr=[{id:"default",label:"Default mono",family:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',description:"Current monospace stack"},{id:"jetbrains-mono",label:"JetBrains Mono",family:'"JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Readable coding font with strong punctuation"},{id:"fira-code",label:"Fira Code",family:'"Fira Code", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Popular ligature-friendly code font"},{id:"cascadia-code",label:"Cascadia Code",family:'"Cascadia Code", "Cascadia Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Windows-friendly modern coding font"},{id:"berkeley-mono",label:"Berkeley Mono",family:'"Berkeley Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace',description:"Editorial-feeling mono stack if installed"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS monospace stack"}],jy=new Set(vn.map(e=>e.id)),ky=new Set(cr.map(e=>e.id));function $t(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:zr("chat",t.chat),code:zr("code",t.code),terminal:zr("terminal",t.terminal)}}function zr(e,t){const r=ls[e],n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof n.preset=="string"?n.preset.trim():"",o=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?jy:ky).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function Vr(e,t){var a;const r=zr(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?vn:cr;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function Sy(e){const t=$t(e),r=Vr("chat",t.chat),n=Vr("code",t.code),a=Vr("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function es(e,t=document.documentElement){const r=$t(e),n=Sy(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function Aa(e){const t=$t(e);try{localStorage.setItem(ql,JSON.stringify(t))}catch{}return t}function Ny(){try{const e=localStorage.getItem(ql);if(e)return $t(JSON.parse(e))}catch{}return ls}function Cy(){return es(Ny())}function Gs(e,t){var n;const r=e==="chat"?vn:cr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const Ty=[{id:"dashboard",path:"/dashboard",icon:s.jsx(Gi,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(us,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:s.jsx(on,{}),label:"Settings"}];function My({children:e}){const t=Ps(),r=La(),n=i.useMemo(()=>Ty.map(o=>({...o,active:r.pathname.startsWith(o.path),onSelect:()=>t(o.path)})),[r.pathname,t]),a=i.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Docs"}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(Yi,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Xi,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(Vp,{brand:({collapsed:o})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!o&&s.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:a,footerInfo:({collapsed:o})=>o?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.60"]}),footerActions:({collapsed:o,toggleCollapsed:c})=>s.jsxs("div",{className:`nav-item cursor-pointer ${o?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:o?"Expand sidebar":"Collapse sidebar",children:[s.jsx("span",{className:"nav-icon text-base",children:o?"›":"‹"}),!o&&s.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const Ay=[{icon:s.jsx(us,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Ut,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Ji,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(Tt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(ar,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Yi,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Iy=[{icon:s.jsx(iu,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Gi,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(cn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(tu,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(qi,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(ru,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Ly=[{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 Ry(){return s.jsxs(sl,{icon:s.jsx(Xi,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","0.9.60"]}),children:[s.jsx(Nt,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:"Keep the same dashboard experience, with the runtime fully on-device."}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:"Standalone keeps the browser, daemon, screenshots, and control path on your own machine. It is the same core product shape as cloud, just without the remote networking and team layers."})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"Docs ↗"}),s.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"GitHub ↗"}),s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:"Try Cloud ↗"})]})]})}),s.jsx(Nt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:Ay.map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(Nt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:Zc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:tl.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:el.map(e=>`${e.icon} ${e.name}`)}].map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(t=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:t},t))})]},e.label))})}),s.jsx(Nt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:Iy.map(e=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(Nt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),s.jsx("tbody",{children:Ly.map((e,t)=>s.jsxs("tr",{className:t%2===0?"bg-bg-glass":"bg-transparent",children:[s.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e.feature}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:e.selfhost?s.jsx("span",{className:"text-emerald-500",children:"✓"}):s.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:s.jsx("span",{className:"text-emerald-500",children:"✓"})})]},e.feature))})]})})}),s.jsx(nl,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:"Cloud is optional, not required",description:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",action:s.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(bu,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function ra(e,t,r){return{...e,[t]:r}}function na({surface:e,title:t,description:r,value:n,options:a,onChange:o}){return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("select",{className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",value:n.preset,onChange:c=>{const l=c.target.value;o(l==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:l})},children:a.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),n.preset==="custom"&&s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:n.customFamily||"",onChange:c=>o({preset:"custom",customFamily:c.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",s.jsx("span",{className:"font-mono break-all",children:Vr(e,n)})]})]})]})}function _y({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:o,onSave:c,onResetToSaved:l,onResetToDefaults:d}){const f=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&s.jsx("div",{className:"rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300",children:n}),a&&s.jsx("div",{className:"rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-300",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(na,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:vn,onChange:u=>o(ra(e,"chat",u))}),s.jsx(na,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:cr,onChange:u=>o(ra(e,"code",u))}),s.jsx(na,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:cr,onChange:u=>o(ra(e,"terminal",u))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",Gs("chat",e.chat.preset)," · Code: ",Gs("code",e.code.preset)," · Terminal: ",Gs("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Gs("chat",ls.chat.preset)," / ",Gs("code",ls.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:c,disabled:r||!f,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),s.jsx("button",{type:"button",onClick:l,disabled:r||!f,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert to saved"}),s.jsx("button",{type:"button",onClick:d,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function Py(){const{ides:e}=ds(),t=e.find(X=>X.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=mt(),{userName:a}=ds(),[o,c]=i.useState(a||""),[l,d]=i.useState(null),[f,u]=i.useState(null),[p,m]=i.useState(ls),[y,N]=i.useState(!1),[h,j]=i.useState(""),[x,b]=i.useState(""),[v,A]=i.useState("127.0.0.1"),[g,M]=i.useState(""),[T,k]=i.useState(""),[w,K]=i.useState(""),[R,S]=i.useState(""),[O,H]=i.useState(""),[P,C]=i.useState(!1),I=async()=>{const ae=await(await Dt("/auth/session")).json();d(ae)},W=async()=>{const ae=await(await Dt("/api/v1/standalone/preferences")).json();u(ae),A(ae.standaloneBindHost);const ge=$t(ae.standaloneFontPreferences);m(ge),es(ge),Aa(ge)};i.useEffect(()=>{a!==void 0&&c(a)},[a]),i.useEffect(()=>{Promise.all([I(),W()]).catch(X=>{S(X instanceof Error?X.message:String(X))})},[]),i.useEffect(()=>{es(p)},[p]);const E=X=>{const ae=X.target.value.trim();t!=null&&t.id&&ae!==a&&n(t.id,"set_user_name",{userName:ae}).catch(console.error)},[$,z]=i.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),J=X=>{z(X);try{localStorage.setItem("adhdev_sound",X?"1":"0")}catch{}},he=async()=>{j(""),b(""),N(!0);try{const X=$t(p),ae=await Dt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:X})}),ge=await ae.json();if(!ae.ok)throw new Error((ge==null?void 0:ge.error)||"Failed to save standalone font preferences");const ee=$t(ge.standaloneFontPreferences);u(ge),m(ee),es(ee),Aa(ee),b("Standalone chat fonts saved for this self-hosted dashboard.")}catch(X){j(X instanceof Error?X.message:String(X))}finally{N(!1)}},ce=()=>{const X=$t(f==null?void 0:f.standaloneFontPreferences);j(""),b(""),m(X),es(X)},te=()=>{j(""),b(""),m(ls),es(ls)},ye=async()=>{S(""),H(""),C(!0);try{const X=await Dt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:v})}),ae=await X.json();if(!X.ok)throw new Error((ae==null?void 0:ae.error)||"Failed to save standalone network preference");u(ae),A(ae.standaloneBindHost),H(ae.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(X){S(X instanceof Error?X.message:String(X))}finally{C(!1)}},fe=async()=>{if(S(""),H(""),T.trim().length<4){S("Password must be at least 4 characters.");return}if(T!==w){S("New password and confirmation do not match.");return}C(!0);try{const X=await Dt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:g,newPassword:T})}),ae=await X.json();if(!X.ok)throw new Error((ae==null?void 0:ae.error)||"Failed to save password");d(ae),await W(),M(""),k(""),K(""),H(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Gl()}catch(X){S(X instanceof Error?X.message:String(X))}finally{C(!1)}},be=async()=>{S(""),H(""),C(!0);try{const X=await Dt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:g,clear:!0})}),ae=await X.json();if(!X.ok)throw new Error((ae==null?void 0:ae.error)||"Failed to clear password");d(ae),await W(),M(""),k(""),K(""),H("Standalone password disabled.")}catch(X){S(X instanceof Error?X.message:String(X))}finally{C(!1)}};return s.jsxs(sl,{icon:s.jsx(on,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(Cr,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint."}),(l==null?void 0:l.publicHostWarning)&&s.jsx(Cr,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),s.jsx(Nt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:"Version"}),s.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.60"]}),s.jsx("span",{className:"text-text-muted",children:"Status"}),s.jsx("span",{className:t?"text-green-400":"text-yellow-400",children:t?"● Running":"○ Not connected"}),s.jsx("span",{className:"text-text-muted",children:"Current bind"}),s.jsx("span",{className:"font-mono text-xs",children:(f==null?void 0:f.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Default bind"}),s.jsx("span",{className:"font-mono text-xs",children:(f==null?void 0:f.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Auth"}),s.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),s.jsx(Nt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:v==="127.0.0.1",onChange:()=>A("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 127.0.0.1. Best when only this machine should open the dashboard."})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:v==="0.0.0.0",onChange:()=>A("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points."})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:()=>{ye()},disabled:P,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:P?"Saving…":"Save default network mode"}),s.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(f==null?void 0:f.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),s.jsx(Nt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:l!=null&&l.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),R&&s.jsx(Cr,{variant:"error",children:R}),O&&s.jsx(Cr,{variant:"success",children:O}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:g,onChange:X=>M(X.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"New password":"New standalone password",value:T,onChange:X=>k(X.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors md:col-span-2",placeholder:"Confirm new password",value:w,onChange:X=>K(X.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{fe()},disabled:P,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:P?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{be()},disabled:P,className:"rounded-lg border border-red-500/30 bg-red-500/10 text-red-300 px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Disable password"})]})]})}),s.jsx(Nt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(X=>s.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${X.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:X.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:X.type})]},X.type))})}),s.jsx(Nt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(th,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(Nt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),s.jsx(ah,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose a preset or create a custom surface, accent, and chat palette for the standalone UI."}),s.jsx(mh,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Fonts"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Standalone-only typography overrides for chat text, markdown code, and terminal output."}),s.jsx(_y,{value:p,savedValue:$t(f==null?void 0:f.standaloneFontPreferences),saving:y,error:h,notice:x,onChange:m,onSave:()=>{he()},onResetToSaved:ce,onResetToDefaults:te})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose whether phones open the dashboard as a chat app first or in the full workspace layout."}),s.jsx(xh,{})]})]})}),s.jsx(Nt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Qp,{}),s.jsx(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xu,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:$,onChange:J})]})}),s.jsx(Nt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(eu,{size:16,className:"text-text-secondary"})," Display Name"]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-1.5 text-sm w-48 text-right focus:border-accent focus:outline-none transition-colors",placeholder:"Anonymous",value:o,onChange:X=>c(X.target.value),onBlur:E,onKeyDown:X=>{X.key==="Enter"&&X.currentTarget.blur()}})]})})})]})}Up();uh();Cy();const Dy=Ui({baseUrl:"",getToken:go});function Ey({children:e}){const[t,r]=i.useState(null),[n,a]=i.useState(!0),[o,c]=i.useState(""),[l,d]=i.useState(""),[f,u]=i.useState(!1),p=async()=>{a(!0),d("");try{const N=await(await Dt("/auth/session")).json();r(N)}catch(y){d(y instanceof Error?y.message:String(y))}finally{a(!1)}};i.useEffect(()=>{p()},[]),i.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let y=!1;return(async()=>{try{const N=await Dt("/api/v1/standalone/preferences");if(!N.ok)return;const h=await N.json();if(y)return;const j=$t(h.standaloneFontPreferences);es(j),Aa(j)}catch{}})(),()=>{y=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const m=async y=>{y.preventDefault(),u(!0),d("");try{const N=await Dt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),h=await N.json();if(!N.ok)throw new Error((h==null?void 0:h.error)||"Login failed");r(h),c(""),Gl()}catch(N){d(N instanceof Error?N.message:String(N))}finally{u(!1)}};return n?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):t?!t.required||t.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:t.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),t.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:m,children:[s.jsx("input",{type:"password",value:o,onChange:y=>c(y.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),s.jsx("button",{type:"submit",disabled:f||!o,className:"rounded-lg bg-accent text-white px-3 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:f?"Signing in…":"Unlock dashboard"})]}):s.jsx("div",{className:"rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-300",children:"Password login is not enabled on this server."}),l&&s.jsx("div",{className:"rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:l})]})}):s.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",l||"unknown error"]})}function $i(){const{ides:e,initialLoaded:t}=ds();if(!t)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?s.jsx(ia,{to:`/machines/${r.id}`,replace:!0}):s.jsx(ia,{to:"/dashboard",replace:!0})}function $y(){const e=i.useMemo(()=>({sendCommand:Ur,sendData:Ma,sendPtyInput:by}),[]);return s.jsx(Ad,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Yd,{client:Dy,children:s.jsx(Ey,{children:s.jsx(wy,{children:s.jsx(Jd,{value:e,children:s.jsx(My,{children:s.jsxs(Id,{children:[s.jsx(Xt,{path:"/dashboard",element:s.jsx(ng,{})}),s.jsx(Xt,{path:"/machine",element:s.jsx($i,{})}),s.jsx(Xt,{path:"/machines/:id",element:s.jsx(dy,{})}),s.jsx(Xt,{path:"/machines",element:s.jsx($i,{})}),s.jsx(Xt,{path:"/about",element:s.jsx(Ry,{})}),s.jsx(Xt,{path:"/settings",element:s.jsx(Py,{})}),s.jsx(Xt,{path:"*",element:s.jsx(ia,{to:"/dashboard",replace:!0})})]})})})})})})})}ap({connectionManager:Ot});Ld(document.getElementById("root")).render(s.jsx($y,{}));
|
|
94
|
+
`})]})}function go(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function uy(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),r=go();return r&&!t.searchParams.has("token")&&t.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function Dt(e,t){return await fetch(uy(e),{credentials:"same-origin",...t})}function Gl(){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 fy{constructor(){Ye(this,"adapters",new Map);Ye(this,"states",new Map);Ye(this,"runtimeListeners",new Map);Ye(this,"screenshotCallbacks",new Map);Ye(this,"statusCallbacks",new Set)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(t,r){this.adapters.set(t,r),this.states.set(t,r.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,r){this.states.set(t,r)}retryConnection(t){}get(t){const r=this.resolveDaemonId(t);return r?this.adapters.get(r):void 0}getState(t){const r=this.resolveDaemonId(t);return r&&this.states.get(r)||"disconnected"}sendData(t,r){return!1}sendPtyInput(t,r,n){return!1}onScreenshot(t,r){return this.screenshotCallbacks.set(t,r),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,r){this.screenshotCallbacks.forEach(n=>n(t,r))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,r){this.statusCallbacks.forEach(n=>n(t,r))}emitRuntimeSnapshot(t,r,n=0,a=!1,o,c){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:o,rows:c})}emitSessionOutput(t,r,n){!t||typeof r!="string"||!r||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(t,r){const n=this.runtimeListeners.get(t)||new Set;return n.add(r),this.runtimeListeners.set(t,n),()=>{const a=this.runtimeListeners.get(t);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,r,n){if(!r)return{success:!1,error:"sessionId is required"};const a=new URL(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`,window.location.origin);typeof(n==null?void 0:n.sinceSeq)=="number"&&a.searchParams.set("sinceSeq",String(n.sinceSeq));const o=await Dt(`${a.pathname}${a.search}`);if(!o.ok){let l=`Runtime snapshot unavailable (${o.status})`;try{const d=await o.json();d!=null&&d.error&&(l=d.error)}catch{}return{success:!1,error:l}}const c=await o.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof c.seq=="number"?c.seq:0,text:typeof c.text=="string"?c.text:"",truncated:!!c.truncated,cols:typeof c.cols=="number"?c.cols:void 0,rows:typeof c.rows=="number"?c.rows:void 0,force:!!(n!=null&&n.force)}),{success:!0}}emitRuntimeEvent(t,r){var n;(n=this.runtimeListeners.get(t))==null||n.forEach(a=>a(r))}}const Ot=new fy;function my(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=go();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Pr=my(),Di=3e3,py=3e4;let Rt=null,hy=0;const an=new Map;let Qt=null,tr=null;function Ei(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Vs(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function xy(e){return e==="connected"?"connected":e}async function Ur(e,t,r){const n=Qc(e,r||{}),a=Rt;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++hy}_${Date.now()}`;return new Promise((c,l)=>{const d=setTimeout(()=>{an.delete(o),l(new Error(`WS command timeout: ${t}`))},3e4);an.set(o,{resolve:f=>{clearTimeout(d),c(f)},reject:f=>{clearTimeout(d),l(f)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Ma(e,t){const r=Rt;if(!r||r.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(t)),!0}catch{return!1}}function by(e,t,r){const n=Rt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=Qc(e,{sessionId:t,targetSessionId:t,data:r});try{return n.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}class gy{constructor(t){Ye(this,"daemonId");Ye(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN}get connectionState(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return Ur(this.daemonId,t,r)}async sendInput(t,r){return Ur(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Qt&&(clearInterval(Qt),Qt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Ur(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(o=>o.blob());Ot.emitScreenshot(this.daemonId,a)}}catch{}};r(),Qt=setInterval(r,2e3)}stopScreenshots(t){Qt&&(clearInterval(Qt),Qt=null)}}let At=null;function yy(e){return(!At||At.daemonId!==e)&&(At=new gy(e)),At}function vy({children:e}){const t=i.useRef(rr()),r=rr();t.current=r;const{setUserName:n}=ds(),a=i.useRef(n);a.current=n;const o=i.useRef(null),c=i.useRef(null),[,l]=i.useState("disconnected"),d=i.useCallback((h,j)=>{l(h),tr==null||tr(h,j)},[]),f=i.useRef(null),u=i.useRef(),p=i.useRef(Di),m=i.useRef(!0),y=i.useRef(!1),N=i.useRef("initial_connect");return i.useEffect(()=>{m.current=!0,y.current=!1;function h(){var b,v;if(!m.current||((b=f.current)==null?void 0:b.readyState)===WebSocket.OPEN||((v=f.current)==null?void 0:v.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Pr}...`),Vs("connect_attempt",{url:Pr,reason:N.current,delayMs:p.current});let x;try{x=new WebSocket(Pr)}catch(A){console.error("[Standalone WS] Failed to create WebSocket:",A),j();return}f.current=x,x.onopen=()=>{if(!m.current){x.close();return}d("connected"),p.current=Di,Vs("open",{url:Pr,reason:N.current}),Ht.resubscribeAll({sendData:Ma}),console.log("[Standalone WS] Connected")},Rt=x,x.onmessage=A=>{var g,M;try{const T=JSON.parse(A.data);if((T.type==="command_result"||T.type==="error")&&T.requestId){const k=an.get(T.requestId);k&&(an.delete(T.requestId),T.type==="error"?k.reject(new Error(((g=T.data)==null?void 0:g.message)||"Command failed")):k.resolve(T.data));return}if(T.type==="session_output"){const k=T.sessionId||T.cliId||T.cliType;k&&Ot.emitSessionOutput(k,typeof T.data=="string"?T.data:"",typeof T.seq=="number"?T.seq:void 0);return}if(T.type==="runtime_snapshot"){Ot.emitRuntimeSnapshot(T.sessionId,typeof T.text=="string"?T.text:"",typeof T.seq=="number"?T.seq:0,!!T.truncated,typeof T.cols=="number"?T.cols:void 0,typeof T.rows=="number"?T.rows:void 0);return}if(T.type==="topic_update"){const k=T.update;k&&Ht.publish(k);return}if(T.type==="status"||T.type==="initial_state"){const k=T.data;if(!k)return;const{injectEntries:w,markLoaded:K,getIdes:R}=t.current,S=k.instanceId||"standalone",O=R().find(C=>C.id===S),H=yy(S);Ot.register(S,H),Ot.setState(S,"connected"),d("connected",S),Ot.emitStatus(S,k);const P=Zr(k,{daemonId:S,existingDaemon:O,existingEntries:R()});Ei("ws_status",{type:T.type,daemonId:S,sessions:(k.sessions||[]).map(C=>({id:C.id,parentId:C.parentId,providerType:C.providerType,kind:C.kind,transport:C.transport,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,title:C.title})),recentLaunches:(k.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),Ei("entries",{daemonId:S,entries:P.filter(C=>C.type!=="adhdev-daemon").map(C=>({id:C.id,type:C.type,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,sessionId:C.sessionId}))}),P.length>0&&w(P,{authoritativeDaemonIds:[S]}),K(),c.current!==S&&((M=o.current)==null||M.call(o),c.current=S,o.current=Ht.subscribe({sendData:Ma},S,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${S}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const I=t.current.getIdes(),W=I.find($=>$.id===S),E=Zr(C.status,{daemonId:S,existingDaemon:W,existingEntries:I,timestamp:C.timestamp});E.length>0&&t.current.injectEntries(E,{authoritativeDaemonIds:[S]}),C.userName&&a.current&&a.current(C.userName)}))}}catch(T){console.error("[Standalone WS] Parse error:",T)}},x.onclose=A=>{m.current&&(At==null||At.stopScreenshots(),At&&Ot.setState(At.daemonId,"disconnected"),d("disconnected"),f.current=null,N.current=`close:${A.code}${A.wasClean?":clean":":unclean"}`,Vs("close",{code:A.code,reason:A.reason||"",wasClean:A.wasClean}),j())},x.onerror=A=>{y.current||!m.current||(N.current="error",Vs("error",{message:A instanceof Event?"event":String(A),readyState:x.readyState}),console.warn("[Standalone WS] Error, will reconnect:",A))}}function j(){if(!m.current)return;clearTimeout(u.current);const x=p.current;console.log(`[Standalone WS] Reconnecting in ${x}ms...`),Vs("schedule_reconnect",{reason:N.current,delayMs:x}),u.current=setTimeout(()=>{p.current=Math.min(p.current*1.5,py),h()},x)}return h(),()=>{var x;m.current=!1,y.current=!0,(x=o.current)==null||x.call(o),o.current=null,c.current=null,clearTimeout(u.current),f.current&&(f.current.onerror=null,f.current.onclose=null,f.current.close(),f.current=null,Rt=null),At&&(At.stopScreenshots(),Ot.unregister(At.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function wy({children:e}){const[t,r]=i.useState("disconnected"),[n,a]=i.useState(null);i.useEffect(()=>(tr=(c,l)=>{r(c),l&&a(l)},()=>{tr=null}),[]);const o=i.useMemo(()=>{const c=t==="connected",l=xy(t),d={};return n&&(d[n]=l),d.standalone=l,{wsStatus:t,isConnected:c,connectionStates:d}},[t,n]);return s.jsx(Vd,{connectionOverrides:o,children:s.jsx(vy,{children:e})})}const ql="adhdev_standalone_font_preferences",ls={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},vn=[{id:"default",label:"Default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS font-family stack"}],cr=[{id:"default",label:"Default mono",family:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',description:"Current monospace stack"},{id:"jetbrains-mono",label:"JetBrains Mono",family:'"JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Readable coding font with strong punctuation"},{id:"fira-code",label:"Fira Code",family:'"Fira Code", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Popular ligature-friendly code font"},{id:"cascadia-code",label:"Cascadia Code",family:'"Cascadia Code", "Cascadia Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Windows-friendly modern coding font"},{id:"berkeley-mono",label:"Berkeley Mono",family:'"Berkeley Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace',description:"Editorial-feeling mono stack if installed"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS monospace stack"}],jy=new Set(vn.map(e=>e.id)),ky=new Set(cr.map(e=>e.id));function $t(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:zr("chat",t.chat),code:zr("code",t.code),terminal:zr("terminal",t.terminal)}}function zr(e,t){const r=ls[e],n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof n.preset=="string"?n.preset.trim():"",o=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?jy:ky).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function Vr(e,t){var a;const r=zr(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?vn:cr;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function Sy(e){const t=$t(e),r=Vr("chat",t.chat),n=Vr("code",t.code),a=Vr("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function es(e,t=document.documentElement){const r=$t(e),n=Sy(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function Aa(e){const t=$t(e);try{localStorage.setItem(ql,JSON.stringify(t))}catch{}return t}function Ny(){try{const e=localStorage.getItem(ql);if(e)return $t(JSON.parse(e))}catch{}return ls}function Cy(){return es(Ny())}function Gs(e,t){var n;const r=e==="chat"?vn:cr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const Ty=[{id:"dashboard",path:"/dashboard",icon:s.jsx(Gi,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(us,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:s.jsx(on,{}),label:"Settings"}];function My({children:e}){const t=Ps(),r=La(),n=i.useMemo(()=>Ty.map(o=>({...o,active:r.pathname.startsWith(o.path),onSelect:()=>t(o.path)})),[r.pathname,t]),a=i.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Docs"}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(Yi,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Xi,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(Vp,{brand:({collapsed:o})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!o&&s.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:a,footerInfo:({collapsed:o})=>o?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.61"]}),footerActions:({collapsed:o,toggleCollapsed:c})=>s.jsxs("div",{className:`nav-item cursor-pointer ${o?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:o?"Expand sidebar":"Collapse sidebar",children:[s.jsx("span",{className:"nav-icon text-base",children:o?"›":"‹"}),!o&&s.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const Ay=[{icon:s.jsx(us,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Ut,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Ji,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(Tt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(ar,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Yi,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Iy=[{icon:s.jsx(iu,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Gi,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(cn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(tu,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(qi,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(ru,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Ly=[{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 Ry(){return s.jsxs(sl,{icon:s.jsx(Xi,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","0.9.61"]}),children:[s.jsx(Nt,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:"Keep the same dashboard experience, with the runtime fully on-device."}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:"Standalone keeps the browser, daemon, screenshots, and control path on your own machine. It is the same core product shape as cloud, just without the remote networking and team layers."})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"Docs ↗"}),s.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"GitHub ↗"}),s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:"Try Cloud ↗"})]})]})}),s.jsx(Nt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:Ay.map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(Nt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:Zc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:tl.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:el.map(e=>`${e.icon} ${e.name}`)}].map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(t=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:t},t))})]},e.label))})}),s.jsx(Nt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:Iy.map(e=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(Nt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),s.jsx("tbody",{children:Ly.map((e,t)=>s.jsxs("tr",{className:t%2===0?"bg-bg-glass":"bg-transparent",children:[s.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e.feature}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:e.selfhost?s.jsx("span",{className:"text-emerald-500",children:"✓"}):s.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:s.jsx("span",{className:"text-emerald-500",children:"✓"})})]},e.feature))})]})})}),s.jsx(nl,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:"Cloud is optional, not required",description:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",action:s.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(bu,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function ra(e,t,r){return{...e,[t]:r}}function na({surface:e,title:t,description:r,value:n,options:a,onChange:o}){return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("select",{className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",value:n.preset,onChange:c=>{const l=c.target.value;o(l==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:l})},children:a.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),n.preset==="custom"&&s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:n.customFamily||"",onChange:c=>o({preset:"custom",customFamily:c.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",s.jsx("span",{className:"font-mono break-all",children:Vr(e,n)})]})]})]})}function _y({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:o,onSave:c,onResetToSaved:l,onResetToDefaults:d}){const f=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&s.jsx("div",{className:"rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300",children:n}),a&&s.jsx("div",{className:"rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-300",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(na,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:vn,onChange:u=>o(ra(e,"chat",u))}),s.jsx(na,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:cr,onChange:u=>o(ra(e,"code",u))}),s.jsx(na,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:cr,onChange:u=>o(ra(e,"terminal",u))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",Gs("chat",e.chat.preset)," · Code: ",Gs("code",e.code.preset)," · Terminal: ",Gs("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Gs("chat",ls.chat.preset)," / ",Gs("code",ls.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:c,disabled:r||!f,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),s.jsx("button",{type:"button",onClick:l,disabled:r||!f,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert to saved"}),s.jsx("button",{type:"button",onClick:d,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function Py(){const{ides:e}=ds(),t=e.find(X=>X.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=mt(),{userName:a}=ds(),[o,c]=i.useState(a||""),[l,d]=i.useState(null),[f,u]=i.useState(null),[p,m]=i.useState(ls),[y,N]=i.useState(!1),[h,j]=i.useState(""),[x,b]=i.useState(""),[v,A]=i.useState("127.0.0.1"),[g,M]=i.useState(""),[T,k]=i.useState(""),[w,K]=i.useState(""),[R,S]=i.useState(""),[O,H]=i.useState(""),[P,C]=i.useState(!1),I=async()=>{const ae=await(await Dt("/auth/session")).json();d(ae)},W=async()=>{const ae=await(await Dt("/api/v1/standalone/preferences")).json();u(ae),A(ae.standaloneBindHost);const ge=$t(ae.standaloneFontPreferences);m(ge),es(ge),Aa(ge)};i.useEffect(()=>{a!==void 0&&c(a)},[a]),i.useEffect(()=>{Promise.all([I(),W()]).catch(X=>{S(X instanceof Error?X.message:String(X))})},[]),i.useEffect(()=>{es(p)},[p]);const E=X=>{const ae=X.target.value.trim();t!=null&&t.id&&ae!==a&&n(t.id,"set_user_name",{userName:ae}).catch(console.error)},[$,z]=i.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),J=X=>{z(X);try{localStorage.setItem("adhdev_sound",X?"1":"0")}catch{}},he=async()=>{j(""),b(""),N(!0);try{const X=$t(p),ae=await Dt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:X})}),ge=await ae.json();if(!ae.ok)throw new Error((ge==null?void 0:ge.error)||"Failed to save standalone font preferences");const ee=$t(ge.standaloneFontPreferences);u(ge),m(ee),es(ee),Aa(ee),b("Standalone chat fonts saved for this self-hosted dashboard.")}catch(X){j(X instanceof Error?X.message:String(X))}finally{N(!1)}},ce=()=>{const X=$t(f==null?void 0:f.standaloneFontPreferences);j(""),b(""),m(X),es(X)},te=()=>{j(""),b(""),m(ls),es(ls)},ye=async()=>{S(""),H(""),C(!0);try{const X=await Dt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:v})}),ae=await X.json();if(!X.ok)throw new Error((ae==null?void 0:ae.error)||"Failed to save standalone network preference");u(ae),A(ae.standaloneBindHost),H(ae.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(X){S(X instanceof Error?X.message:String(X))}finally{C(!1)}},fe=async()=>{if(S(""),H(""),T.trim().length<4){S("Password must be at least 4 characters.");return}if(T!==w){S("New password and confirmation do not match.");return}C(!0);try{const X=await Dt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:g,newPassword:T})}),ae=await X.json();if(!X.ok)throw new Error((ae==null?void 0:ae.error)||"Failed to save password");d(ae),await W(),M(""),k(""),K(""),H(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Gl()}catch(X){S(X instanceof Error?X.message:String(X))}finally{C(!1)}},be=async()=>{S(""),H(""),C(!0);try{const X=await Dt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:g,clear:!0})}),ae=await X.json();if(!X.ok)throw new Error((ae==null?void 0:ae.error)||"Failed to clear password");d(ae),await W(),M(""),k(""),K(""),H("Standalone password disabled.")}catch(X){S(X instanceof Error?X.message:String(X))}finally{C(!1)}};return s.jsxs(sl,{icon:s.jsx(on,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(Cr,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint."}),(l==null?void 0:l.publicHostWarning)&&s.jsx(Cr,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),s.jsx(Nt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:"Version"}),s.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.61"]}),s.jsx("span",{className:"text-text-muted",children:"Status"}),s.jsx("span",{className:t?"text-green-400":"text-yellow-400",children:t?"● Running":"○ Not connected"}),s.jsx("span",{className:"text-text-muted",children:"Current bind"}),s.jsx("span",{className:"font-mono text-xs",children:(f==null?void 0:f.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Default bind"}),s.jsx("span",{className:"font-mono text-xs",children:(f==null?void 0:f.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Auth"}),s.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),s.jsx(Nt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:v==="127.0.0.1",onChange:()=>A("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 127.0.0.1. Best when only this machine should open the dashboard."})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:v==="0.0.0.0",onChange:()=>A("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points."})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:()=>{ye()},disabled:P,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:P?"Saving…":"Save default network mode"}),s.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(f==null?void 0:f.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),s.jsx(Nt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:l!=null&&l.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),R&&s.jsx(Cr,{variant:"error",children:R}),O&&s.jsx(Cr,{variant:"success",children:O}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:g,onChange:X=>M(X.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"New password":"New standalone password",value:T,onChange:X=>k(X.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors md:col-span-2",placeholder:"Confirm new password",value:w,onChange:X=>K(X.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{fe()},disabled:P,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:P?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{be()},disabled:P,className:"rounded-lg border border-red-500/30 bg-red-500/10 text-red-300 px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Disable password"})]})]})}),s.jsx(Nt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(X=>s.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${X.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:X.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:X.type})]},X.type))})}),s.jsx(Nt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(th,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(Nt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),s.jsx(ah,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose a preset or create a custom surface, accent, and chat palette for the standalone UI."}),s.jsx(mh,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Fonts"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Standalone-only typography overrides for chat text, markdown code, and terminal output."}),s.jsx(_y,{value:p,savedValue:$t(f==null?void 0:f.standaloneFontPreferences),saving:y,error:h,notice:x,onChange:m,onSave:()=>{he()},onResetToSaved:ce,onResetToDefaults:te})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose whether phones open the dashboard as a chat app first or in the full workspace layout."}),s.jsx(xh,{})]})]})}),s.jsx(Nt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Qp,{}),s.jsx(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xu,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:$,onChange:J})]})}),s.jsx(Nt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(eu,{size:16,className:"text-text-secondary"})," Display Name"]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-1.5 text-sm w-48 text-right focus:border-accent focus:outline-none transition-colors",placeholder:"Anonymous",value:o,onChange:X=>c(X.target.value),onBlur:E,onKeyDown:X=>{X.key==="Enter"&&X.currentTarget.blur()}})]})})})]})}Up();uh();Cy();const Dy=Ui({baseUrl:"",getToken:go});function Ey({children:e}){const[t,r]=i.useState(null),[n,a]=i.useState(!0),[o,c]=i.useState(""),[l,d]=i.useState(""),[f,u]=i.useState(!1),p=async()=>{a(!0),d("");try{const N=await(await Dt("/auth/session")).json();r(N)}catch(y){d(y instanceof Error?y.message:String(y))}finally{a(!1)}};i.useEffect(()=>{p()},[]),i.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let y=!1;return(async()=>{try{const N=await Dt("/api/v1/standalone/preferences");if(!N.ok)return;const h=await N.json();if(y)return;const j=$t(h.standaloneFontPreferences);es(j),Aa(j)}catch{}})(),()=>{y=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const m=async y=>{y.preventDefault(),u(!0),d("");try{const N=await Dt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),h=await N.json();if(!N.ok)throw new Error((h==null?void 0:h.error)||"Login failed");r(h),c(""),Gl()}catch(N){d(N instanceof Error?N.message:String(N))}finally{u(!1)}};return n?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):t?!t.required||t.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:t.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),t.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:m,children:[s.jsx("input",{type:"password",value:o,onChange:y=>c(y.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),s.jsx("button",{type:"submit",disabled:f||!o,className:"rounded-lg bg-accent text-white px-3 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:f?"Signing in…":"Unlock dashboard"})]}):s.jsx("div",{className:"rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-300",children:"Password login is not enabled on this server."}),l&&s.jsx("div",{className:"rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:l})]})}):s.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",l||"unknown error"]})}function $i(){const{ides:e,initialLoaded:t}=ds();if(!t)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?s.jsx(ia,{to:`/machines/${r.id}`,replace:!0}):s.jsx(ia,{to:"/dashboard",replace:!0})}function $y(){const e=i.useMemo(()=>({sendCommand:Ur,sendData:Ma,sendPtyInput:by}),[]);return s.jsx(Ad,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Yd,{client:Dy,children:s.jsx(Ey,{children:s.jsx(wy,{children:s.jsx(Jd,{value:e,children:s.jsx(My,{children:s.jsxs(Id,{children:[s.jsx(Xt,{path:"/dashboard",element:s.jsx(ng,{})}),s.jsx(Xt,{path:"/machine",element:s.jsx($i,{})}),s.jsx(Xt,{path:"/machines/:id",element:s.jsx(dy,{})}),s.jsx(Xt,{path:"/machines",element:s.jsx($i,{})}),s.jsx(Xt,{path:"/about",element:s.jsx(Ry,{})}),s.jsx(Xt,{path:"/settings",element:s.jsx(Py,{})}),s.jsx(Xt,{path:"*",element:s.jsx(ia,{to:"/dashboard",replace:!0})})]})})})})})})})}ap({connectionManager:Ot});Ld(document.getElementById("root")).render(s.jsx($y,{}));
|