@adhdev/daemon-standalone 0.9.79 → 0.9.80

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.
@@ -39,7 +39,7 @@ ${JSON.stringify(t.bundle,null,2)}
39
39
  ${JSON.stringify(t,null,2)}
40
40
  \`\`\``}function zn(e,t){return`${e}:${t}`}function rp(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Qs(e,t){rp()&&console.debug(`[subscription-manager] ${e}`,t)}class np{constructor(){Je(this,"active",new Map);Je(this,"retryTimers",new Map)}subscribe(t,r,n,a,o){var u;const c=zn(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 h={daemonId:r,request:n,handlers:new Set([a])};this.active.set(c,h),Qs("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 m=()=>{var k;this.clearRetry(c);const h=this.active.get(c);if(!h||(h.handlers.delete(a),h.handlers.size>0))return;this.active.delete(c);const b={type:"unsubscribe",topic:n.topic,key:n.key};Qs("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(k=t.sendData)==null||k.call(t,r,b)};return m.initialSendAccepted=d,m}publish(t){const r=zn(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,Rs.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),Rs.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=zn(t,r),o=this.active.get(a);o&&(o.request={...o.request,params:{...o.request.params,...n}})}resubscribeAll(t){var r;Qs("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);Qs("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;Qs("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 Ut=new np;function ap(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,settings:n.settings});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 op(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 Vn(e,t){return t&&(t.startsWith(`${e}:`)?t:`${e}:${t}`)}function ip(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function cp(e){ip()&&console.debug("[dashboard-conversations] statusPayloadToEntries",e.map(t=>({id:t.id,daemonId:t.daemonId,sessionId:t.sessionId,instanceId:t.instanceId,providerSessionId:t.providerSessionId,transport:t.transport,type:t.type})))}function fn(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:o,timestamp:c}=t,l=c||e.timestamp||Date.now(),d=e.sessions||[],{topLevel:m,childrenByParent:u}=op(d),h=ap(o,n),b=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,k=m.filter(x=>x.kind==="workspace"&&x.transport==="cdp-page"),y=m.filter(x=>x.kind==="agent"&&x.transport==="pty"),p=m.filter(x=>x.kind==="agent"&&x.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...b&&{machine:b,platform:b.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:k.some(x=>!!x.cdpConnected)});for(const x of k){const g=h.get(x.id),f=nr(x,g),N=(u.get(x.id)||[]).map(S=>nr(S,h.get(S.id)));r.push({id:`${n}:ide:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(g==null?void 0:g.providerSessionId),parentSessionId:f.parentId,sessionKind:f.kind,transport:f.transport,sessionCapabilities:f.capabilities,type:f.providerType,status:f.cdpConnected?"online":"detected",daemonId:n,instanceId:Vn(n,x.id),workspace:f.workspace,terminals:0,childSessions:N,agents:N.map(S=>({id:S.id,name:S.providerName||S.providerType,type:S.providerType,status:S.status})),activeChat:f.activeChat,chats:[],cdpConnected:f.cdpConnected,...f.lastMessagePreview!==void 0&&{lastMessagePreview:f.lastMessagePreview},...f.lastMessageRole!==void 0&&{lastMessageRole:f.lastMessageRole},...f.lastMessageAt!==void 0&&{lastMessageAt:f.lastMessageAt},...f.lastMessageHash!==void 0&&{lastMessageHash:f.lastMessageHash},lastUpdated:f.lastUpdated,unread:f.unread,lastSeenAt:f.lastSeenAt,inboxBucket:f.inboxBucket,completionMarker:f.completionMarker,seenCompletionMarker:f.seenCompletionMarker,surfaceHidden:f.surfaceHidden,...f.controlValues!==void 0&&{controlValues:f.controlValues},...f.providerControls!==void 0&&{providerControls:f.providerControls},...f.summaryMetadata!==void 0&&{summaryMetadata:f.summaryMetadata},...f.settings!==void 0&&{settings:f.settings},...f.messageInput!==void 0&&{messageInput:f.messageInput},timestamp:l})}for(const x of y){const g=h.get(x.id),f=nr(x,g);r.push({id:`${n}:cli:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(g==null?void 0:g.providerSessionId),parentSessionId:f.parentId,sessionKind:f.kind,transport:f.transport,sessionCapabilities:f.capabilities,type:f.providerType,agentType:f.providerType,status:f.status||"running",daemonId:n,instanceId:Vn(n,x.id),cliName:f.providerName||f.providerType,mode:f.mode||(g==null?void 0:g.mode)||"terminal",workspace:f.workspace||"",activeChat:f.activeChat,...f.resume!==void 0&&{resume:f.resume},...f.runtimeKey!==void 0&&{runtimeKey:f.runtimeKey},...f.runtimeDisplayName!==void 0&&{runtimeDisplayName:f.runtimeDisplayName},...f.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:f.runtimeWorkspaceLabel},...f.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:f.runtimeWriteOwner},...f.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:f.runtimeAttachedClients},...f.lastMessagePreview!==void 0&&{lastMessagePreview:f.lastMessagePreview},...f.lastMessageRole!==void 0&&{lastMessageRole:f.lastMessageRole},...f.lastMessageAt!==void 0&&{lastMessageAt:f.lastMessageAt},...f.lastMessageHash!==void 0&&{lastMessageHash:f.lastMessageHash},lastUpdated:f.lastUpdated,unread:f.unread,lastSeenAt:f.lastSeenAt,inboxBucket:f.inboxBucket,completionMarker:f.completionMarker,seenCompletionMarker:f.seenCompletionMarker,surfaceHidden:f.surfaceHidden,...f.controlValues!==void 0&&{controlValues:f.controlValues},...f.providerControls!==void 0&&{providerControls:f.providerControls},...f.summaryMetadata!==void 0&&{summaryMetadata:f.summaryMetadata},...f.settings!==void 0&&{settings:f.settings},...f.messageInput!==void 0&&{messageInput:f.messageInput},timestamp:l,_isCli:!0})}for(const x of p){const g=h.get(x.id),f=nr(x,g);r.push({id:`${n}:acp:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(g==null?void 0:g.providerSessionId),parentSessionId:f.parentId,sessionKind:f.kind,transport:f.transport,sessionCapabilities:f.capabilities,type:f.providerType,agentType:f.providerType,status:f.status||"running",daemonId:n,instanceId:Vn(n,x.id),cliName:f.providerName||f.providerType,mode:"chat",workspace:f.workspace||"",activeChat:f.activeChat,...f.runtimeKey!==void 0&&{runtimeKey:f.runtimeKey},...f.runtimeDisplayName!==void 0&&{runtimeDisplayName:f.runtimeDisplayName},...f.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:f.runtimeWorkspaceLabel},...f.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:f.runtimeWriteOwner},...f.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:f.runtimeAttachedClients},...f.lastMessagePreview!==void 0&&{lastMessagePreview:f.lastMessagePreview},...f.lastMessageRole!==void 0&&{lastMessageRole:f.lastMessageRole},...f.lastMessageAt!==void 0&&{lastMessageAt:f.lastMessageAt},...f.lastMessageHash!==void 0&&{lastMessageHash:f.lastMessageHash},lastUpdated:f.lastUpdated,unread:f.unread,lastSeenAt:f.lastSeenAt,inboxBucket:f.inboxBucket,completionMarker:f.completionMarker,seenCompletionMarker:f.seenCompletionMarker,surfaceHidden:f.surfaceHidden,...f.controlValues!==void 0&&{controlValues:f.controlValues},...f.providerControls!==void 0&&{providerControls:f.providerControls},...f.summaryMetadata!==void 0&&{summaryMetadata:f.summaryMetadata},...f.settings!==void 0&&{settings:f.settings},...f.messageInput!==void 0&&{messageInput:f.messageInput},timestamp:l,_isAcp:!0})}return cp(r),r}const lp=15e3,dp=15e3,up=6e4,mp=1200,bi=12,fp=8e3,pp=4e3,Gn=new Map,qn=new Map,Dr=new Set,lr=new Map;function hp(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 gi(e,t){const r=lr.get(e);!r||r.size===0||(lr.delete(e),r.forEach(n=>n(t)))}function xp(e,t){return new Promise(r=>{const n=lr.get(e)||new Set;lr.set(e,n);const a=c=>{clearTimeout(o),n.delete(a),n.size===0&&lr.delete(e),r(c)},o=setTimeout(()=>a(!1),t);n.add(a)})}function jr(){const{sendCommand:e,sendData:t}=gt(),{injectEntries:r,getIdes:n}=hr();return i.useCallback(async(a,o)=>{if(!a)return;const c=(o==null?void 0:o.minFreshMs)??up,l=qn.get(a)||0;if(!(o!=null&&o.force)&&Dr.has(a)&&l>0||!(o!=null&&o.force)&&l>0&&Date.now()-l<c)return;const d=Gn.get(a);if(d)return d;const m=(async()=>{if(t&&!Dr.has(a)){const p=Ut.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},x=>{const g=n(),f=g.find(S=>S.id===a),N=fn(x.status,{daemonId:a,existingDaemon:f,existingEntries:g,timestamp:x.timestamp});N.length>0&&r(N),qn.set(a,Date.now()),gi(a,!0)});if(p.initialSendAccepted?Dr.add(a):Dr.delete(a),!(o!=null&&o.force)&&p.initialSendAccepted&&await xp(a,mp))return}const u=await e(a,"get_status_metadata"),h=hp(u);if(!h)return;const b=n(),k=b.find(p=>p.id===a),y=fn(h,{daemonId:a,existingDaemon:k,existingEntries:b,timestamp:h.timestamp||Date.now()});y.length>0&&r(y,{authoritativeDaemonIds:[a]}),qn.set(a,Date.now()),gi(a,!0)})().finally(()=>{Gn.delete(a)});return Gn.set(a,m),m},[n,r,e,t])}function bp(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const gp=60,yp=50;function ol(e={}){return e.isCliLike?yp:gp}function vp(e={}){return ol(e)}function St(e){return(typeof e=="string"?e.trim():"")||void 0}function Ht(e,t){const r=St(t);return r?`${e}:${r}`:void 0}function Xt(e,t,r){const n=Ht(t,r),a=St(r);n&&e.push(n),a&&e.push(a)}function Is(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function il(e){return St(e.providerSessionId)||St(e.sessionId)||St(e.tabKey)||St(e.routeId)}function bo(e){return Is([St(e.providerSessionId),St(e.sessionId)])}function Ls(e){const t=[];return Xt(t,"provider",e.providerSessionId),Xt(t,"session",e.sessionId),Xt(t,"tab",e.tabKey),Xt(t,"route",e.routeId),Is(t)}function wp(e){const t=[];return St(e.providerSessionId)?(Xt(t,"provider",e.providerSessionId),Is(t)):St(e.sessionId)?(Xt(t,"session",e.sessionId),Is(t)):St(e.tabKey)?(Xt(t,"tab",e.tabKey),Is(t)):St(e.routeId)?(Xt(t,"route",e.routeId),Is(t)):[]}function go(e){return Ht("provider",e.providerSessionId)||Ht("session",e.sessionId)||Ht("tab",e.tabKey)||Ht("route",e.routeId)||"unknown:"}function kr(e){return bo(e)[0]}function jp(e){const t=St(e.providerSessionId),r=St(e.sessionId),n=St(e.tabKey),a=St(e.routeId),o=[Ht("provider",t),Ht("session",r),Ht("tab",n),Ht("route",a)].filter(d=>typeof d=="string"),c=Ls({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),l=go({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:il({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:kr({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:o,lookupKeys:c}}function Ea(e,t){const r=jp(e);return wp(t).some(n=>r.lookupKeys.includes(n))}const Sr=60,kp=1e3,yo=12e4,Sp=new Set(["generating","waiting_approval","starting","streaming","working"]),yi=new Map;function cl(e,t){return`${e}::${t}`}function $a(e=Sr){return{liveMessages:[],hasLiveSnapshot:!1,cursor:Np([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function Np(e,t=Sr){return{tailLimit:t}}function vi(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("|")}class Cp{constructor(t){Je(this,"manager");Je(this,"sendData");Je(this,"daemonId");Je(this,"sessionId");Je(this,"historySessionId");Je(this,"subscriptionKey");Je(this,"fallbackRecentCount");Je(this,"snapshot");Je(this,"transportSubscription",null);Je(this,"listeners",new Set);Je(this,"retainCount",0);Je(this,"loadHistoryPromise",null);Je(this,"pendingDisconnectTimer",null);this.manager=t.manager||Ut,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount??0),this.snapshot=$a(Math.max(0,t.tailLimit??Sr))}updateOptions(t){if(t.manager&&(this.manager=t.manager),t.sendData&&(this.sendData=t.sendData),t.historySessionId&&(this.historySessionId=t.historySessionId),t.fallbackRecentCount!==void 0&&(this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount)),t.tailLimit!==void 0){const r=Math.max(0,t.tailLimit);r!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect()))}}getSnapshot(){return this.snapshot}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=this.snapshot.hasLiveSnapshot,a=n?this.snapshot.liveMessages.length:Math.max(this.snapshot.liveMessages.length,this.fallbackRecentCount),o=await t({offset:this.snapshot.historyOffset,excludeRecentCount:a}),c=Array.isArray(o.messages)?o.messages:[],l=!n&&c.length===0&&o.hasMore!==!0&&this.fallbackRecentCount>0;this.snapshot={...this.snapshot,historyMessages:[...c,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+c.length,hasMoreHistory:l?!0:o.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}:{},...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:kp}))}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=Array.isArray(t.messages)?t.messages:[],n={tailLimit:this.snapshot.cursor.tailLimit};vi(this.snapshot.liveMessages)===vi(r)&&this.snapshot.cursor.tailLimit===n.tailLimit||(this.snapshot={...this.snapshot,liveMessages:r,hasLiveSnapshot:!0,cursor:n},this.emit())}}function ll(e){const t=cl(e.daemonId,e.sessionId),r=yi.get(t);if(r)return r.updateOptions(e),r;const n=new Cp(e);return yi.set(t,n),n}function Ip(e,t){return{...e,loadHistoryPage:t}}function Tp(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function Mp(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(Sp.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??yo)),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 Ap(e=yo){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Lp(e,t={}){const r=new Set,n=[];for(const a of e){if(!Mp(a,t))continue;const o=wr(a),c=a.sessionId||"";if(!o||!c)continue;const l=cl(o,c);if(r.has(l))continue;r.add(l);const d=kr(a);n.push({daemonId:o,sessionId:c,historySessionId:d||c,subscriptionKey:`daemon:${o}:session:${c}`})}return n.sort(Tp),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Rp(e,t){const{sendData:r,sendCommand:n}=gt(),a=(t==null?void 0:t.enabled)!==!1,o=wr(e),c=e.sessionId||"",l=kr(e)||c,d=`daemon:${o}:session:${c}`,m=Math.max(0,(t==null?void 0:t.tailLimit)??Sr),u=i.useMemo(()=>!a||!o||!c?null:ll({daemonId:o,sessionId:c,historySessionId:l,subscriptionKey:d,sendData:r,tailLimit:m,fallbackRecentCount:e.messages.length}),[e.messages.length,o,a,l,r,c,d,m]),[h,b]=i.useState(()=>(u==null?void 0:u.getSnapshot())||$a(m));i.useEffect(()=>{if(!u){b($a(m));return}u.retain(),b(u.getSnapshot());const y=u.subscribe(p=>{b(p)});return()=>{y(),u.release()}},[u,m]);const k=i.useCallback(async()=>{!u||!o||!c||await u.loadHistoryPage(async({offset:y,excludeRecentCount:p})=>{const x=e.agentType,g=await n(o,"chat_history",{agentType:x,offset:y,limit:30,targetSessionId:c,historySessionId:l,excludeRecentCount:p}),f=g&&typeof g=="object"&&"result"in g?g.result||{}:g||{};return{messages:Array.isArray(f.messages)?f.messages:[],hasMore:f.hasMore===!0}})},[e.agentType,u,o,l,n,c]);return i.useMemo(()=>Ip(h,k),[k,h])}function Pp(e,t){const{sendData:r}=gt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??Sr),o=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??yo)),c=Ap(o),[l,d]=i.useState(0);i.useEffect(()=>{if(!n||e.length===0)return;const u=setInterval(()=>{d(h=>h+1)},c);return()=>{clearInterval(u)}},[e.length,n,c]);const m=i.useMemo(()=>Lp(e,{recentActivityMs:o}),[e,o,l]);i.useEffect(()=>{if(!n||!r||m.descriptors.length===0)return;const u=m.descriptors.map(h=>ll({...h,sendData:r,tailLimit:a}));return u.forEach(h=>{h.retain()}),()=>{u.forEach(h=>h.release())}},[m.signature,n,r,a])}function _p(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function wi(e){const t=String(e.role||"").toLowerCase();if(t!=="user"&&t!=="assistant")return!1;const r=String(e.kind||"standard").toLowerCase();return r===""||r==="standard"}function Dp(e,t){if(e.length===0)return[];if(t.some(wi))return[];const r=[],n=new Set;for(let a=e.length-1;a>=0&&r.length<2;a-=1){const o=e[a];if(!o||!wi(o))continue;const c=String(o.role||"").toLowerCase();n.has(c)||(n.add(c),r.unshift(o))}return r}function Ep(e){const{historyMessages:t,liveMessages:r,visibleLiveCount:n}=e,a=Math.max(0,r.length-n),o=a>0?r.slice(0,a):[],c=a>0?r.slice(-n):r,l=Dp(o,c),d=l.length>0?[...l,...c]:c;return t.length===0?d:[...t,...d]}function $p(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function Bp(e){return $p(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}function Kp(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function Op(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function Wp(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function dl(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function ul(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 Fp(e){return dl(e)?!1:e.inboxBucket==="task_complete"&&ul(e).length>0}function ji(e){return e.branch||"detached HEAD"}function Hp(e){if(e.error)return`${ji(e)} · Git error: ${e.error}`;const t=[ji(e)];return e.changedFiles>0?t.push(Kp(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 Up(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${Hp(t)}`}function zp(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function Vp(e,t={}){if(t.enabled===!1)return[];if(!Wp(e))return[];const r=dl(e)?"working":Fp(e)?"complete":null;if(!r)return[];const n=r==="complete"?ul(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${Op(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:Up(r,e.git),timestamp:zp(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 Gp=60;function Ba({activeConv:e,ideEntry:t,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:o,isFocusingAgent:c,actionLogs:l,userName:d,scrollToBottomRequestNonce:m,isInputActive:u=!0,isVisible:h=!0}){var Ne,me,pe,oe,fe,ie,D;const b=i.useRef(new Map),k=i.useRef(void 0),y=jr(),{sendCommand:p}=gt(),{isVisible:x}=lo();vr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const g=Ct.useMemo(()=>Fs(e),[e.status,e.connectionState]),f=i.useMemo(()=>Vf(e,t),[e,t]),N=i.useMemo(()=>{var z;return fo((z=f.targetEntry)==null?void 0:z.providerControls,{hostIdeType:e.hostIdeType,providerType:f.providerType})},[e.hostIdeType,f.providerType,(Ne=f.targetEntry)==null?void 0:Ne.providerControls]),S=ol({isCliLike:f.isCli||f.isAcp}),v=vp({isCliLike:f.isCli||f.isAcp}),M=Rp(e,{enabled:h&&!!e.sessionId,tailLimit:v}),[A,w]=i.useState(S),[j,K]=i.useState(()=>si()),P=e.tabKey,T=M.historyMessages,W=M.hasMoreHistory,H=M.historyError,R=_p(e,M),I=Rc(R).length;i.useEffect(()=>{w(S)},[S,P]);const C=Math.max(0,R.length-A),O=po(e),_=wr(e),E=Bp(e),U=ho(e),Q=a||U,xe=!!U,[de,Z]=i.useState(!1);i.useEffect(()=>{const z=f.targetEntry;_&&(!z||z.providerControls===void 0||z.controlValues===void 0)&&y(_,{minFreshMs:3e4}).catch(()=>{})},[_,f.isAcp,(me=f.targetEntry)==null?void 0:me.providerControls,(pe=f.targetEntry)==null?void 0:pe.controlValues,y]);const he=i.useCallback(async()=>{if(!de){if(R.length>A){w(z=>Math.min(R.length,z+Gp));return}Z(!0);try{await M.loadHistoryPage()}finally{Z(!1)}}},[M,de,R.length,A]),{allMessages:we,receivedAtMap:be}=i.useMemo(()=>{const z=Ep({historyMessages:T,liveMessages:R,visibleLiveCount:A}),ce=Vp(e),se=ce.length>0?[...z,...ce]:z,q={};return se.forEach((ke,ve)=>{const Le=`${e.tabKey}:${on(ke,ve)}`;let Ae=bp(ke)||b.current.get(Le)||0;Ae||(Ae=Date.now(),b.current.set(Le,Ae)),q[on(ke,ve)]=Ae}),{allMessages:se,receivedAtMap:q}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,C,T,R,A]),X=i.useMemo(()=>l.filter(z=>z.routeId===e.tabKey).sort((z,ce)=>z.timestamp-ce.timestamp),[l,e.tabKey]),ue=i.useCallback(async()=>{var ve,Le;if(!_)return;const z=sl({activeConv:e,visibleMessages:we,actionLogs:l,controls:(ve=f.targetEntry)==null?void 0:ve.providerControls,controlValues:(Le=f.targetEntry)==null?void 0:Le.controlValues,visibleBarControlCount:N.length,chatTailState:{liveMessages:M.liveMessages,hasLiveSnapshot:M.hasLiveSnapshot,hasMoreHistory:W,historyError:H,historyMessages:T},ui:{controlsVisible:x,visibleLiveCount:A,activityVisible:j,activityCount:I,hiddenLiveCount:C,isInputActive:u,isVisible:h}}),ce=await p(_,"get_chat_debug_bundle",{agentType:f.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:z}),se=mn(ce),q=al(se),ke=await nl(q);ke==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),nt.showToast(rl(se,{locatorCopyStatus:ke}),ke==="failed"?"warning":"success")},[e,l,I,we,x,M.hasLiveSnapshot,M.liveMessages,f.providerType,(oe=f.targetEntry)==null?void 0:oe.controlValues,(fe=f.targetEntry)==null?void 0:fe.providerControls,_,W,C,T,u,h,H,p,j,N.length,A]),ge=i.useCallback(()=>{K(z=>{const ce=!z;return hm(ce),ce})},[]);i.useEffect(()=>{const z=ce=>{ce.key===ao&&K(si())};return window.addEventListener("storage",z),()=>window.removeEventListener("storage",z)},[]);const te=i.useCallback(()=>{const z=sp(k.current);k.current=z.state,z.shouldCollect&&ue().catch(ce=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",ce),nt.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[ue]),le=i.useMemo(()=>{if(R.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((g.isGenerating||e.status==="streaming")&&Z(!1),e.status==="not_monitored"&&E)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(_s,{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(xs,{size:14})," Open ",O," 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"&&E)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(Tc,{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(xs,{size:14})," Open ",O," 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"&&!de)return!W&&T.length===0?s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"No messages yet"})]}):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,E,o,W,T.length,c,de,R.length,O,g.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[s.jsx("div",{className:"chat-activity-toggle-bar",children:s.jsxs("button",{type:"button",className:`chat-activity-toggle ${j?"chat-activity-toggle-active":""}`,onClick:ge,"aria-pressed":j,title:"Show tool, terminal, and runtime activity rows",children:[s.jsx("span",{className:"chat-activity-toggle-dot"}),"Activity",I>0&&s.jsx("span",{className:"chat-activity-toggle-count",children:I})]})}),s.jsx(Am,{messages:we,actionLogs:X,agentName:Ds(e)||O||"Agent",userName:d,isCliMode:f.isCli||f.isAcp,isWorking:g.isGenerating,contextKey:e.tabKey,receivedAtMap:be,lastMessageHash:e.lastMessageHash,showActivityMessages:j,onLoadMore:he,isLoadingMore:de,hasMoreHistory:W,hiddenLiveCount:C,loadError:H??void 0,emptyState:le,scrollToBottomRequestNonce:m,isVisible:h}),s.jsx(_f,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:f.providerType,displayLabel:f.displayLabel,controls:(ie=f.targetEntry)==null?void 0:ie.providerControls,controlValues:(D=f.targetEntry)==null?void 0:D.controlValues,isActive:u,isCliTerminal:f.isCliTerminal}),!f.isCliTerminal&&s.jsx(qc,{contextKey:e.tabKey,panelLabel:O,isSending:n,isBusy:xe,statusMessage:Q,onSend:r,isActive:u,showControlsToggle:N.length>0,onControlsToggle:te,messageInput:e.messageInput})]})}let ml=es;function fl(){return ml()}class qp{constructor(){Je(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 pl=new qp;class Yp{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 ut=new Yp;function Xp(e){e.dashboardWS&&(pl=e.dashboardWS),e.connectionManager&&(ut=e.connectionManager),e.useDaemonsHook&&(ml=e.useDaemonsHook)}const Jp=.5,Qp=1.25;function lt(e){return po(e)}function gs(e){return Zc(e).join(" · ")}function hl(e){const t=Qc(e);return t||(e.title?e.title:gs(e)||"No messages yet")}function xl(e,t){const{isReconnecting:r,isConnecting:n}=Fs(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function Zp(e,t){const r=["Chat",...Zc(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function cs(e){return xl(e)||gs(e)}function eh(e){return`${lt(e)} · ${hl(e)}`}function th(e){const t=un(e),r=t?it(t):Ds(e);return`${lt(e)} — ${r||"Agent"}`}function sh(e){return Ds(e)||"CLI"}function bl(e){return Jc(e)}function gl(e){return e?`Remote · ${lt(e)||e.workspaceName||"Session"}`:"Remote"}function rh({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:c=!0,isInputActive:l=!0}){var re;es();const{sendPtyInput:d}=gt(),[m,u]=i.useState(!1),h=i.useRef(!1);h.current=m;const[b,k]=i.useState("Runtime terminal unavailable"),[y,p]=i.useState(!1),[x,g]=i.useState(null),[f,N]=i.useState(!1),[S,v]=i.useState(!1),[M,A]=i.useState(1),[w,j]=i.useState(!1),[K,P]=i.useState({width:0,height:0}),[T,W]=i.useState({width:0,height:0}),[H,R]=i.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[I,C]=i.useState(null),O=i.useRef(null),_=i.useRef(null),E=i.useRef(!1),U=i.useRef(!1),Q=i.useRef(c),xe=i.useRef(0),de=i.useRef(!1),Z=i.useRef(""),he=i.useRef(null),we=i.useRef(!1),be=i.useRef(!1),X=i.useRef(null),ue=i.useRef(null),ge=i.useRef(null),te=32*1024,le=()=>{var $,Y,ee,ne;return((Y=($=O.current)==null?void 0:$.ownerDocument)==null?void 0:Y.defaultView)||((ne=(ee=_.current)==null?void 0:ee.ownerDocument)==null?void 0:ne.defaultView)||window},Ne=$=>{const Y=le();return{ownerWindow:Y,frameId:Y.requestAnimationFrame($)}},me=()=>{const $=X.current;if($){try{$.ownerWindow.cancelAnimationFrame($.frameId)}catch{}X.current=null}},pe=()=>{const $=ue.current;if($){try{$.ownerWindow.clearTimeout($.timeoutId)}catch{}ue.current=null}},oe=()=>{const $=ge.current;if($){try{$.ownerWindow.clearTimeout($.timeoutId)}catch{}ge.current=null}},fe=()=>{c&&X.current===null&&(X.current=Ne(()=>{tt()}))},ie=e.tabKey,D=e.sessionId||"",z=e.daemonId||((re=e.routeId)==null?void 0:re.split(":")[0])||e.routeId||"",ce=ho(e),se=m?o||ce:b,q=Jp,ke=Qp,ve=.05,Le=()=>{const $=T.width,Y=T.height;if(!Number.isFinite(K.width)||K.width<=0||!Number.isFinite(K.height)||K.height<=0||!Number.isFinite($)||$<=0||!Number.isFinite(Y)||Y<=0)return 1;const ee=K.width/$,ne=K.height/Y;return Number(Math.min(ke,Math.max(q,Math.min(ee,ne))).toFixed(2))},Ae=Le(),B=E.current&&M>Ae,Ie=Number.isFinite(T.width)&&T.width>0?Math.max(K.width,Math.round(T.width*M)):K.width,Pe=Number.isFinite(T.height)&&T.height>0?Math.max(K.height,Math.round(T.height*M)):K.height,Fe=()=>{Ne(()=>{const $=_.current;$&&($.scrollLeft=0,$.scrollTop=$.scrollHeight-$.clientHeight)})},He=()=>{var $,Y;xe.current=0,de.current=!1,Z.current="",he.current=null,we.current=!1,be.current=!1,E.current||(U.current=!1,A(1)),X.current!==null&&me(),u(!1),k("Runtime terminal unavailable"),oe(),pe(),g(null),C(null),j(!1),p(!1),N(!1),v(!1),(Y=($=r.current)==null?void 0:$.reset)==null||Y.call($)},qe=()=>{var $,Y;xe.current=0,de.current=!1,Z.current="",he.current=null,we.current=!1,be.current=!1,X.current!==null&&me(),u(!0),k(""),oe(),pe(),g(null),C(null),j(!1),p(!1),N(!1),v(!1),(Y=($=r.current)==null?void 0:$.reset)==null||Y.call($)},Ye=()=>{be.current&&(be.current=!1,Ne(()=>{var $,Y;(Y=($=r.current)==null?void 0:$.scrollToTop)==null||Y.call($)}))},tt=()=>{if(X.current=null,!c)return;const $=Z.current;if(!$)return;const Y=$.slice(0,te);Z.current=$.slice(Y.length);const ee=r.current;if(!ee){Z.current=Y+Z.current,fe();return}ee.write(Y,()=>{if(Z.current.length>0){fe();return}Ye()})},mt=$=>{$&&(Z.current+=$,fe())},ht=($,Y=0,ee,ne,Se={})=>{var Ee,Ce,$e,Be;const De=!!Se.force;!De&&Y>0&&xe.current>=Y||!De&&Y===0&&de.current||(xe.current=Y,Y>0&&N(!0),u(!0),k(""),typeof ee=="number"&&typeof ne=="number"&&ee>0&&ne>0&&((Ce=(Ee=r.current)==null?void 0:Ee.resize)==null||Ce.call(Ee,ee,ne)),Z.current="",(Be=($e=r.current)==null?void 0:$e.reset)==null||Be.call($e),$?mt($):Ye())};i.useEffect(()=>{He()},[D]),i.useEffect(()=>{var Y;if(!D)return;const $=((Y=ut.onRuntimeEvent)==null?void 0:Y.call(ut,D,ee=>{if(!(!ee||ee.sessionId!==D)){if(ee.type==="runtime_snapshot"){if(!c){he.current={text:ee.text||"",seq:ee.seq||0,cols:ee.cols,rows:ee.rows,force:!!ee.force};return}ht(ee.text||"",ee.seq||0,ee.cols,ee.rows,{force:!!ee.force});return}if(ee.type==="session_output"){de.current=!0,typeof ee.seq=="number"&&(xe.current=Math.max(xe.current,ee.seq),ee.seq>0&&N(!0)),h.current||u(!0),h.current||k(""),typeof ee.data=="string"&&mt(ee.data);return}if(ee.type==="session_cleared"){if(!c){we.current=!0,Z.current="",he.current=null;return}qe();return}if(ee.type==="session_io_error"){const ne=typeof ee.error=="string"&&ee.error?ee.error:typeof ee.reason=="string"&&ee.reason?ee.reason:"unknown error";u(!1),k(`Runtime input failed: ${ne}`);return}}},z))||(()=>{});return()=>{$()}},[z,D,r,c]);const bt=async($={})=>{var Y;if(!z||!D)return{success:!1,error:"daemonId and sessionId are required"};$.preserveStatus||k($.loadingMessage||"Loading runtime terminal...");try{const ee=await((Y=ut.requestRuntimeSnapshot)==null?void 0:Y.call(ut,z,D,{sinceSeq:$.sinceSeq,force:$.force}));return ee&&ee.success===!1?($.preserveStatus||(u(!1),k(`Runtime terminal unavailable: ${ee.error}`)),ee):ee||{success:!0}}catch(ee){const ne=(ee==null?void 0:ee.message)||String(ee);return $.preserveStatus||(u(!1),k(`Runtime terminal unavailable: ${ne}`)),{success:!1,error:ne}}},Te=async $=>{var De,Ee;const Y=((De=O.current)==null?void 0:De.ownerDocument)||document,ee=Y.defaultView||window,ne=(Ee=ee.navigator)==null?void 0:Ee.clipboard;if(ne!=null&&ne.writeText&&ee.isSecureContext)try{return await ne.writeText($),!0}catch{}let Se=null;try{return Se=Y.createElement("textarea"),Se.value=$,Se.setAttribute("readonly","true"),Se.style.position="fixed",Se.style.left="-9999px",Se.style.top="0",Y.body.appendChild(Se),Se.focus(),Se.select(),Y.execCommand("copy")}catch{return!1}finally{Se==null||Se.remove()}},Ue=$=>{pe(),C($);const Y=le();ue.current={ownerWindow:Y,timeoutId:Y.setTimeout(()=>{ue.current=null,C(ee=>ee===$?null:ee)},2200)}},Qe=$=>{oe(),g($);const Y=le();ge.current={ownerWindow:Y,timeoutId:Y.setTimeout(()=>{ge.current=null,g(ee=>ee===$?null:ee)},2200)}},ze=async()=>{var Se,De,Ee,Ce;const $=((De=(Se=r.current)==null?void 0:Se.getSelection)==null?void 0:De.call(Se))||"",Y=((Ce=(Ee=r.current)==null?void 0:Ee.getVisibleText)==null?void 0:Ce.call(Ee))||"",ee=$.trimEnd()||Y.trimEnd();if(!ee){Ue("Nothing to copy");return}if(!await Te(ee)){Ue("Copy failed");return}Ue($.trimEnd()?"Copied selection":"Copied visible terminal")},rt=$=>{if(!m||!c)return;((d==null?void 0:d(z,D,$))??!1)||Ue("Terminal input failed")},F=async()=>{if(y)return;p(!0),g("Loading older terminal output..."),be.current=!0;const $=await bt({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(p(!1),($==null?void 0:$.success)===!1){be.current=!1,g(`Older terminal output unavailable: ${$.error}`);return}v(!0),Qe("Older terminal output loaded"),Ne(()=>{var Y;(Y=r.current)==null||Y.bumpResize()})};i.useEffect(()=>{var Y,ee;if(!D)return;z&&((Y=ut.getState)==null?void 0:Y.call(ut,z))==="connected"&&bt();const $=(ee=ut.onStateChange)==null?void 0:ee.call(ut,(ne,Se)=>{ne!==z||Se!=="connected"||bt()});return()=>{$==null||$()}},[z,D,r]),i.useEffect(()=>{t&&He()},[t,ie,r]),i.useEffect(()=>{var ne,Se;const $=O.current,Y=(Se=(ne=$==null?void 0:$.ownerDocument)==null?void 0:ne.defaultView)==null?void 0:Se.ResizeObserver;if(!$||!Y)return;const ee=new Y(De=>{const Ee=De[0];if(!Ee)return;const{width:Ce,height:$e}=Ee.contentRect;P(Be=>{const Re=Math.round(Ce),Xe=Math.round($e);return Be.width===Re&&Be.height===Xe?Be:{width:Re,height:Xe}})});return ee.observe($),()=>ee.disconnect()},[]),i.useEffect(()=>{if(E.current)return;const $=Le();!Number.isFinite($)||$<=0||A(Y=>U.current?$<Y-ve?$:Y:(U.current=!0,$))},[T.height,T.width,K.height,K.width]),i.useEffect(()=>{B&&Fe()},[B,Pe,Ie]),i.useEffect(()=>{var ee;const $=Q.current;if(Q.current=c,!c)return;$||v(!1),we.current&&(we.current=!1,qe());const Y=he.current;Y&&(he.current=null,ht(Y.text,Y.seq,Y.cols,Y.rows,{force:!!Y.force})),z&&D&&((ee=ut.getState)==null?void 0:ee.call(ut,z))==="connected"&&bt(),Z.current&&X.current===null&&fe(),Ne(()=>{var ne;(ne=r.current)==null||ne.bumpResize()})},[z,c,D]),i.useEffect(()=>()=>{X.current!==null&&me(),pe(),oe()},[]),i.useEffect(()=>{const $=ne=>{var De;const Se=ne.detail;Se!=null&&Se.sessionId&&Se.sessionId!==D||m&&((De=r.current)==null||De.bumpResize())},Y=le(),ee=Y===window?[window]:[window,Y];for(const ne of ee)ne.addEventListener("adhdev:fit-cli-terminal",$);return()=>{for(const ne of ee)ne.removeEventListener("adhdev:fit-cli-terminal",$)}},[m,D,r]);const J=m&&f&&!S&&(H.atTop||!H.canScroll)||y||!!x;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:O,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[J&&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:!D||y,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:y?"Loading older...":"Load older terminal output"}),x&&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:x})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[I&&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:I}),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:()=>{ze()},disabled:!m,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:()=>j($=>!$),disabled:!m,"aria-label":"Open terminal control keys","aria-expanded":w,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),w&&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:()=>j(!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:()=>rt("\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:()=>rt(" "),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:()=>rt("\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:()=>rt("\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:()=>rt("\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:()=>rt("\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:()=>rt("\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:()=>rt(""),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:()=>rt(""),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:()=>rt(""),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:()=>{E.current=!0,A($=>{const Y=Math.max(Ae,Number(($-.1).toFixed(2)));return Y>Ae&&Fe(),Y})},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:()=>{E.current=!0,A($=>{const Y=Math.min(ke,Number(($+.1).toFixed(2)));return Y>Ae&&Fe(),Y})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:_,className:B?"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:Ie>0?`${Ie}px`:"100%",height:Pe>0?`${Pe}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:T.width>0?`${T.width}px`:"100%",height:T.height>0?`${T.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:M},children:s.jsx($c,{ref:r,readOnly:!m||!c,sizingMode:"measured",onViewportMetrics:W,onScrollMetrics:R,onInput:$=>{!m||(d==null||d(z,D,$))}})})})}),!m&&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:b})]}),s.jsx(qc,{contextKey:e.tabKey,panelLabel:lt(e),isSending:a,isBusy:!!ce,statusMessage:se,onSend:async $=>ce?!1:n($),isActive:l&&c,showControlsToggle:!1,animateVisibility:!1})]})}const nh=5e3,ah=12e3;function oh(e){return e==="disconnected"||e==="reconnecting"}function ih({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=nh,reconnectActionDelayMs:o=ah}){const c=oh(e),[l,d]=i.useState(()=>!c||a<=0),[m,u]=i.useState(()=>!c||o<=0),h=i.useRef(!1);i.useEffect(()=>{if(!c){d(!1);return}if(h.current=!1,a<=0){h.current=!0,d(!0);return}d(!1);const v=setTimeout(()=>{h.current=!0,d(!0)},a);return()=>clearTimeout(v)},[a,c]),i.useEffect(()=>{if(!c){u(!1);return}if(o<=0){u(!0);return}u(!1);const v=setTimeout(()=>{u(!0)},o);return()=>clearTimeout(v)},[o,c]);const b=c?l:e==="offline"||e==="auth_failed",k=!!(n&&e!=="auth_failed"&&(!c||m)),y=i.useMemo(()=>!t||e!=="connected"?!1:a<=0||h.current,[a,t,e]),p=e==="auth_failed"?"red":e==="offline"?"orange":"accent",x={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))"},g={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)"},f={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},N="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",S={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[b&&s.jsx("div",{className:N,style:S,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:x[p],border:g[p],color:f[p]},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.")]}),k&&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"})]})}),y&&s.jsx("div",{className:N,style:S,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 ch({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 vo({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(ro,{size:n}):s.jsx(zt,{size:n})})}const Bt="New session",yl="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 lh(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 dh(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 uh(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 $s({git:e,className:t="",compact:r=!1}){const n=lh(e),a=dh(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 ${uh(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 mh({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 ki({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Si({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:o}){const c=kn(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 fh({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:o,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:d,onHideConversation:m,hiddenConversations:u=[],onShowConversation:h,onShowAllHidden:b,onResetPanelsToMain:k,inboxOpen:y,onInboxOpenChange:p,hiddenOpen:x,onHiddenOpenChange:g,onOpenNewSession:f,onOpenDashboardGuide:N,guideNudgeVisible:S=!1,actionShortcuts:v,notifications:M,notificationUnreadCount:A,onOpenNotification:w,onMarkNotificationRead:j,onMarkNotificationUnread:K,onDeleteNotification:P,onOpenGitDialog:T}){const{ides:W,p2pStates:H={}}=es(),R=!!e&&st(e)&&!et(e),I=!!e&&et(e),C=l||(e?Yc(e)?"terminal":"chat":null),[O,_]=i.useState(!1),E=i.useRef(null),U=i.useRef(null),Q=W.filter(te=>te.type==="adhdev-daemon"),xe=mh({wsStatus:t,isConnected:r,daemonCount:Q.length,p2pStates:H}),de=xe.subtitle,Z=xe.tone==="connected"?"#22c55e":xe.tone==="limited"?"#eab308":"#ef4444",he=xe.tone==="connected"?"0 0 4px #22c55e80":xe.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",we=i.useMemo(()=>M.filter(te=>!te.readAt),[M]),be=i.useMemo(()=>M.filter(te=>!!te.readAt),[M]),X=i.useMemo(()=>we.slice(0,9),[we]),ue=A;i.useEffect(()=>{if(!y)return;const te=le=>{var Ne;(Ne=E.current)!=null&&Ne.contains(le.target)||p(!1)};return document.addEventListener("mousedown",te),()=>document.removeEventListener("mousedown",te)},[y,p]),i.useEffect(()=>{if(!x)return;const te=le=>{var Ne;(Ne=U.current)!=null&&Ne.contains(le.target)||g(!1)};return document.addEventListener("mousedown",te),()=>document.removeEventListener("mousedown",te)},[x,g]),i.useEffect(()=>{if(!x&&!y)return;const te=le=>{if(!le.altKey)return;const Ne=le.code.match(/^Digit([1-9])$/);if(!Ne)return;const me=Number(Ne[1])-1,pe=x?u[me]:void 0,oe=y?X[me]:void 0;if(!(!pe&&!oe)){if(le.preventDefault(),le.stopPropagation(),pe){h==null||h(pe),g(!1);return}oe&&(w(oe),p(!1))}};return window.addEventListener("keydown",te,!0),()=>window.removeEventListener("keydown",te,!0)},[u,x,y,X,g,p,w,h]);const ge=te=>{if(!te)return;const le=n.find(Ne=>Ne.tabKey===te);le&&(m==null||m(le))};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(zt,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?lt(e):"Dashboard"}),s.jsx("span",{title:xe.title,"aria-label":xe.title,className:"header-title-status-dot",style:{background:Z,boxShadow:he}}),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:Z,boxShadow:he}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[de&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",de]}),f&&s.jsx("button",{type:"button",onClick:f,className:"btn btn-secondary btn-sm ml-2",title:`${Bt}${v!=null&&v.openNewSession?` (${v.openNewSession})`:""}`,"aria-label":Bt,children:s.jsx(Ac,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[N&&s.jsxs("button",{type:"button",onClick:N,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:"?"}),S&&s.jsx("span",{children:"Guide"})]}),e&&(R||I||!et(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:gs(e)||lt(e),children:lt(e)}),T&&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:()=>T(e.daemonId,e.workspacePath),children:s.jsx($s,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx($s,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(R||I)&&c&&s.jsxs(s.Fragment,{children:[R&&d&&C&&s.jsx(vo,{mode:C,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>c(e),className:"btn btn-secondary btn-sm",title:I?"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(vt,{size:14})})]}),!et(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(to,{size:14})}),!R&&!et(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:E,children:[s.jsxs("div",{className:`dashboard-header-hidden${O?" is-drop-target":""}`,ref:U,onDragEnter:te=>{te.dataTransfer.types.includes("text/tab-key")&&(te.preventDefault(),_(!0))},onDragOver:te=>{te.dataTransfer.types.includes("text/tab-key")&&(te.preventDefault(),te.dataTransfer.dropEffect="move",_(!0))},onDragLeave:te=>{te.currentTarget.contains(te.relatedTarget)||_(!1)},onDrop:te=>{const le=te.dataTransfer.getData("text/tab-key");te.preventDefault(),_(!1),ge(le)},children:[s.jsxs("button",{type:"button",onClick:()=>g(!x),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${v!=null&&v.toggleHiddenTabs?` (${v.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[s.jsx(so,{size:16}),u.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:u.length})]}),x&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),s.jsx(ki,{value:v==null?void 0:v.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[k&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:k,children:"Reset panels"}),u.length>0&&b&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{b(),g(!1)},children:"Restore all"})]})]}),e&&m&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>m(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(ki,{value:v==null?void 0:v.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:lt(e)})]}),u.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(te=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{h==null||h(te),g(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:lt(te)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(te)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(te)+1]}):null,gs(te)]})]},te.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>p(!y),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(jn,{size:16}),ue>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:ue})]}),y&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[we.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),we.map(te=>s.jsx(Si,{notification:te,shortcutIndex:X.indexOf(te)>=0?X.indexOf(te)+1:void 0,onOpen:()=>w(te),onMarkRead:()=>j(te.id),onMarkUnread:()=>K(te.id),onDelete:()=>P(te.id)},te.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(te=>s.jsx(Si,{notification:te,onOpen:()=>w(te),onMarkRead:()=>j(te.id),onMarkUnread:()=>K(te.id),onDelete:()=>P(te.id)},te.id))]}),M.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function jt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function ph(e,t){return String(e||"")!==String(t||"")}function hh(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(`
41
41
  `).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!Fc(c.summaryMetadata).map(d=>d.toLowerCase()).join(`
42
- `).includes(a)))}function xh(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 vl(e,t={}){return xh(hh(e,t),t.sortMode||"recent")}function pn(e){return e?"Resume saved history":"Start fresh"}function wo(e){return e?"Resuming saved history…":"Starting fresh…"}function bh(){return"Start fresh"}function wl(e,t=!1){return e==="cli"?pn(t):e==="ide"?"Start IDE":"Start ACP session"}function jl(e,t=!1){return e==="cli"?wo(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function gh(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function yh(){return"Open saved history"}function vh(){return"Saved History"}function jo(){return"Use saved history when you want continuity in the same provider conversation."}function wh(){return"No saved history found yet."}function jh(){return"Refresh saved history"}function kh(){return"Refreshing saved history…"}function ls(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function ds(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 Bs(e){return e==="start-fresh"?"Start fresh":"Restart"}function Ks(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function ko(e){return`Resume saved history with ${e}?`}function So(){return"Review or change the target workspace before resuming saved history."}function Sh(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 No({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:m,onClose:u,onNewChat:h,onSwitchSession:b,onRefreshHistory:k,onResumeSavedSession:y}){var P;const p=t.find(T=>T.id===e.routeId),x=(p==null?void 0:p.chats)||[],g=(P=p==null?void 0:p.activeChat)==null?void 0:P.id,f=st(e)&&!et(e),[N,S]=i.useState(()=>jt()),v=l||N,M=String(d||"").trim(),A=T=>{if(m){m(T);return}S(T)},w=i.useMemo(()=>a.map(T=>{const W=String(T.workspace||"").trim();return T.canResume||W||!M?T:{...T,workspace:M,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[M,a]),j=i.useMemo(()=>vl(w,{textQuery:v.textQuery,workspaceQuery:v.workspaceQuery,modelQuery:v.modelQuery,resumableOnly:v.resumableOnly,sortMode:v.sortMode}),[w,v.modelQuery,v.resumableOnly,v.sortMode,v.textQuery,v.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:f?vh():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:th(e)}),f&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:jo()})]}),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(vt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!f&&s.jsx("button",{onClick:h,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"}),f?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:v.textQuery,onChange:T=>A({...v,textQuery:T.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:v.workspaceQuery,onChange:T=>A({...v,workspaceQuery:T.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:v.modelQuery,onChange:T=>A({...v,modelQuery:T.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:v.sortMode,onChange:T=>A({...v,sortMode:T.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:v.resumableOnly,onChange:T=>A({...v,resumableOnly:T.target.checked})}),"Resume-ready only"]})]}),j.map(T=>{const W=e.providerSessionId===T.providerSessionId,H=W||!T.canResume||!!c,R=T.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{H||!y||y(T)},disabled:H,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${W?"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 ${W?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:T.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:T.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Sh(T.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:T.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:[T.workspace||"Workspace unknown",R?" · selected workspace":"",bs(T.summaryMetadata)?` · ${bs(T.summaryMetadata)}`:"",T.messageCount>0?` · ${T.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:W?"ACTIVE":T.canResume?R?"RESUME IN SELECTED WORKSPACE":c===T.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},T.id)})]}):x.map(T=>s.jsxs("div",{onClick:()=>{b(e.routeId,T.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${g===T.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 ${g===T.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:T.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:[T.id.substring(0,12),"..."]}),g===T.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},T.id)),(f&&!o&&j.length===0||!f&&x.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(qu,{size:32})}),s.jsx("div",{className:"text-[13px]",children:f?a.length>0?"No saved history matches these filters.":wh():"No recent chat sessions found."})]}),f&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:kh()})})]}),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:k,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(yr,{size:13})," ",f?jh():"Refresh History"]})})})]})]});return typeof document>"u"?K:pr.createPortal(K,document.body)}const Ni={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 kl({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=Ni[n.type]||Ni.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(vt,{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 Nh=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Ch(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function Ih(e){return e.sessionId||e.instanceId||e.agentType}function Yn(e,t){return t||e||"unknown"}function Sl(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=It(r,{fallbackId:r.id}));return t}function Nl(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 Co(e,t={}){return Th(e,Nl(e,t))}function Th(e,t={}){var h,b,k,y,p;const r=[],n=t.machineName,a=t.connectionState,o=Ch(e),c=e.workspace||"",l=Jm(e.type,{agentName:e.cliName}),d=st(e)||et(e)?l:it(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(x=>{var g,f;return{sessionId:x.id,instanceId:x.id,providerSessionId:x.providerSessionId,transport:x.transport,sessionCapabilities:x.capabilities,agentType:x.providerType,agentName:x.providerName||it(x.providerType),status:x.status,title:x.title,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,messages:((g=x.activeChat)==null?void 0:g.messages)||[],activeModal:((f=x.activeChat)==null?void 0:f.activeModal)||void 0,unread:x.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,surfaceHidden:x.surfaceHidden,git:x.git,settings:x.settings,messageInput:x.messageInput}}):[],u=Nh(e);if(u){const x=e.sessionId||e.instanceId,g=(h=e.settings)==null?void 0:h.meshCoordinatorFor,f=(b=e.settings)==null?void 0:b.meshNodeFor,N=g?" (Coordinator)":f?" (Mesh Node)":"",S=l+N,v=(k=e.activeChat)==null?void 0:k.activeModal,M=v&&Array.isArray(v.buttons)&&v.buttons.length>0,A=Qm(e.activeChat,[{status:e.status,activeModal:(y=e.activeChat)==null?void 0:y.activeModal}],e.agents||[]),w=e.activeChat||{title:"",messages:[]};let j=w.title&&String(w.title).trim()?String(w.title).trim():"";const K=(p=e.activeChat)==null?void 0:p.id,P=e.chats;if(K&&Array.isArray(P)&&P.length>0){const R=P.find(I=>I.id===K||I.id&&String(I.id)===String(K));R!=null&&R.title&&String(R.title).trim()&&(j=String(R.title).trim())}const T=(st(e)||et(e),e.type),W=(st(e)||et(e))&&di(j,S,T)?"":j,H=w.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:st(e)?e.mode||"terminal":"chat",agentName:S,agentType:T,status:A,title:W,messages:H,resume:e.resume,hostIdeType:!st(e)&&!et(e)?e.type:void 0,workspaceName:o,workspacePath:c,git:e.git,displayPrimary:W||o||(st(e)?e.mode==="chat"?S:`Terminal${N}`:S),displaySecondary:st(e)&&o?S: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:M?v.buttons:void 0,modalMessage:M?v.message:void 0,streamSource:"native",tabKey:Yn(x,e.id),machineName:n,connectionState:a,settings:e.settings,messageInput:e.messageInput})}if(u&&(st(e)||et(e)))return r;for(const x of m){const g=x.activeModal&&Array.isArray(x.activeModal.buttons)&&x.activeModal.buttons.length>0,f=Zm(x),N=Ih(x),S=`${e.id}:${N}`,v=x.title&&String(x.title).trim()||"",M=di(v,x.agentName,x.agentType)?"":v,A=x.messages||[];(x.transport==="cdp-webview"||x.sessionId||x.providerSessionId||A.length>0||g||M||!["idle","panel_hidden","disconnected","not_monitored"].includes(f))&&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:f,title:M,messages:A,hostIdeType:e.type,workspaceName:o,workspacePath:c,git:x.git||e.git,displayPrimary:M||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:g?x.activeModal.buttons:void 0,modalMessage:g?x.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Yn(x.sessionId||x.instanceId,S),machineName:n,connectionState:a,settings:x.settings,messageInput:x.messageInput})}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:Yn(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),r}function Cl(e){return String(e.type||e.id||"").trim()}function Mh(e){var t;return e.category!=="cli"||!Cl(e)||e.enabled===!1?!1:e.machineStatus?e.machineStatus==="detected":((t=e.lastDetection)==null?void 0:t.ok)===!0||e.installed===!0||!!e.detectedPath}function Ah(e){var n;const t=new Set,r=[];for(const a of e||[]){if(!Mh(a))continue;const o=Cl(a);if(!o||t.has(o))continue;t.add(o);const c=String(a.displayName||a.name||o),l=a.detectedPath||((n=a.lastDetection)==null?void 0:n.path)||null;r.push({type:o,label:c,icon:a.icon,statusLabel:l?`Detected at ${l}`:"Detected on this machine",detectedPath:l})}return r}function Tn(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],r=new Set,n=[];for(const a of t){const o=typeof a=="string"?a.trim():"";!o||r.has(o)||(r.add(o),n.push(o))}return n}function Ka(e,t){const r=new Set(t.map(n=>n.type));return Tn(e).filter(n=>r.has(n))}function Lh(e){return e.map(t=>t.type)}function Rh(e,t){const r=Tn(e),n=t.trim();return!n||r.includes(n)?r:[...r,n]}function Ph(e,t){return Tn(e).filter(r=>r!==t)}function Ci(e,t,r){const n=Tn(e),a=n.indexOf(t);if(a<0)return n;const o=n.filter(l=>l!==t);if(r==="top")return[t,...o];if(r==="bottom")return[...o,t];const c=r==="up"?Math.max(0,a-1):Math.min(o.length,a+1);return o.splice(c,0,t),o}function Ii({direction:e}){return s.jsx("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e==="up"?s.jsx("polyline",{points:"18 15 12 9 6 15"}):s.jsx("polyline",{points:"6 9 12 15 18 9"})})}function Ti({value:e,availableProviders:t,onChange:r,disabled:n=!1,saveButton:a}){const[o,c]=i.useState(""),l=i.useMemo(()=>new Map(t.map(b=>[b.type,b])),[t]),d=i.useMemo(()=>Ka(e,t),[e,t]),m=e.length-d.length,u=t.filter(b=>!d.includes(b.type)),h=()=>{o&&(r(Rh(d,o)),c(""))};return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[s.jsx("div",{className:"flex flex-col gap-2",children:d.length===0?s.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:"No provider priority configured. Launches without an explicit CLI provider will fail closed."}):d.map((b,k)=>{const y=l.get(b);return s.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border-subtle bg-bg-primary px-3 py-2 sm:flex-row sm:items-center sm:justify-between",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",k+1]}),(y==null?void 0:y.icon)&&s.jsx("span",{"aria-hidden":"true",children:y.icon}),s.jsx("span",{className:"font-mono text-[12px] text-text-primary",children:b}),s.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:"available"})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:y?`${y.label} · ${y.statusLabel}`:b})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move up",disabled:n||k===0,title:"Move up",onClick:()=>r(Ci(d,b,"up")),children:s.jsx(Ii,{direction:"up"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move down",disabled:n||k===d.length-1,title:"Move down",onClick:()=>r(Ci(d,b,"down")),children:s.jsx(Ii,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:n,onClick:()=>r(Ph(d,b)),children:"Remove"})]})]},b)})}),s.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[s.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:"Add available CLI provider"}),s.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:o,onChange:b=>c(b.target.value),disabled:n||u.length===0,children:[s.jsx("option",{value:"",children:u.length?"Select provider…":"No additional detected CLI providers"}),u.map(b=>s.jsxs("option",{value:b.type,children:[b.label," (",b.type,")"]},b.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:n||!o,onClick:h,children:"Add provider"}),a]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Inventory is filtered to CLI providers detected on this machine. New launches use this order; existing running sessions may need restart.",m>0?` ${m} provider${m===1?"":"s"} from the saved policy are not detected now and will be omitted when saved.`:""]})]})}function _h(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 Il(e,t){const r=_h(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Tl=[{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:"🏄"}],Ml=[{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:"🧩"}],Al=[{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:"🟠"}],Dh=Tl,Eh=Ml,$h=Al;function Vt(...e){return iu(cu(e))}function Bh({icon:e,title:t,subtitle:r,badge:n,actions:a,className:o}){return s.jsxs("div",{className:Vt("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 dr({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(Bh,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Vt("mx-auto flex w-full flex-col gap-4",o,c),children:l})})]})}const Oa="adhdev:themechange";function Kh(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Ss(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Ns(e){return e==="system"?Kh():e}function Ll(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Yr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(Oa,{detail:{preference:e,theme:t}}))}function Oh(){const e=Ss(),t=Ns(e);Ll(t),Yr(e,t)}function Io(){const[e,t]=i.useState(Ss),[r,n]=i.useState(()=>Ns(Ss()));i.useEffect(()=>{Ll(r)},[r]),i.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=d=>{if(e==="system"){const m=d.matches?"light":"dark";n(m),Yr("system",m)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),i.useEffect(()=>{const c=d=>{const m=d.detail||{},u=m.preference,h=m.theme;t(u==="dark"||u==="light"||u==="system"?u:Ss()),n(h==="dark"||h==="light"?h:Ns(Ss()))},l=d=>{if(d.key!=="theme")return;const m=Ss(),u=Ns(m);t(m),n(u)};return window.addEventListener(Oa,c),window.addEventListener("storage",l),()=>{window.removeEventListener(Oa,c),window.removeEventListener("storage",l)}},[]);const a=i.useCallback(c=>{const l=Ns(c);t(c),n(l);try{localStorage.setItem("theme",c)}catch{}Yr(c,l)},[]),o=i.useCallback(()=>{t(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",d=Ns(l);n(d);try{localStorage.setItem("theme",l)}catch{}return Yr(l,d),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const Mi={dark:"Dark",light:"Light",system:"System"};function Wh({collapsed:e}){const{preference:t,cycleTheme:r}=Io(),n=t==="dark"?s.jsx(Xu,{size:16}):t==="light"?s.jsx(Yu,{size:16}):s.jsx(Ju,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Mi[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:Mi[t]})]})}function Xn(e,t){return e?typeof e=="function"?e(t):e:null}function Fh({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:o,footerActions:c,preMainContent:l,collapsedStorageKey:d="sidebar-collapsed"}){const[m,u]=i.useState(!1),[h,b]=i.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),k=()=>u(!0),y=()=>u(!1),p=()=>{b(N=>{const S=!N;try{localStorage.setItem(d,S?"1":"0")}catch{}return S})},x=i.useMemo(()=>({collapsed:h,mobileMenuOpen:m,openMobileMenu:k,closeMobileMenu:y,toggleCollapsed:p}),[h,m]),g=N=>`nav-item${N.active?" active":""} cursor-pointer ${h?"justify-center py-2.5 px-0":""}${N.className?` ${N.className}`:""}`,f=N=>s.jsxs("div",{className:g(N),id:`nav-${N.id}`,onClick:()=>{N.onSelect(),y()},title:h?N.title??(typeof N.label=="string"?N.label:void 0):N.title,children:[s.jsx("span",{className:"nav-icon",children:N.icon}),!h&&N.label]},N.id);return s.jsxs("div",{className:`app-layout${m?" mobile-menu-open":""}${h?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:k,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),m&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:y,onKeyDown:N=>N.key==="Escape"&&y()}),s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${h?"justify-center gap-0":""}`,children:Xn(t,x)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:y,children:s.jsx(vt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(f)}),n.map(N=>s.jsxs("div",{className:N.className??"border-t border-border-subtle pt-2 mt-2",children:[!h&&N.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:N.title}):null,N.items.map(f)]},N.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(f),Xn(o,x),s.jsx(Wh,{collapsed:h}),Xn(c,x)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function yt({title:e,icon:t,description:r,accentColor:n,className:a,children:o}){return s.jsxs("div",{className:Vt("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 hn({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:Vt("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 Hh={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"},Uh={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Ts({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:Vt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Hh[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Uh[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:"✕"})]})}function Mt({label:e,hint:t,children:r,className:n}){return s.jsxs("div",{className:Vt("mb-5",n),children:[s.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),r,t&&s.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function Jn(e){const{className:t,...r}=e;return s.jsx("input",{...r,className:Vt("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none","focus:border-accent transition-colors",t)})}const zh={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"},Vh={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Gh({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:Vt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",zh[e],r),children:[s.jsx("span",{className:Vt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Vh[e])}),n]})}function as({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 qh({onPrefChange:e}){const[t,r]=df(),[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(as,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(jn,{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(as,{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:()=>{zc().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(as,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Qu,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:c=>o("completionAlert",c)}),s.jsx(as,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Zu,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:c=>o("approvalAlert",c)}),s.jsx(as,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(_s,{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 xn(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function Yh(e,t){const r=xn(e),n=xn(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 Rl(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function ur(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||Yh(r,t)>=0)return!1;const n=xn(r),a=xn(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Xh(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Qn(e,t){return e instanceof Error?e.message:t}function Jh({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(hn,{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(Zh,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function Ai({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 pr.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 Qh(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Dh,...Eh,...$h].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 Zh({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var H,R;const[o,c]=i.useState("idle"),[l,d]=i.useState(""),[m,u]=i.useState(null),[h,b]=i.useState("idle"),[k,y]=i.useState(""),p=e.version||null,x=((H=e.machine)==null?void 0:H.platform)||((R=e.system)==null?void 0:R.platform)||"",g=It(e,{fallbackId:e.id}),f=x==="win32"?"🪟":x==="darwin"?"🍎":"🐧",N=t.filter(I=>I.daemonId===e.id&&I.transport==="cdp-page"),S=t.filter(I=>I.daemonId===e.id&&I.transport==="pty"),v=t.filter(I=>I.daemonId===e.id&&I.transport==="acp"),M=e.p2p,A=async()=>{if(r){c("upgrading"),d("Starting upgrade...");try{const I=Xh(await r(e.id,"daemon_upgrade",{}));I.alreadyLatest?(c("done"),d(`Already on v${I.version||"latest"}.`)):I.upgraded||I.success?(c("done"),d(`Upgrade to v${I.version||"latest"} started. Daemon is restarting...`)):(c("error"),d(I.error||"Upgrade failed"))}catch(I){c("error"),d(Qn(I,"Connection lost during upgrade"))}}},w=async()=>{if(u(null),!!n){b("loading");try{await n(e.id),b("done"),y("Machine disconnected.")}catch(I){b("error"),y(Qn(I,"Failed to disconnect"))}}},j=async()=>{if(u(null),!!a){b("loading");try{await a(e.id),b("done"),y("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(I){b("error"),y(Qn(I,"Failed to revoke token"))}}},K="0.9.79",P=Rl(e,K),T=ur(e,K),W=N.length+S.length+v.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:f}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:g}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),p&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${P?"":"bg-bg-secondary"}`,style:P?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",p,!P&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&P&&s.jsx("button",{onClick:A,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":`${T?"↑ Update now":`↑ Update${` to v${K}`}`}`}),n&&s.jsx("button",{onClick:()=>u("disconnect"),disabled:h==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>u("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(Gh,{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&&W>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),W>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[N.map(I=>{const C=Qh(I.type),O=I.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:C.icon}),s.jsx("span",{children:C.name}),O!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${O?"bg-green-400":"animate-pulse"}`,style:O?void 0:{background:"var(--status-warning)"},title:O?"CDP connected":"CDP connecting..."})]},I.id)}),S.map(I=>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:I.cliName||"CLI"})]},I.id)),v.map(I=>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:I.cliName||"ACP"})]},I.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||k)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||h==="error"?"text-red-400":o==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:k||l})]}),m==="disconnect"&&s.jsx(Ai,{title:"🔌 Disconnect Machine",message:`Disconnect "${g}" from ADHDev?
42
+ `).includes(a)))}function xh(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 vl(e,t={}){return xh(hh(e,t),t.sortMode||"recent")}function pn(e){return e?"Resume saved history":"Start fresh"}function wo(e){return e?"Resuming saved history…":"Starting fresh…"}function bh(){return"Start fresh"}function wl(e,t=!1){return e==="cli"?pn(t):e==="ide"?"Start IDE":"Start ACP session"}function jl(e,t=!1){return e==="cli"?wo(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function gh(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function yh(){return"Open saved history"}function vh(){return"Saved History"}function jo(){return"Use saved history when you want continuity in the same provider conversation."}function wh(){return"No saved history found yet."}function jh(){return"Refresh saved history"}function kh(){return"Refreshing saved history…"}function ls(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function ds(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 Bs(e){return e==="start-fresh"?"Start fresh":"Restart"}function Ks(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function ko(e){return`Resume saved history with ${e}?`}function So(){return"Review or change the target workspace before resuming saved history."}function Sh(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 No({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:m,onClose:u,onNewChat:h,onSwitchSession:b,onRefreshHistory:k,onResumeSavedSession:y}){var P;const p=t.find(T=>T.id===e.routeId),x=(p==null?void 0:p.chats)||[],g=(P=p==null?void 0:p.activeChat)==null?void 0:P.id,f=st(e)&&!et(e),[N,S]=i.useState(()=>jt()),v=l||N,M=String(d||"").trim(),A=T=>{if(m){m(T);return}S(T)},w=i.useMemo(()=>a.map(T=>{const W=String(T.workspace||"").trim();return T.canResume||W||!M?T:{...T,workspace:M,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[M,a]),j=i.useMemo(()=>vl(w,{textQuery:v.textQuery,workspaceQuery:v.workspaceQuery,modelQuery:v.modelQuery,resumableOnly:v.resumableOnly,sortMode:v.sortMode}),[w,v.modelQuery,v.resumableOnly,v.sortMode,v.textQuery,v.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:f?vh():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:th(e)}),f&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:jo()})]}),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(vt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!f&&s.jsx("button",{onClick:h,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"}),f?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:v.textQuery,onChange:T=>A({...v,textQuery:T.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:v.workspaceQuery,onChange:T=>A({...v,workspaceQuery:T.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:v.modelQuery,onChange:T=>A({...v,modelQuery:T.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:v.sortMode,onChange:T=>A({...v,sortMode:T.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:v.resumableOnly,onChange:T=>A({...v,resumableOnly:T.target.checked})}),"Resume-ready only"]})]}),j.map(T=>{const W=e.providerSessionId===T.providerSessionId,H=W||!T.canResume||!!c,R=T.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{H||!y||y(T)},disabled:H,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${W?"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 ${W?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:T.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:T.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Sh(T.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:T.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:[T.workspace||"Workspace unknown",R?" · selected workspace":"",bs(T.summaryMetadata)?` · ${bs(T.summaryMetadata)}`:"",T.messageCount>0?` · ${T.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:W?"ACTIVE":T.canResume?R?"RESUME IN SELECTED WORKSPACE":c===T.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},T.id)})]}):x.map(T=>s.jsxs("div",{onClick:()=>{b(e.routeId,T.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${g===T.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 ${g===T.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:T.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:[T.id.substring(0,12),"..."]}),g===T.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},T.id)),(f&&!o&&j.length===0||!f&&x.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(qu,{size:32})}),s.jsx("div",{className:"text-[13px]",children:f?a.length>0?"No saved history matches these filters.":wh():"No recent chat sessions found."})]}),f&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:kh()})})]}),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:k,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(yr,{size:13})," ",f?jh():"Refresh History"]})})})]})]});return typeof document>"u"?K:pr.createPortal(K,document.body)}const Ni={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 kl({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=Ni[n.type]||Ni.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(vt,{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 Nh=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Ch(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function Ih(e){return e.sessionId||e.instanceId||e.agentType}function Yn(e,t){return t||e||"unknown"}function Sl(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=It(r,{fallbackId:r.id}));return t}function Nl(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 Co(e,t={}){return Th(e,Nl(e,t))}function Th(e,t={}){var h,b,k,y,p;const r=[],n=t.machineName,a=t.connectionState,o=Ch(e),c=e.workspace||"",l=Jm(e.type,{agentName:e.cliName}),d=st(e)||et(e)?l:it(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(x=>{var g,f;return{sessionId:x.id,instanceId:x.id,providerSessionId:x.providerSessionId,transport:x.transport,sessionCapabilities:x.capabilities,agentType:x.providerType,agentName:x.providerName||it(x.providerType),status:x.status,title:x.title,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,messages:((g=x.activeChat)==null?void 0:g.messages)||[],activeModal:((f=x.activeChat)==null?void 0:f.activeModal)||void 0,unread:x.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,surfaceHidden:x.surfaceHidden,git:x.git,settings:x.settings,messageInput:x.messageInput}}):[],u=Nh(e);if(u){const x=e.sessionId||e.instanceId,g=(h=e.settings)==null?void 0:h.meshCoordinatorFor,f=(b=e.settings)==null?void 0:b.meshNodeFor,N=g?" (Coordinator)":f?" (Mesh Node)":"",S=l+N,v=(k=e.activeChat)==null?void 0:k.activeModal,M=v&&Array.isArray(v.buttons)&&v.buttons.length>0,A=Qm(e.activeChat,[{status:e.status,activeModal:(y=e.activeChat)==null?void 0:y.activeModal}],e.agents||[]),w=e.activeChat||{title:"",messages:[]};let j=w.title&&String(w.title).trim()?String(w.title).trim():"";const K=(p=e.activeChat)==null?void 0:p.id,P=e.chats;if(K&&Array.isArray(P)&&P.length>0){const R=P.find(I=>I.id===K||I.id&&String(I.id)===String(K));R!=null&&R.title&&String(R.title).trim()&&(j=String(R.title).trim())}const T=(st(e)||et(e),e.type),W=(st(e)||et(e))&&di(j,S,T)?"":j,H=w.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:st(e)?e.mode||"terminal":"chat",agentName:S,agentType:T,status:A,title:W,messages:H,resume:e.resume,hostIdeType:!st(e)&&!et(e)?e.type:void 0,workspaceName:o,workspacePath:c,git:e.git,displayPrimary:W||o||(st(e)?e.mode==="chat"?S:`Terminal${N}`:S),displaySecondary:st(e)&&o?S: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:M?v.buttons:void 0,modalMessage:M?v.message:void 0,streamSource:"native",tabKey:Yn(x,e.id),machineName:n,connectionState:a,settings:e.settings,messageInput:e.messageInput})}if(u&&(st(e)||et(e)))return r;for(const x of m){const g=x.activeModal&&Array.isArray(x.activeModal.buttons)&&x.activeModal.buttons.length>0,f=Zm(x),N=Ih(x),S=`${e.id}:${N}`,v=x.title&&String(x.title).trim()||"",M=di(v,x.agentName,x.agentType)?"":v,A=x.messages||[];(x.transport==="cdp-webview"||x.sessionId||x.providerSessionId||A.length>0||g||M||!["idle","panel_hidden","disconnected","not_monitored"].includes(f))&&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:f,title:M,messages:A,hostIdeType:e.type,workspaceName:o,workspacePath:c,git:x.git||e.git,displayPrimary:M||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:g?x.activeModal.buttons:void 0,modalMessage:g?x.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Yn(x.sessionId||x.instanceId,S),machineName:n,connectionState:a,settings:x.settings,messageInput:x.messageInput})}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:Yn(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),r}function Cl(e){return String(e.type||e.id||"").trim()}function Mh(e){var t;return e.category!=="cli"||!Cl(e)||e.enabled===!1?!1:e.machineStatus?e.machineStatus==="detected":((t=e.lastDetection)==null?void 0:t.ok)===!0||e.installed===!0||!!e.detectedPath}function Ah(e){var n;const t=new Set,r=[];for(const a of e||[]){if(!Mh(a))continue;const o=Cl(a);if(!o||t.has(o))continue;t.add(o);const c=String(a.displayName||a.name||o),l=a.detectedPath||((n=a.lastDetection)==null?void 0:n.path)||null;r.push({type:o,label:c,icon:a.icon,statusLabel:l?`Detected at ${l}`:"Detected on this machine",detectedPath:l})}return r}function Tn(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],r=new Set,n=[];for(const a of t){const o=typeof a=="string"?a.trim():"";!o||r.has(o)||(r.add(o),n.push(o))}return n}function Ka(e,t){const r=new Set(t.map(n=>n.type));return Tn(e).filter(n=>r.has(n))}function Lh(e){return e.map(t=>t.type)}function Rh(e,t){const r=Tn(e),n=t.trim();return!n||r.includes(n)?r:[...r,n]}function Ph(e,t){return Tn(e).filter(r=>r!==t)}function Ci(e,t,r){const n=Tn(e),a=n.indexOf(t);if(a<0)return n;const o=n.filter(l=>l!==t);if(r==="top")return[t,...o];if(r==="bottom")return[...o,t];const c=r==="up"?Math.max(0,a-1):Math.min(o.length,a+1);return o.splice(c,0,t),o}function Ii({direction:e}){return s.jsx("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e==="up"?s.jsx("polyline",{points:"18 15 12 9 6 15"}):s.jsx("polyline",{points:"6 9 12 15 18 9"})})}function Ti({value:e,availableProviders:t,onChange:r,disabled:n=!1,saveButton:a}){const[o,c]=i.useState(""),l=i.useMemo(()=>new Map(t.map(b=>[b.type,b])),[t]),d=i.useMemo(()=>Ka(e,t),[e,t]),m=e.length-d.length,u=t.filter(b=>!d.includes(b.type)),h=()=>{o&&(r(Rh(d,o)),c(""))};return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[s.jsx("div",{className:"flex flex-col gap-2",children:d.length===0?s.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:"No provider priority configured. Launches without an explicit CLI provider will fail closed."}):d.map((b,k)=>{const y=l.get(b);return s.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border-subtle bg-bg-primary px-3 py-2 sm:flex-row sm:items-center sm:justify-between",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",k+1]}),(y==null?void 0:y.icon)&&s.jsx("span",{"aria-hidden":"true",children:y.icon}),s.jsx("span",{className:"font-mono text-[12px] text-text-primary",children:b}),s.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:"available"})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:y?`${y.label} · ${y.statusLabel}`:b})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move up",disabled:n||k===0,title:"Move up",onClick:()=>r(Ci(d,b,"up")),children:s.jsx(Ii,{direction:"up"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move down",disabled:n||k===d.length-1,title:"Move down",onClick:()=>r(Ci(d,b,"down")),children:s.jsx(Ii,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:n,onClick:()=>r(Ph(d,b)),children:"Remove"})]})]},b)})}),s.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[s.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:"Add available CLI provider"}),s.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:o,onChange:b=>c(b.target.value),disabled:n||u.length===0,children:[s.jsx("option",{value:"",children:u.length?"Select provider…":"No additional detected CLI providers"}),u.map(b=>s.jsxs("option",{value:b.type,children:[b.label," (",b.type,")"]},b.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:n||!o,onClick:h,children:"Add provider"}),a]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Inventory is filtered to CLI providers detected on this machine. New launches use this order; existing running sessions may need restart.",m>0?` ${m} provider${m===1?"":"s"} from the saved policy are not detected now and will be omitted when saved.`:""]})]})}function _h(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 Il(e,t){const r=_h(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Tl=[{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:"🏄"}],Ml=[{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:"🧩"}],Al=[{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:"🟠"}],Dh=Tl,Eh=Ml,$h=Al;function Vt(...e){return iu(cu(e))}function Bh({icon:e,title:t,subtitle:r,badge:n,actions:a,className:o}){return s.jsxs("div",{className:Vt("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 dr({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(Bh,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Vt("mx-auto flex w-full flex-col gap-4",o,c),children:l})})]})}const Oa="adhdev:themechange";function Kh(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Ss(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Ns(e){return e==="system"?Kh():e}function Ll(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Yr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(Oa,{detail:{preference:e,theme:t}}))}function Oh(){const e=Ss(),t=Ns(e);Ll(t),Yr(e,t)}function Io(){const[e,t]=i.useState(Ss),[r,n]=i.useState(()=>Ns(Ss()));i.useEffect(()=>{Ll(r)},[r]),i.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=d=>{if(e==="system"){const m=d.matches?"light":"dark";n(m),Yr("system",m)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),i.useEffect(()=>{const c=d=>{const m=d.detail||{},u=m.preference,h=m.theme;t(u==="dark"||u==="light"||u==="system"?u:Ss()),n(h==="dark"||h==="light"?h:Ns(Ss()))},l=d=>{if(d.key!=="theme")return;const m=Ss(),u=Ns(m);t(m),n(u)};return window.addEventListener(Oa,c),window.addEventListener("storage",l),()=>{window.removeEventListener(Oa,c),window.removeEventListener("storage",l)}},[]);const a=i.useCallback(c=>{const l=Ns(c);t(c),n(l);try{localStorage.setItem("theme",c)}catch{}Yr(c,l)},[]),o=i.useCallback(()=>{t(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",d=Ns(l);n(d);try{localStorage.setItem("theme",l)}catch{}return Yr(l,d),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const Mi={dark:"Dark",light:"Light",system:"System"};function Wh({collapsed:e}){const{preference:t,cycleTheme:r}=Io(),n=t==="dark"?s.jsx(Xu,{size:16}):t==="light"?s.jsx(Yu,{size:16}):s.jsx(Ju,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Mi[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:Mi[t]})]})}function Xn(e,t){return e?typeof e=="function"?e(t):e:null}function Fh({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:o,footerActions:c,preMainContent:l,collapsedStorageKey:d="sidebar-collapsed"}){const[m,u]=i.useState(!1),[h,b]=i.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),k=()=>u(!0),y=()=>u(!1),p=()=>{b(N=>{const S=!N;try{localStorage.setItem(d,S?"1":"0")}catch{}return S})},x=i.useMemo(()=>({collapsed:h,mobileMenuOpen:m,openMobileMenu:k,closeMobileMenu:y,toggleCollapsed:p}),[h,m]),g=N=>`nav-item${N.active?" active":""} cursor-pointer ${h?"justify-center py-2.5 px-0":""}${N.className?` ${N.className}`:""}`,f=N=>s.jsxs("div",{className:g(N),id:`nav-${N.id}`,onClick:()=>{N.onSelect(),y()},title:h?N.title??(typeof N.label=="string"?N.label:void 0):N.title,children:[s.jsx("span",{className:"nav-icon",children:N.icon}),!h&&N.label]},N.id);return s.jsxs("div",{className:`app-layout${m?" mobile-menu-open":""}${h?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:k,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),m&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:y,onKeyDown:N=>N.key==="Escape"&&y()}),s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${h?"justify-center gap-0":""}`,children:Xn(t,x)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:y,children:s.jsx(vt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(f)}),n.map(N=>s.jsxs("div",{className:N.className??"border-t border-border-subtle pt-2 mt-2",children:[!h&&N.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:N.title}):null,N.items.map(f)]},N.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(f),Xn(o,x),s.jsx(Wh,{collapsed:h}),Xn(c,x)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function yt({title:e,icon:t,description:r,accentColor:n,className:a,children:o}){return s.jsxs("div",{className:Vt("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 hn({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:Vt("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 Hh={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"},Uh={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Ts({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:Vt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Hh[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Uh[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:"✕"})]})}function Mt({label:e,hint:t,children:r,className:n}){return s.jsxs("div",{className:Vt("mb-5",n),children:[s.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),r,t&&s.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function Jn(e){const{className:t,...r}=e;return s.jsx("input",{...r,className:Vt("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none","focus:border-accent transition-colors",t)})}const zh={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"},Vh={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Gh({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:Vt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",zh[e],r),children:[s.jsx("span",{className:Vt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Vh[e])}),n]})}function as({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 qh({onPrefChange:e}){const[t,r]=df(),[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(as,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(jn,{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(as,{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:()=>{zc().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(as,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Qu,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:c=>o("completionAlert",c)}),s.jsx(as,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Zu,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:c=>o("approvalAlert",c)}),s.jsx(as,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(_s,{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 xn(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function Yh(e,t){const r=xn(e),n=xn(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 Rl(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function ur(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||Yh(r,t)>=0)return!1;const n=xn(r),a=xn(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Xh(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Qn(e,t){return e instanceof Error?e.message:t}function Jh({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(hn,{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(Zh,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function Ai({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 pr.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 Qh(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Dh,...Eh,...$h].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 Zh({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var H,R;const[o,c]=i.useState("idle"),[l,d]=i.useState(""),[m,u]=i.useState(null),[h,b]=i.useState("idle"),[k,y]=i.useState(""),p=e.version||null,x=((H=e.machine)==null?void 0:H.platform)||((R=e.system)==null?void 0:R.platform)||"",g=It(e,{fallbackId:e.id}),f=x==="win32"?"🪟":x==="darwin"?"🍎":"🐧",N=t.filter(I=>I.daemonId===e.id&&I.transport==="cdp-page"),S=t.filter(I=>I.daemonId===e.id&&I.transport==="pty"),v=t.filter(I=>I.daemonId===e.id&&I.transport==="acp"),M=e.p2p,A=async()=>{if(r){c("upgrading"),d("Starting upgrade...");try{const I=Xh(await r(e.id,"daemon_upgrade",{}));I.alreadyLatest?(c("done"),d(`Already on v${I.version||"latest"}.`)):I.upgraded||I.success?(c("done"),d(`Upgrade to v${I.version||"latest"} started. Daemon is restarting...`)):(c("error"),d(I.error||"Upgrade failed"))}catch(I){c("error"),d(Qn(I,"Connection lost during upgrade"))}}},w=async()=>{if(u(null),!!n){b("loading");try{await n(e.id),b("done"),y("Machine disconnected.")}catch(I){b("error"),y(Qn(I,"Failed to disconnect"))}}},j=async()=>{if(u(null),!!a){b("loading");try{await a(e.id),b("done"),y("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(I){b("error"),y(Qn(I,"Failed to revoke token"))}}},K="0.9.80",P=Rl(e,K),T=ur(e,K),W=N.length+S.length+v.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:f}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:g}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),p&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${P?"":"bg-bg-secondary"}`,style:P?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",p,!P&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&P&&s.jsx("button",{onClick:A,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":`${T?"↑ Update now":`↑ Update${` to v${K}`}`}`}),n&&s.jsx("button",{onClick:()=>u("disconnect"),disabled:h==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>u("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(Gh,{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&&W>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),W>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[N.map(I=>{const C=Qh(I.type),O=I.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:C.icon}),s.jsx("span",{children:C.name}),O!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${O?"bg-green-400":"animate-pulse"}`,style:O?void 0:{background:"var(--status-warning)"},title:O?"CDP connected":"CDP connecting..."})]},I.id)}),S.map(I=>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:I.cliName||"CLI"})]},I.id)),v.map(I=>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:I.cliName||"ACP"})]},I.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||k)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||h==="error"?"text-red-400":o==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:k||l})]}),m==="disconnect"&&s.jsx(Ai,{title:"🔌 Disconnect Machine",message:`Disconnect "${g}" from ADHDev?
43
43
 
44
44
  This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
45
45
 
@@ -50,7 +50,7 @@ This will:
50
50
  • Delete the machine registration
51
51
  • Require restarting ADHDev on that machine
52
52
 
53
- Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:j,onCancel:()=>u(null)})]})}const ex=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function tx(){const{preference:e,setPreference:t}=Io();return s.jsx("div",{className:"flex gap-2",children:ex.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 sx(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 rx(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Zn(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Li(e){const{r:t,g:r,b:n}=rx(e);return .2126*Zn(t)+.7152*Zn(r)+.0722*Zn(n)}function Ri(e,t){const r=Li(e),n=Li(t),a=Math.max(r,n),o=Math.min(r,n);return(a+.05)/(o+.05)}function Pl(e){const t=sx(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return Ri(t,r)>=Ri(t,n)?r:n}const Wa={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},Fa={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},nx=[{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"}}}],_l="adhdev-chat-theme",Dl="adhdev-chat-theme-custom";function Xr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(_l)||"ember"}catch{return"ember"}}function Dt(e){try{const t=localStorage.getItem(Dl);if(t){const r=JSON.parse(t);return{...e==="dark"?Wa:Fa,...r[e]}}}catch{}return e==="dark"?Wa:Fa}function Er(e,t){try{localStorage.setItem(Dl,JSON.stringify({dark:e,light:t}))}catch{}}function At(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 bn(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 ax={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function mr(e,t){var a;const r=(a=ax[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",bn(r,24)),n.style.setProperty("--accent-on-primary",Pl(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${bn(r,18)})`),n.style.setProperty("--border-accent",At(r,.35)),n.style.setProperty("--nav-active-bg",At(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${At(r,.06)}`)}function us(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",At(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",At(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",At(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",At(e.borderSubtle,.5)),t.style.setProperty("--border-default",At(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",bn(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Pl(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${bn(e.accentColor,40)})`),t.style.setProperty("--border-accent",At(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",At(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${At(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 ${At(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 To(){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 ox(e){try{localStorage.setItem(_l,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ms()?"dark":"light";us(Dt(t))}else To(),mr(e,ms()?"dark":"light")}function ix(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Xr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ms()?"dark":"light";us(Dt(t))}else To(),mr(e,ms()?"dark":"light")}function ms(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function kt({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 Zs({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 cx({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=i.useState(()=>Dt(r));i.useEffect(()=>{a(Dt(r))},[r]);const o=i.useCallback((c,l)=>{a(d=>{const m={...d,[c]:l},h=Dt(r==="dark"?"light":"dark");return r==="dark"?Er(m,h):Er(h,m),us(m),t(m),m})},[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(Zs,{title:"App Background",children:[s.jsx(kt,{label:"Background",value:n.bgPrimary,onChange:c=>o("bgPrimary",c)}),s.jsx(kt,{label:"Surface",value:n.bgSecondary,onChange:c=>o("bgSecondary",c)}),s.jsx(kt,{label:"Card",value:n.surfacePrimary,onChange:c=>o("surfacePrimary",c)})]}),s.jsxs(Zs,{title:"App Text",children:[s.jsx(kt,{label:"Primary",value:n.textPrimary,onChange:c=>o("textPrimary",c)}),s.jsx(kt,{label:"Secondary",value:n.textSecondary,onChange:c=>o("textSecondary",c)}),s.jsx(kt,{label:"Muted",value:n.textMuted,onChange:c=>o("textMuted",c)})]}),s.jsxs(Zs,{title:"Borders & Accent",children:[s.jsx(kt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>o("borderSubtle",c)}),s.jsx(kt,{label:"Border default",value:n.borderDefault,onChange:c=>o("borderDefault",c)}),s.jsx(kt,{label:"Accent",value:n.accentColor,onChange:c=>o("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Zs,{title:"Chat Bubbles",children:[s.jsx(kt,{label:"User bubble",value:n.userBubble,onChange:c=>o("userBubble",c)}),s.jsx(kt,{label:"User text",value:n.userText,onChange:c=>o("userText",c)}),s.jsx(kt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>o("assistantBubble",c)}),s.jsx(kt,{label:"Agent text",value:n.assistantText,onChange:c=>o("assistantText",c)})]}),s.jsxs(Zs,{title:"Chat Layout",children:[s.jsx(kt,{label:"Chat BG",value:n.containerBg,onChange:c=>o("containerBg",c)}),s.jsx(kt,{label:"Send button",value:n.sendButton,onChange:c=>o("sendButton",c)}),s.jsx(kt,{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?Wa:Fa,d=Dt(e?"light":"dark");e?Er(c,d):Er(d,c),a(c),us(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 lx(){const[e,t]=i.useState(Xr),[r,n]=i.useState(!0),[a,o]=i.useState(()=>Dt("dark"));i.useEffect(()=>{n(ms());const d=new MutationObserver(()=>{const h=ms();n(h);const b=Xr();b==="custom"?us(Dt(h?"dark":"light")):mr(b,h?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const h=ms();n(h);const b=Xr();b==="custom"?us(Dt(h?"dark":"light")):mr(b,h?"dark":"light")};return m.addEventListener("change",u),()=>{d.disconnect(),m.removeEventListener("change",u)}},[]),i.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?us(Dt(r?"dark":"light")):(To(),mr(e,r?"dark":"light"))},[e,r]),i.useEffect(()=>{o(Dt(r?"dark":"light"))},[r]);const c=d=>{t(d),ox(d)},l=[...nx,{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 m=e===d.id,u=r?d.preview.dark:d.preview.light,h=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:m?"var(--bg-glass-hover)":"var(--bg-glass)",border:m?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:m?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:h},children:"Fix the bug please"}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"On it! ✨"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[m&&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(cx,{dark:r,onColorsChange:d=>o(d)})]})}const Mo="adhdev_mobileDashboardMode_v1",Ha="adhdev:mobile-dashboard-mode-change";function Ao(){try{return localStorage.getItem(Mo)==="workspace"?"workspace":"chat"}catch{return"chat"}}function dx(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??Ao())},r=a=>{const o=a.detail;t(o)},n=a=>{a.key&&a.key!==Mo||t()};return window.addEventListener(Ha,r),window.addEventListener("storage",n),()=>{window.removeEventListener(Ha,r),window.removeEventListener("storage",n)}}function ux(e){try{localStorage.setItem(Mo,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ha,{detail:e}))}function mx(){const[e,t]=i.useState(!0);return i.useEffect(()=>{t(Ao()==="chat")},[]),s.jsx(as,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(zt,{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),ux(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const ea=new Map,Pi=new Map;function fx(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 px(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 El(){const{sendCommand:e}=gt(),{injectEntries:t,getIdes:r}=hr();return i.useCallback(async(n,a)=>{if(!n)return;const o=(a==null?void 0:a.minFreshMs)??dp,c=Pi.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<o)return;const l=ea.get(n);if(l)return l;const d=(async()=>{const m=await e(n,"get_machine_runtime_stats"),u=fx(m);if(!u)return;const h=r().find(k=>k.id===n),b=px(h,n,u.machine,u.timestamp||Date.now());t([b]),Pi.set(n,Date.now())})().finally(()=>{ea.delete(n)});return ea.set(n,d),d},[r,t,e])}function hx(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 xx(e,t){const{sendData:r}=gt(),{injectEntries:n,getIdes:a}=hr(),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=>Ut.subscribe({sendData:r},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const h=a().find(k=>k.id===d),b=hx(h,d,u);n([b])}));return()=>{l.forEach(d=>d())}},[o,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function bx(e,t){const{sendData:r}=gt(),[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=Ut.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}:{}}},m=>{l&&(clearTimeout(l),l=null),a(m.diagnostics),c(!1)});return d.initialSendAccepted?l=setTimeout(()=>{c(!1)},pp):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 gx(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function $l(e){const{sendData:t}=gt(),[r,n]=i.useState({});return i.useEffect(()=>{const a=gx(e);if(!a||!e.sessionId||!t){n({});return}const o=Ut.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}),Rs.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 Bl="adhdev_hiddenTabs",Kl="adhdev_autoHiddenMeshTabs";function yx(){try{const e=localStorage.getItem(Bl);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ss(e){try{localStorage.setItem(Bl,JSON.stringify([...e]))}catch{}}function vx(){try{const e=localStorage.getItem(Kl);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function _i(e){try{localStorage.setItem(Kl,JSON.stringify([...e]))}catch{}}function or(e){return go(e)}function Mn(e,t){return Ls(t).some(r=>e.has(r))}function wx(e){var t,r,n;return((t=e.settings)==null?void 0:t.launchedByCoordinator)===!0&&typeof((r=e.settings)==null?void 0:r.meshNodeFor)=="string"&&e.settings.meshNodeFor.trim().length>0&&((n=e.settings)==null?void 0:n.spawnedSessionVisibility)==="hidden"}function jx(e,t,r=new Set){return e.filter(n=>{if(!wx(n))return!1;const a=or(n);return r.has(a)?!1:!Mn(t,n)})}function kx(){const[e,t]=i.useState(yx),[r,n]=i.useState(vx),a=i.useCallback(b=>{const k=or(b);t(y=>{const p=new Set(y);return p.has(k)?p.delete(k):p.add(k),ss(p),p})},[]),o=i.useCallback(b=>{const k=or(b);t(y=>{if(y.has(k))return y;const p=new Set(y);return p.add(k),ss(p),p})},[]),c=i.useCallback(b=>{const k=or(b);t(y=>{if(y.has(k))return y;const p=new Set(y);return p.add(k),ss(p),p}),n(y=>{if(y.has(k))return y;const p=new Set(y);return p.add(k),_i(p),p})},[]),l=i.useCallback(b=>{const k=or(b);t(y=>{if(!y.has(k))return y;const p=new Set(y);return p.delete(k),ss(p),p}),n(y=>{if(y.has(k))return y;const p=new Set(y);return p.add(k),_i(p),p})},[]),d=i.useCallback(()=>{t(b=>{if(b.size===0)return b;const k=new Set;return ss(k),k})},[]),m=i.useCallback((b,k)=>{t(y=>{const p=new Set(y);for(const x of k)p.add(x);return ss(p),p})},[]),u=i.useCallback((b,k)=>{t(y=>{const p=new Set(y);for(const x of k)p.delete(x);return ss(p),p})},[]),h=i.useCallback(b=>Mn(e,b),[e]);return{hiddenTabs:e,autoHiddenTabs:r,toggleTarget:a,hideTarget:o,autoHideTarget:c,showTarget:l,showAllTabs:d,hideAllForDaemon:m,showAllForDaemon:u,isHidden:h}}function Ol(e){return e instanceof Error?e.message:String(e||"")}function Wl(e){const t=Ol(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 Fl(e){const t=Ol(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||!st(e)||et(e))return;const o=Hs(e);if(o===t)return;const c=e.sessionId;c&&a(l=>({...l,[c]:t}));try{await n(ws(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Ot(e),mode:t})}catch(l){const d=Fl(l);c&&!d&&a(m=>{const u={...m};return o===Ul(r,c)?delete u[c]:u[c]=o,u}),Wl(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 Di(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 Sx(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=Di(a,t),c=Array.isArray(a.childSessions)?a.childSessions.map(d=>Di(d,t)):a.childSessions,l=c!==a.childSessions;return o!==a||l?(r=!0,{...o,...l?{childSessions:c}:{}}):a});return r?n:e}function Ul(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 Nx(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))Ul(t,a)===o&&(delete n[a],r=!0);return r?n:e}function Cx({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){i.useEffect(()=>{zc()},[]);const a=i.useMemo(()=>e.map(o=>({id:o.tabKey,name:bl(o),status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null})),[e]);return pf(a),i.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{r(l=>{const d=Date.now(),m={};for(const[u,h]of Object.entries(l))d-h<5e3&&(m[u]=h);return Object.keys(m).length===Object.keys(l).length?l:m})},5500);return()=>clearTimeout(c)},[t,r]),i.useEffect(()=>{const o=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const d=l.filter(m=>m.timestamp>c).slice(-100);return d.length===l.length?l:d})},6e4);return()=>clearInterval(o)},[n]),null}function Ei(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 fs(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=Ei(t==null?void 0:t.receivedAt)||Ei(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function Ua(e,t=0){return fs(e)||e.lastUpdated||t||0}function zl(e){return fs(e)||e.lastUpdated||0}function Vl(e,t,r=zl){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 za(e){var r;const t=xt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function Ix(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!za(e)&&!e.title.trim()}function Tx(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(za(r))-Number(za(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:Vl(t,r)})[0]||null}function Et(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=Tx(a);return n?o&&Ix(n)?o:n:o||r[0]||null}function Mx(e){const t=String(e.daemonId||"").trim(),r=String(e.id||"").trim();return!t||r.startsWith(`${t}:`)?r:`${t}:${r}`}function Ax(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=Mx(n),o=r.get(a);if(!o){r.set(a,n);continue}const c=(o.workspace?1:0)+(o.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>c||(n.timestamp||0)>(o.timestamp||0))&&r.set(a,n)}return Array.from(r.values())}function ta(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 Lx(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 $i(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?Lx(Ps(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 Rx(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||""),$i(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||""),$i(r.activeChat)].join(":"))].join("|")}function Px(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 _x(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const o of Ls({routeId:n.routeId}))r.set(o,a);for(const o of Ls({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(o,n.streamSource==="native"?a:n);for(const o of Ls({tabKey:n.tabKey}))r.set(o,n)}return r}function Dx(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Ex(e){const t=Dx(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=Ps(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function $x({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=i.useMemo(()=>Ax(e),[e]),o=i.useMemo(()=>Sl(e),[e]),c=i.useRef([]),l=i.useRef([]),d=i.useRef([]),m=i.useRef(new Map),u=i.useRef(new Map),h=i.useMemo(()=>{const S=new Map,v=[];for(const j of a){const{connectionState:K="new",machineName:P}=Nl(j,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),T=Rx(j),W=m.current.get(j.id);if(W&&W.ide===j&&W.sourceSignature===T&&W.connectionState===K&&W.machineName===P){S.set(j.id,W),v.push(...W.conversations);continue}const H=Co(j,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),R={ide:j,sourceSignature:T,connectionState:K,machineName:P,conversations:H};S.set(j.id,R),v.push(...H)}m.current=S;const M=new Map,A=j=>{const K=Ex(j),P=u.current.get(j.tabKey);if(P&&P.signature===K)return M.set(j.tabKey,P),P.timestamp;const T={signature:K,timestamp:zl(j)||(P==null?void 0:P.timestamp)||0};return M.set(j.tabKey,T),T.timestamp},w=[...v].sort((j,K)=>Vl(j,K,A));return u.current=M,w},[a,t,o]),b=i.useMemo(()=>{const S=Px(h,r);return ta(c.current,S)?c.current:(c.current=S,S)},[h,r]),k=i.useMemo(()=>{const S=new Map,v=Array.from(new Set(b.map(M=>M.routeId)));for(const M of v){const A=Et(b,M);A&&S.set(M,A)}return S},[b]),y=i.useMemo(()=>{const S=new Map;for(const v of b){const M=k.get(v.routeId),A=v.streamSource==="native"&&M?M:v;for(const w of Ls({providerSessionId:v.providerSessionId,sessionId:v.sessionId,tabKey:v.tabKey}))S.set(w,A)}return S},[b,k]),p=i.useMemo(()=>_x(b,k),[b,k]),x=i.useCallback(S=>{if(S)return y.get(S)},[y]),g=i.useCallback(S=>{if(S)return p.get(S)},[p]),f=i.useMemo(()=>{const S=b.filter(v=>!Mn(n,v));return ta(l.current,S)?l.current:(l.current=S,S)},[b,n]),N=i.useMemo(()=>{const S=f.map(v=>v.tabKey);return ta(d.current,S)?d.current:(d.current=S,S)},[f]);return{chatIdes:a,conversations:b,visibleConversations:f,visibleTabKeys:N,resolveConversationBySessionId:x,resolveConversationByTarget:g}}function Bx({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 Kx({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){i.useEffect(()=>{nt.setIdes(e)},[e]),i.useEffect(()=>{nt.setResolveAction((a,o,c)=>{t(a,o,c).catch(()=>{})})},[t]),i.useEffect(()=>{const a=nt.onToast(o=>{r(l=>l.some(m=>m.message===o.message&&o.timestamp-m.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=pl.on("status_event",o=>{nt.handleRawEvent(o,"ws")});return()=>{a()}},[]),i.useEffect(()=>{var o;const a=c=>{var p;const l=c.data;if((l==null?void 0:l.type)!=="notification_action"||typeof l.action!="string"||!l.action.startsWith("approval_")||!(l.daemonId||l.targetSessionId||l.targetKey))return;const d=l.targetSessionId||l.targetKey||l.daemonId,m=n(d),u=(m==null?void 0:m.routeId)||l.daemonId;if(!u)return;const h=Number(l.buttonIndex),b=l.button||((p=m==null?void 0:m.modalButtons)==null?void 0:p[h])||"Approve",k=String(b).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),y=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(k);t(u,"resolve_action",{action:y?"approve":"reject",button:b,...Number.isFinite(h)&&{buttonIndex:h},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(x=>console.error("[SW Action] approval failed:",x))};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 Ox="adhdev_dashboardLayout_v1",Wx="adhdev_dashboardDockview_v1",Fx="adhdev_dashboardDockviewHiddenRestore_v1",er={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Lo(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function Hx(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Gl(e){return`${Ox}:${e}`}function Ux(e){const t=Gl(e);return Lo(t,null)}function zx(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=Gl(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function ql(e){return`${Wx}:${e}`}function Vx(e){const t=ql(e);return Lo(t,null)}function Gx(e,t){try{const r=ql(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Yl(e){return`${Fx}:${e}`}function qx(e){const t=Yl(e);return Lo(t,{})}function Yx(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 Xx(){return{groupAssignments:[...er.groupAssignments],focusedGroup:er.focusedGroup,groupActiveTabIds:{...er.groupActiveTabIds},groupTabOrders:{...er.groupTabOrders},groupSizes:[...er.groupSizes]}}function Jx(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function Qx(){const[e]=i.useState(()=>Hx(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({}),[m,u]=i.useState([]),[h,b]=i.useState(()=>typeof window<"u"&&window.innerWidth<768),[k,y]=i.useState(!1),p=i.useCallback(()=>{if(k)return;const j=Ux(e)??Xx();r(new Map(j.groupAssignments)),a(j.focusedGroup),c(j.groupActiveTabIds),d(j.groupTabOrders),u(j.groupSizes),y(!0)},[k,e]);i.useEffect(()=>{k&&zx(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:l,groupSizes:m})},[k,e,t,n,o,l,m]),i.useEffect(()=>{const j=window.matchMedia("(max-width: 767px)"),K=P=>b(P.matches);return j.addEventListener("change",K),()=>j.removeEventListener("change",K)},[]);const x=i.useCallback(j=>{r(j)},[]),g=i.useCallback(j=>{a(j)},[]),f=i.useCallback(j=>{c(j)},[]),N=i.useCallback(j=>{d(j)},[]),S=i.useCallback(j=>{u(j)},[]),v=i.useCallback(j=>{g(j)},[g]),M=i.useCallback((j,K)=>{c(P=>(P[j]??null)===(K??null)?P:{...P,[j]:K})},[]),A=i.useCallback((j,K)=>{d(P=>{const T=P[j];return Jx(T,K)?P:{...P,[j]:K}})},[]),w=i.useCallback((j,K)=>{const P=K.get(j)??0;return M(P,j),v(P),P},[v,M]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:x,focusedGroup:n,updateFocusedGroup:g,focusGroup:v,groupActiveTabIds:o,updateGroupActiveTabIds:f,setGroupActiveTab:M,groupTabOrders:l,updateGroupTabOrders:N,setGroupTabOrder:A,groupSizes:m,updateGroupSizes:S,isMobile:h,hasHydratedStoredLayout:k,hydrateStoredLayout:p,focusConversationTab:w}}function Zx(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=bo(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function eb({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:c,setSearchParams:l,historyModalOpen:d,activeConv:m,isRefreshingHistory:u,ides:h,handleRefreshHistory:b}){const k=i.useRef(!1),y=i.useRef(!1),p=i.useRef(null),x=i.useRef(!1);i.useEffect(()=>{if(!e||k.current||t.length===0)return;if(!a){o();return}const g=r(e);g&&(c(g.tabKey,n),k.current=!0,y.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),l(f=>{const N=new URLSearchParams(f);return N.delete("activeTab"),N},{replace:!0}))},[e,t,r,n,a,o,c,l]),i.useEffect(()=>{if(!(y.current||a)&&t.length!==0){if(!e){o(),y.current=!0;return}if(k.current){y.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(y.current||a)&&(o(),y.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,t.length,a,o]),i.useEffect(()=>{if(!d){x.current=!1;return}if(!m||x.current||u)return;const g=h.find(f=>f.id===m.routeId);g&&(!g.chats||g.chats.length===0||Zx(g.chats,m))&&(x.current=!0,b())},[d,m,u,h,b])}function sa(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=bo(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Xl({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:o}){const[c,l]=i.useState(!1),[d,m]=i.useState(!1),u=i.useCallback(async y=>{try{await e("standalone","launch_ide",{ideType:y,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),h=i.useCallback(async(y,p)=>{try{const x=y||(t==null?void 0:t.daemonId)||"",g=await e(x,"switch_chat",{id:p,sessionId:p,...is(t)}),f=g==null?void 0:g.result;if((g==null?void 0:g.success)===!0||f==="switched"||f==="switched-by-title")return;f===!1||f==="not_found"?Xs(a,"⚠️ Session tab not found — try refreshing history"):typeof f=="string"&&f.startsWith("error:")?Xs(a,`⚠️ Switch error: ${f}`):Xs(a,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),Xs(a,`❌ Switch failed: ${x.message||"connection error"}`)}},[t,e,a]),b=i.useCallback(async()=>{if(!(!t||c)){l(!0);try{const y=Es(t);await e(y,"new_chat",{...is(t)}),o(p=>({...p,[t.tabKey]:Date.now()}))}catch(y){console.error("New chat failed",y)}finally{l(!1)}}},[t,c,e,o]),k=i.useCallback(async()=>{var y,p;if(!(!t||d)){m(!0);try{const x=Es(t),g=async()=>e(x,"list_chats",{forceExpand:!0,...is(t)});let f=await g(),N=(f==null?void 0:f.chats)||((y=f==null?void 0:f.result)==null?void 0:y.chats);sa(N,t)&&(await new Promise(S=>setTimeout(S,450)),f=await g(),N=(f==null?void 0:f.chats)||((p=f==null?void 0:f.result)==null?void 0:p.chats)),f!=null&&f.success&&Array.isArray(N)&&(n(t.routeId,N),sa(N,t)&&!sa(r,t)&&Xs(a,"⚠️ History dialog did not fully open — try once more"))}catch(x){console.error("Refresh history failed",x)}finally{m(!1)}}},[t,r,d,e,n,a]);return{isCreatingChat:c,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:h,handleNewChat:b,handleRefreshHistory:k}}function tb(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 sb(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function Bi(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 $r(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 Ki(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 rb(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 nb(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 Oi(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 Wi(e){return Array(e).fill(100/e)}function ab({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:c,isMobile:l,visibleConversations:d,visibleTabKeys:m}){const u=i.useRef(null),h=i.useMemo(()=>$r(e,m),[e,m]),b=h.assignments,k=i.useMemo(()=>l?1:h.groupCount,[h.groupCount,l]),y=k>1,p=i.useCallback((v,M)=>{t(A=>{const w=new Map($r(A,m).assignments);return M===0?w.delete(v):w.set(v,M),w}),n(A=>({...A,[M]:v})),r(M)},[t,m,n,r]),x=i.useCallback(v=>{t(M=>{const A=$r(M,m).assignments,w=new Map;for(const[j,K]of A)K!==v&&(K>v?w.set(j,K-1):w.set(j,K));return w}),c(M=>{if(M.length<=1)return[];const A=[...M];A.splice(v,1);const w=A.reduce((j,K)=>j+K,0);return w>0?A.map(j=>j/w*100):[]}),r(0)},[t,m,c,r]),g=i.useCallback((v,M)=>{M.preventDefault();const A=u.current;if(!A)return;const w=M.clientX,j=A.offsetWidth,K=o.length===k?[...o]:Wi(k),P=W=>{const R=(W.clientX-w)/j*100,I=[...K];I[v]=Math.max(15,K[v]+R),I[v+1]=Math.max(15,K[v+1]-R),c(I)},T=()=>{document.removeEventListener("mousemove",P),document.removeEventListener("mouseup",T),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",P),document.addEventListener("mouseup",T)},[o,k,c]),f=i.useCallback((v,M,A)=>{if(k>=4)return;const w=A==="left"?M:M+1;t(j=>{const K=$r(j,m).assignments,P=new Map;for(const T of d){const W=K.get(T.tabKey)??0,H=W>=w?W+1:W;H>0&&P.set(T.tabKey,H)}return w>0&&P.set(v,w),P}),c(j=>{const K=j.length===k?[...j]:Wi(k),P=K[M]??100/k,T=Math.max(15,P/2),W=Math.max(15,P/2),H=[...K];H[M]=T,H.splice(w,0,W);const R=H.reduce((I,C)=>I+C,0);return H.map(I=>I/R*100)}),n(j=>{const K=Oi(j,w);return K[w]=v,K}),a(j=>{const K=Oi(j,w);return K[w]=[v],K}),r(w)},[k,t,m,d,c,n,a,r]);i.useEffect(()=>{tb(e,b)||t(b)},[e,b,t]),i.useEffect(()=>{const{mapping:v,usedGroups:M}=h;n(A=>{const w=Ki(A,v);return Bi(A,w)?A:w}),a(A=>{const w=Ki(A,v);return Bi(A,w)?A:w}),r(A=>{const w=l?0:rb(A,M,v);return A===w?A:w}),c(A=>{const w=l?[]:nb(A,M,h.groupCount);return sb(A,w)?A:w})},[h,l,n,a,r,c]);const N=i.useMemo(()=>{const v=Array.from({length:k},()=>[]);for(const M of d){const A=b.get(M.tabKey)??0,w=Math.min(A,k-1);v[w].push(M)}return v},[d,b,k]),S=i.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:u,normalizedGroupAssignments:b,numGroups:k,isSplitMode:y,groupedConvs:N,moveTabToGroup:p,closeGroup:x,handleResizeStart:g,splitTabRelative:f,clearAllSplits:S}}function ra(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="stable"||t==="latest"?"stable":t==="preview"||t==="next"?"preview":null}function ob(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="latest"||t==="stable"?"latest":t==="next"||t==="preview"?"next":null}function Br(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Ro(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},r=ra(t.channel)||ra(e.updateChannel)||ra(e.releaseChannel)||void 0,n=ob(t.npmTag)||(r==="preview"?"next":r==="stable"?"latest":void 0),a=Br(t.targetVersion)||Br(e.serverVersion)||void 0,o=Br(t.minVersion)||void 0,c=Br(t.updateCommand)||(r?`adhdev update --channel ${r}`:void 0);return{...r?{channel:r}:{},...n?{npmTag:n}:{},...a?{targetVersion:a}:{},...o?{minVersion:o}:{},...c?{updateCommand:c}:{}}}function Cs(e,t=null){return Ro(e).targetVersion||t}function Jl(e){return Ro(e).channel||null}function Ql(e){const t=Ro(e);return{...t.channel?{channel:t.channel}:{},...t.npmTag?{npmTag:t.npmTag}:{},...t.targetVersion?{targetVersion:t.targetVersion}:{},...Object.keys(t).length>0?{updatePolicy:t}:{}}}function ib({ides:e,sendDaemonCommand:t}){const r="0.9.79",n=i.useMemo(()=>e.filter(h=>h.type!=="adhdev-daemon"?!1:Rl(h,Cs(h,r))).sort((h,b)=>Number(ur(b,Cs(b,r)))-Number(ur(h,Cs(h,r)))),[r,e]),a=i.useMemo(()=>n.some(h=>ur(h,Cs(h,r))),[r,n]),o=i.useMemo(()=>n.map(h=>Cs(h,r)).find(h=>typeof h=="string"&&h.trim().length>0)||r,[r,n]),[c,l]=i.useState(!1),[d,m]=i.useState({}),u=i.useCallback(async h=>{var k,y;const b=e.find(p=>p.id===h);if(b){m(p=>({...p,[h]:"upgrading"}));try{const p=await t(h,"daemon_upgrade",Ql(b));(k=p==null?void 0:p.result)!=null&&k.upgraded||(y=p==null?void 0:p.result)!=null&&y.success?m(x=>({...x,[h]:"done"})):m(x=>({...x,[h]:"error"}))}catch{m(p=>({...p,[h]:"error"}))}}},[e,t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:c,setVersionBannerDismissed:l,upgradingDaemons:d,handleBannerUpgrade:u}}const Zl=80;function Jr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function cb(e){return{...e,createdAt:Jr(e.createdAt),updatedAt:Jr(e.updatedAt,e.createdAt),lastEventAt:Jr(e.lastEventAt,e.updatedAt||e.createdAt)}}function lb(e){const t=go(e);return t==="unknown:"?e.id:t}function db(e){return[e.type,il(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function ub(e,t=Zl){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=lb(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 mb(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=Sn(a,t),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const d=Jr(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,r),m=db({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(cb({id:m,dedupKey:m,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Jc(a),preview:Ff(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return ub(n)}function fb(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function pb(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=Zl}=e,a=i.useMemo(()=>mb(t,r).slice(0,Math.max(0,n)),[t,r,n]),o=i.useMemo(()=>fb(a),[a]);return{notifications:a,unreadCount:o}}function hb({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}}const xb=i.createContext(null);function bb(){return i.useContext(xb)}function An(...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 gb(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 Ln(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=gb(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 yb(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 vb(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Rn(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=vb(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=(m,u)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${u}`:m==="/"||m==="\\"?`${c}${u}`:`${m.replace(/[\\/]+$/,"")}${c}${u}`,d=Array.isArray(a==null?void 0:a.files)?a.files.filter(m=>(m==null?void 0:m.type)==="directory"&&typeof(m==null?void 0:m.name)=="string").map(m=>({name:m.name,path:typeof(m==null?void 0:m.path)=="string"&&m.path.trim()?m.path:l(o,m.name)})).sort((m,u)=>m.name.localeCompare(u.name)):[];return{path:o,directories:d}}function wb(e,t){const r={meshId:t.meshId||"",workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp"};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand)\s*\}\}/g,(n,a)=>r[a]||"")}function ed(e,t={}){const r=e==null?void 0:e.mcpConfig;return(r==null?void 0:r.mode)!=="manual"?null:{serverName:r.serverName||"adhdev-mesh",configFormat:r.format,configPathCommand:r.configPathCommand,requiresRestart:r.requiresRestart===!0,instructions:r.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:wb(r.template||"",{...t,serverName:r.serverName||"adhdev-mesh"})}}function jb(e){if(!e||typeof e!="object")return null;const t=e,r=typeof t.instructions=="string"?t.instructions:"",n=typeof t.template=="string"?t.template:"";return!r&&!n?null:{serverName:typeof t.serverName=="string"?t.serverName:void 0,configFormat:typeof t.configFormat=="string"?t.configFormat:void 0,configPathCommand:typeof t.configPathCommand=="string"?t.configPathCommand:void 0,requiresRestart:t.requiresRestart===!0,instructions:r||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:n}}function Zt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function td(e){return kr(e)||e.tabKey||e.routeId||null}function sd(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",a=e.conversations.find(o=>{if(n&&o.routeId!==n)return!1;const c=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey].map(l=>typeof l=="string"?l.trim():"").filter(Boolean);return!!(t&&c.includes(t)||r&&c.includes(r)||n&&o.routeId===n)});if(a!=null&&a.tabKey)return a.tabKey;if(n){const o=Et(e.conversations,n)||e.conversations.find(c=>c.routeId===n);if(o!=null&&o.tabKey)return o.tabKey}return t||r||n||null}function Yt(e){return String(e||"").trim()}function rd(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function gn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function kb(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function Sb(e,t){const r=Yt(e.providerSessionId),n=Yt(e.targetSessionId),a=t.find(o=>{const c=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(Yt).filter(Boolean);return!!(r&&c.includes(r)||n&&c.includes(n))});return a?a.tabKey:n||r||null}function Nb(e,t,r){if(t.event!=="agent:generating_completed")return null;const n=rd(t.daemonId);if(n&&n!==e.machineId)return null;const a=Yt(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=Yt(e.resumeSessionId),c=Yt(e.launchedSessionId),l=Yt(t.providerSessionId),d=Yt(t.targetSessionId);if(o&&o!==l&&o!==d||c&&c!==l&&c!==d)return null;const m=gn(e.workspacePath);if(m){const u=gn(t.workspaceName);if(u&&!kb(u,m))return null}return Sb(t,r)}function Fi(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Cb({ides:e,conversations:t,onOpenSession:r}){const[n,a]=i.useState(null),o=i.useRef(null),c=i.useCallback(()=>{o.current=null,a(null)},[]),l=i.useCallback(d=>{o.current=d,a(d)},[]);return i.useEffect(()=>{if(!n)return;const d=gn(n.workspacePath),m=e.find(h=>{var x,g,f,N;if(!h||h.type==="adhdev-daemon"||rd(h.daemonId||h.id)!==n.machineId||(br(h)?"cli":Ms(h)?"acp":"ide")!==n.kind)return!1;const y=String(h.agentType||h.type||"");if(n.providerType&&y!==n.providerType)return!1;if(n.resumeSessionId)return String(h.providerSessionId||"")===n.resumeSessionId;if(n.launchedSessionId){const S=String(n.launchedSessionId||"");return[h.providerSessionId,h.sessionId,h.instanceId,h.id].map(M=>String(M||"")).filter(Boolean).includes(S)}if(d){const S=gn(h.workspace||h.runtimeWorkspaceLabel);return S?S===d:!1}return Number(h.lastUpdated||h._lastUpdate||h.timestamp||((N=(f=(g=(x=h.activeChat)==null?void 0:x.messages)==null?void 0:g.at)==null?void 0:f.call(g,-1))==null?void 0:N.timestamp)||0)>=n.startedAt-5e3});if(!m)return;const u=sd({entrySessionId:m.sessionId,entryInstanceId:m.instanceId,entryRouteId:m.id,conversations:t});u&&(c(),r(u))},[c,t,e,r,n]),i.useEffect(()=>nt.onStatusEvent(d=>{const m=o.current;if(!m)return;const u=Nb(m,d,t);u&&(c(),r(u))}),[c,t,r]),i.useEffect(()=>{if(!n)return;const d=window.setTimeout(()=>{a(m=>!m||m.startedAt!==n.startedAt?m:(o.current=null,null))},45e3);return()=>window.clearTimeout(d)},[n]),{trackPendingLaunch:l}}function Ib({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:o}){const c=bb(),l=i.useCallback(async(p,x)=>Rn(e,p,x),[e]),d=i.useCallback(async(p,x)=>{if(!x.trim())return{ok:!1,error:"Choose a workspace path first."};try{const g=await e(p,"workspace_add",{path:x.trim()});return g!=null&&g.success?{ok:!0}:{ok:!1,error:(g==null?void 0:g.error)||"Could not save workspace"}}catch(g){return{ok:!1,error:g instanceof Error?g.message:"Could not save workspace"}}},[e]),m=i.useCallback(async(p,x,g)=>{var f;try{const N={ideType:x,enableCdp:!0};(f=g==null?void 0:g.workspacePath)!=null&&f.trim()&&(N.workspace=g.workspacePath.trim());const S=await e(p,"launch_ide",N);return!(S!=null&&S.success)&&(S==null?void 0:S.success)!==void 0?{ok:!1,error:(S==null?void 0:S.error)||"Could not launch IDE"}:(t({machineId:p,kind:"ide",providerType:x,workspacePath:(g==null?void 0:g.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(N){return{ok:!1,error:N instanceof Error?N.message:"Could not launch IDE"}}},[e,t]),u=i.useCallback(async(p,x,g,f)=>{var S,v,M;const N=Date.now();try{const A={cliType:g};(S=f==null?void 0:f.workspacePath)!=null&&S.trim()?A.dir=f.workspacePath.trim():f!=null&&f.workspaceId&&(A.workspaceId=f.workspaceId),(v=f==null?void 0:f.resumeSessionId)!=null&&v.trim()&&(A.resumeSessionId=f.resumeSessionId.trim()),Array.isArray(f==null?void 0:f.cliArgs)&&f.cliArgs.length>0&&(A.cliArgs=f.cliArgs),(M=f==null?void 0:f.initialModel)!=null&&M.trim()&&(A.initialModel=f.initialModel.trim());const w=await e(p,"launch_cli",A),j=(w==null?void 0:w.result)||w,K=(j==null?void 0:j.sessionId)||(j==null?void 0:j.id);return w!=null&&w.success&&K?(t({machineId:p,kind:x,providerType:g,workspacePath:(f==null?void 0:f.workspacePath)||null,resumeSessionId:(f==null?void 0:f.resumeSessionId)||null,launchedSessionId:K,startedAt:N}),{ok:!0}):w!=null&&w.success?(t({machineId:p,kind:x,providerType:g,workspacePath:(f==null?void 0:f.workspacePath)||null,resumeSessionId:(f==null?void 0:f.resumeSessionId)||null,startedAt:N}),{ok:!0}):{ok:!1,error:(w==null?void 0:w.error)||(j==null?void 0:j.error)||`Could not launch ${x.toUpperCase()} session`}}catch(A){return Fi(A)?(t({machineId:p,kind:x,providerType:g,workspacePath:(f==null?void 0:f.workspacePath)||null,resumeSessionId:(f==null?void 0:f.resumeSessionId)||null,startedAt:N}),{ok:!0}):{ok:!1,error:A instanceof Error?A.message:`Could not launch ${x.toUpperCase()} session`}}},[r,e,t]),h=i.useCallback(async p=>{var x;if(c!=null&&c.listMeshes)return c.listMeshes(p);if(!p)return[];try{const g=await e(p,"list_meshes",{}),f=(g==null?void 0:g.result)??g;if((f==null?void 0:f.success)===!1)throw new Error((f==null?void 0:f.error)||"Could not load meshes");return(Array.isArray(f==null?void 0:f.meshes)?f.meshes:Array.isArray((x=f==null?void 0:f.result)==null?void 0:x.meshes)?f.result.meshes:[]).map(S=>{var v;return{id:String((S==null?void 0:S.id)||""),name:String((S==null?void 0:S.name)||(S==null?void 0:S.id)||"Untitled mesh"),repoIdentity:(S==null?void 0:S.repoIdentity)||(S==null?void 0:S.repo_identity)||null,workspace:Array.isArray(S==null?void 0:S.nodes)&&S.nodes.length>0?String(((v=S.nodes[0])==null?void 0:v.workspace)||""):null,nodesCount:Array.isArray(S==null?void 0:S.nodes)?S.nodes.length:void 0,status:(S==null?void 0:S.status)||null}}).filter(S=>S.id)}catch(g){throw console.error("List meshes failed",g),g}},[c,e]),b=i.useCallback(async(p,x,g)=>{if(!x.trim())return{ok:!1,error:"Choose a mesh first."};if(c!=null&&c.launchMeshCoordinator)return c.launchMeshCoordinator(p,x,g);const f=Date.now();try{const N={meshId:x.trim()};g.trim()&&(N.cliType=g.trim());const S=await e(p,"launch_mesh_coordinator",N),v=(S==null?void 0:S.result)??S;if((v==null?void 0:v.success)===!1||(S==null?void 0:S.success)===!1){const A=String((v==null?void 0:v.code)||(S==null?void 0:S.code)||""),w=jb((v==null?void 0:v.meshCoordinatorSetup)||(v==null?void 0:v.manualSetup)||(S==null?void 0:S.meshCoordinatorSetup)||(S==null?void 0:S.manualSetup));return{ok:!1,error:(v==null?void 0:v.error)||(S==null?void 0:S.error)||"Could not launch mesh coordinator",code:A||void 0,manualSetup:w}}const M=(v==null?void 0:v.sessionId)||(v==null?void 0:v.id);return M?r(M):t({machineId:p,kind:"cli",providerType:(v==null?void 0:v.cliType)||g.trim()||void 0,workspacePath:(v==null?void 0:v.workspace)||null,startedAt:f}),{ok:!0}}catch(N){return Fi(N)?(t({machineId:p,kind:"cli",providerType:g.trim()||void 0,startedAt:f}),{ok:!0}):{ok:!1,error:N instanceof Error?N.message:"Could not launch mesh coordinator"}}},[c,r,e,t]),k=i.useCallback(async(p,x)=>{if(!p||!x)return[];try{const g=await e(p,"list_saved_sessions",{providerType:x,kind:"cli",limit:30}),f=(g==null?void 0:g.result)??g;return Array.isArray(f==null?void 0:f.sessions)?f.sessions:[]}catch(g){return console.error("List saved sessions failed",g),[]}},[e]),y=i.useCallback(async p=>{await Hl({conversation:n,mode:p,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[n,a,e,o]);return{handleBrowseMachineDirectory:l,handleSaveMachineWorkspace:d,handleLaunchMachineIde:m,handleLaunchMachineProvider:u,handleListMachineMeshes:h,handleLaunchMeshCoordinator:b,handleListMachineSavedSessions:k,setActiveCliViewMode:y}}function Tb(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 Mb(e,t,r=Date.now()){return!e||!Tb(t)?null:{tabKey:e,nonce:r}}function Ab({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:o,setSearchParams:c}){const[l,d]=i.useState(null),[m,u]=i.useState(null),h=i.useMemo(()=>{var x,g;if(!e){if(l){const f=t.find(N=>N.tabKey===l);if(f)return f}return r[0]}const p=n[a];if(p){const f=t.find(N=>N.tabKey===p);if(f)return f}return((x=o[a])==null?void 0:x[0])||((g=o[0])==null?void 0:g[0])},[t,l,a,n,o,e,r]),b=i.useCallback(p=>{d(p)},[]),k=i.useCallback(p=>{d(p.tabKey),c(x=>{const g=new URLSearchParams(x),f=Uf(p);return f?g.set("activeTab",f):g.delete("activeTab"),g},{replace:!0})},[c]),y=i.useCallback((p,x)=>{const g=Mb(p,x);g&&u(g)},[]);return{activeConv:h,openDesktopConversation:k,requestScrollToBottom:y,scrollToBottomRequest:m,setDesktopActiveTab:b}}function Lb(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 Rb(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 Pb({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 m=()=>{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){m(),a.current=null;return}if(!(e!=null&&e.sessionId)){m(),a.current=null;return}const u=cn(e,r),h=Rb({tabKey:e.tabKey,historySessionId:kr(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:fs(e),liveState:u}),b=h.autoReadKey,k=Lb({autoReadKey:b,shouldMarkSeen:h.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!h.shouldMarkSeen){k.shouldCancelPending&&m(),a.current=b;return}if(!k.shouldSchedule)return;k.shouldCancelPending&&m();const y=()=>{if(document.visibilityState!=="visible"||a.current===b)return;a.current=b,o.current=null,c.current=null,l.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const x=h.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:x,completionMarker:h.completionMarker}).catch(()=>{})};if(o.current=k.nextPendingKey,document.visibilityState==="visible"){c.current=setTimeout(y,1500);const x=()=>{document.visibilityState!=="visible"&&c.current&&(clearTimeout(c.current),c.current=null)};d.current=x,document.addEventListener("visibilitychange",x);return}const p=()=>{document.visibilityState==="visible"&&(l.current&&clearTimeout(l.current),l.current=setTimeout(y,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=p,document.addEventListener("visibilitychange",p)},[e,t,r,n]),i.useEffect(()=>()=>{c.current&&clearTimeout(c.current),l.current&&clearTimeout(l.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function na(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 _b({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:o,setToasts:c,setClearedTabs:l,setSearchParams:d}){var C;const[m,u]=i.useState(!1),[h,b]=i.useState([]),[k,y]=i.useState(()=>jt()),[p,x]=i.useState(!1),[g,f]=i.useState(null),N=i.useRef(null),S=i.useMemo(()=>r||t||e,[e,r,t]),v=!!S&&st(S)&&!et(S),M=i.useMemo(()=>{if(!S||!v)return null;const O=S.daemonId||S.routeId||"",_=Ot(S),E=na(S);return`${O}:${_}:${S.providerSessionId||""}:${E}`},[S,v]),A=i.useMemo(()=>!S||!v?"":na(S),[S,v]),{isCreatingChat:w,isRefreshingHistory:j,handleSwitchSession:K,handleNewChat:P,handleRefreshHistory:T}=Xl({sendDaemonCommand:a,activeConv:S,chats:(C=n.find(O=>O.id===(S==null?void 0:S.routeId)))==null?void 0:C.chats,updateRouteChats:o,setToasts:c,setClearedTabs:l}),W=i.useCallback(()=>{u(!0)},[]),H=i.useCallback(()=>{u(!1)},[]),R=i.useCallback(async()=>{if(!(!S||!v||p)){x(!0);try{const O=S.daemonId||S.routeId,_=Ot(S),E=na(S),U=await a(O,"list_saved_sessions",{agentType:_,providerType:_,kind:"cli",limit:50,...S.providerSessionId?{providerSessionId:S.providerSessionId}:{},...E?{workspace:E}:{}}),Q=(U==null?void 0:U.result)??U;b(Array.isArray(Q==null?void 0:Q.sessions)?Q.sessions:[])}catch(O){console.error("Refresh saved sessions failed",O),b([])}finally{x(!1)}}},[S,p,v,a]);i.useEffect(()=>{if(!m){N.current=null;return}if(!v){N.current=null,b([]),x(!1);return}!M||p||N.current!==M&&(N.current=M,R())},[R,m,p,v,M]);const I=i.useCallback(async O=>{if(!S||!v||!O.providerSessionId||!O.workspace)return;const _=S.daemonId||S.routeId,E=Ot(S);try{f(O.providerSessionId);const U=await a(_,"launch_cli",{cliType:E,dir:O.workspace,resumeSessionId:O.providerSessionId,initialModel:Hc(O.summaryMetadata,"model",{preferShortValue:!0})||void 0}),Q=(U==null?void 0:U.result)??U,xe=typeof(Q==null?void 0:Q.sessionId)=="string"?Q.sessionId:typeof(Q==null?void 0:Q.id)=="string"?Q.id:"";xe&&d(de=>{const Z=new URLSearchParams(de);return Z.set("activeTab",xe),Z},{replace:!0}),H()}catch(U){console.error("Resume saved session failed",U)}finally{f(null)}},[H,S,v,a,d]);return{historyModalOpen:m,openHistoryModal:W,closeHistoryModal:H,historyTargetConv:S,isSavedSessionHistoryTarget:v,isHistoryCreatingChat:w,isHistoryRefreshingHistory:j,handleHistorySwitchSession:K,handleHistoryNewChat:P,handleHistoryRefresh:T,savedHistorySessions:h,savedHistoryFilters:k,setSavedHistoryFilters:y,missingWorkspaceResumePath:A,isSavedHistoryLoading:p,resumingSavedHistorySessionId:g,handleRefreshSavedHistory:R,handleResumeSavedHistorySession:I}}function Db({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l}){const[d,m]=i.useState(null),[u,h]=i.useState(null),b=i.useMemo(()=>{if(e||!n)return null;const g=l(n);return g&&!st(g)&&!et(g)?g:null},[e,n,l]),k=i.useMemo(()=>{const g=d==null?void 0:d.routeId;if(!g)return null;const f=d!=null&&d.tabKey?o.find(N=>N.tabKey===d.tabKey):a?o.find(N=>N.tabKey===a):null;return(f==null?void 0:f.routeId)===g?f:Et(o,g)},[o,d,a]),y=i.useMemo(()=>{if(k)return c.find(g=>g.id===k.routeId)},[c,k]);i.useEffect(()=>{b&&(m({routeId:b.routeId,tabKey:fi(b)}),h(b),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,b]);const p=i.useCallback(g=>{g&&(m({routeId:g.routeId,tabKey:fi(g)}),h(g))},[]),x=i.useCallback(()=>{m(null),h(null)},[]);return{remoteDialogConv:k,remoteDialogIdeEntry:y,remoteDialogActiveConv:u,setRemoteDialogActiveConv:h,openRemoteDialog:p,closeRemoteDialog:x}}function Eb({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l,activeConv:d,sendDaemonCommand:m}){const{remoteDialogConv:u,remoteDialogIdeEntry:h,remoteDialogActiveConv:b,setRemoteDialogActiveConv:k,openRemoteDialog:y,closeRemoteDialog:p}=Db({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l}),[x,g]=i.useState(!1),[f,N]=i.useState(null),S=i.useCallback(async A=>{const w=A||d;!w||!st(w)&&!et(w)||(N(w),g(!0))},[d]),v=i.useCallback(()=>{g(!1),N(null)},[]),M=i.useCallback(async A=>{const w=f||d;if(!w||!st(w)&&!et(w)){v();return}g(!1);try{const j=Ot(w),K=w.routeId||w.daemonId||"";await m(K,"stop_cli",{cliType:j,targetSessionId:w.sessionId,mode:A})}catch(j){console.error("Stop CLI failed:",j)}finally{N(null)}},[d,v,f,m]);return{remoteDialogConv:u,remoteDialogIdeEntry:h,remoteDialogActiveConv:b,setRemoteDialogActiveConv:k,openRemoteDialog:y,closeRemoteDialog:p,cliStopDialogOpen:x,cliStopTargetConv:f,requestCliStop:S,cancelCliStop:v,confirmCliStop:M}}function nd({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0,meshOnly:o=!1}){var N,S;const c=Ws(),l=ws(e),d=o?null:Xc(e),m=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),u=!o&&e.streamSource==="agent-stream"&&!!e.agentName,h=!o&&!u&&(e.transport==="pty"||e.transport==="acp"),b=Ds(e),k=Hf(e),y=(N=e.settings)==null?void 0:N.meshNodeFor,p=e.meshQueueStats,x=(S=e.settings)==null?void 0:S.meshCoordinatorFor;if(!m&&!u&&!h&&!d&&!y&&!p)return null;const g=i.useCallback(()=>{if(n){n();return}l&&c("/dashboard",{state:{openMachineId:l}})},[l,c,n]),f=i.useCallback(()=>{if(r){r();return}const v=td(e);v&&c(Zt(v))},[e,c,r]);return s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[m&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:f,title:k,children:[s.jsx(Tt,{size:12}),s.jsx("span",{children:k})]}):s.jsxs("span",{className:"conversation-meta-chip",title:k,children:[s.jsx(Tt,{size:12}),s.jsx("span",{children:k})]})),u&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:b,children:[s.jsx(_s,{size:12}),s.jsx("span",{children:b})]}),h&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:b,children:[s.jsx(_s,{size:12}),s.jsx("span",{children:b})]}),d&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:g,title:d,children:[s.jsx(Jt,{size:12}),s.jsx("span",{children:d})]}):s.jsxs("span",{className:"conversation-meta-chip",title:d,children:[s.jsx(Jt,{size:12}),s.jsx("span",{children:d})]})),y&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(Jt,{size:12}),s.jsx("span",{children:"Mesh Node"})]}),x&&p&&s.jsxs("span",{className:`conversation-meta-chip ${p.pending>0?"is-active":""}`,style:p.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${p.pending} pending, ${p.assigned} assigned, ${p.completed} completed, ${p.failed} failed`,children:[s.jsx(Fu,{size:12}),s.jsxs("span",{children:[p.pending," Pending"]})]})]})}function aa(e,t=!0){return(e??!0)&&t}const Po=i.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:o,handleModalButton:c,handleRelaunch:l,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u=null,handleFocusAgent:h,isFocusingAgent:b,actionLogs:k,userName:y,scrollToBottomRequestNonce:p,isInputActive:x=!0,isVisible:g=!0}){const f=n,N=!n,S=aa(g,f),v=aa(g,N),M=aa(g),A=$l(t),w=A.status||A.modalMessage||A.modalButtons?{...t,...A.status?{status:A.status}:{},...A.modalMessage!==void 0?{modalMessage:A.modalMessage}:{},...A.modalButtons!==void 0?{modalButtons:A.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(Oc,{activeConv:w,onModalButton:c}),s.jsx(nd,{conversation:w,className:"chat-pane-meta-row mx-3 mt-1",meshOnly:!0}),w.transport!=="pty"&&w.transport!=="acp"&&w.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(xr,{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,w.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:f?"visible":"hidden",pointerEvents:f?"auto":"none"},children:s.jsx(rh,{activeConv:w,clearToken:r,terminalRef:o,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,isVisible:S,isInputActive:x&&S})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:N?"visible":"hidden",pointerEvents:N?"auto":"none"},children:s.jsx(Ba,{activeConv:w,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:h,isFocusingAgent:b,actionLogs:k,userName:y,scrollToBottomRequestNonce:p,isInputActive:x&&v,isVisible:v})})]}):s.jsx(Ba,{activeConv:w,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:h,isFocusingAgent:b,actionLogs:k,userName:y,scrollToBottomRequestNonce:p,isInputActive:x&&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 $b({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:o,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:d,onBack:m,onOpenNativeConversation:u,onOpenMachine:h,onOpenHistory:b,onOpenRemote:k,onStopCli:y,cliViewMode:p,onSetCliViewMode:x,handleSendChat:g,handleFocusAgent:f,handleModalButton:N,handleRelaunch:S}){const v=i.useRef(null),M=st(e)&&!t,A=M&&p==="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:m,type:"button","aria-label":"Back",children:s.jsx(eo,{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:lt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(nd,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>h(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[M&&p&&s.jsx(vo,{mode:p,onChange:x,compact:!0}),M&&y&&s.jsx("button",{onClick:()=>{y(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(vt,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>b(e),type:"button",children:s.jsx(to,{size:14})}),!t&&!M&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>k(e),type:"button",children:s.jsx(Tt,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(Po,{activeConv:e,clearToken:0,isCliTerminal:A,ideEntry:n,terminalRef:v,handleModalButton:N,handleRelaunch:S,handleSendChat:g,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:f,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const oa={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 Bb(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function ad(){const[e,t]=i.useState("unix"),[r,n]=i.useState("powershell"),[a,o]=i.useState(!1),c=e==="unix"?"unix":r;i.useEffect(()=>{t(Bb())},[]);const l=i.useCallback(()=>{navigator.clipboard.writeText(oa[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:oa[c].prompt}),s.jsx("span",{className:"flex-1 break-all",children:oa[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 od({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Tt},{key:"chats",label:"Chats",icon:zt}];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 Kr({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 js({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 tr({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 Kb({conversation:e,onCancel:t,onConfirm:r}){const n=lt(e),a=gs(e);return s.jsxs("div",{className:"fixed inset-0 z-[1400] 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",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:t}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-hide-confirm-title",className:"fade-in relative w-full sm:w-[min(92vw,420px)] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] border border-border-subtle bg-bg-primary shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-border-subtle bg-[var(--surface-primary)] px-4 py-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base font-extrabold text-text-primary",children:"Hide this chat from the inbox?"}),s.jsx("div",{className:"mt-1 text-[13px] leading-relaxed text-text-muted",children:"This only collapses the chat locally. You can restore it from Hidden tabs."})]}),s.jsx("button",{type:"button",className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary text-text-secondary transition-colors hover:bg-surface-primary hover:text-text-primary",onClick:t,"aria-label":"Cancel hide chat",children:s.jsx(vt,{size:16})})]}),s.jsx("div",{className:"px-4 py-4",children:s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary/60 px-3.5 py-3",children:[s.jsx("div",{className:"truncate text-sm font-bold text-text-primary",children:n}),s.jsx("div",{className:"mt-1 truncate text-xs text-text-muted",children:a})]})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 border-t border-border-subtle bg-bg-secondary px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))]",children:[s.jsx("button",{type:"button",className:"btn btn-secondary min-h-[40px] px-4 text-sm",onClick:t,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary min-h-[40px] px-4 text-sm",onClick:r,children:"Hide tab"})]})]})]})}function Or({item:e,type:t,getAvatarText:r,onOpenConversation:n,onRequestHideConversation:a,onCollectChatDebugBundle:o}){const c=t==="needs_attention"||t==="task_complete",l=t==="working",d=t==="earlier",m=t==="task_complete",{isReconnecting:u,isConnecting:h}=Fs(e.conversation),b=lt(e.conversation),k=gs(e.conversation),y=xl(e.conversation,{requiresAction:t==="needs_attention"}),p=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",x=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",g=d?"text-text-secondary":"text-text-primary",f=d?"text-text-muted":"text-text-secondary",N=d?"text-text-secondary opacity-80":"text-text-muted",S=d?"text-text-muted opacity-80":"text-text-muted",v=!l&&!m,M="text-[color:var(--status-warning)]",A=w=>{if(!o)return;w.preventDefault(),w.stopPropagation();const j=o==null?void 0:o(e.conversation);Promise.resolve(j).catch(K=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",K)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${p}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",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.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${x}`,style:c?{color:"var(--accent-on-primary)"}:void 0,children:r(b)}),a&&s.jsxs("button",{type:"button",className:"mobile-inbox-hide-button inline-flex min-h-7 items-center justify-center gap-1 rounded-full border border-border-subtle bg-bg-primary/70 px-2 text-[10px] font-semibold text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:w=>{w.preventDefault(),w.stopPropagation(),a()},"aria-label":`Hide ${b}`,title:"Hide conversation",children:[s.jsx(so,{size:11}),s.jsx("span",{children:"Hide"})]})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>n(e.conversation),onContextMenu:A,type:"button",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${g}`,children:b}),v&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${S}`,children:Kc(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${f}`,children:[s.jsx("span",{className:"truncate",children:k}),s.jsx($s,{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…"})]}):h?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):y==="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] ${N}`,children:e.preview})]}),c&&!m&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),m&&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"})]})},e.conversation.tabKey)}function Hi({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 Ob({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:o,machineCards:c,getAvatarText:l,actionLogs:d,sendDaemonCommand:m,onOpenConversation:u,onShowAllHidden:h,onHideConversation:b,onOpenNewSession:k,onOpenMachine:y,onOpenSettings:p,onSectionChange:x,wsStatus:g="connected",isStandalone:f=!1,onCollectChatDebugBundle:N}){const[S,v]=i.useState(null),M=g==="disconnected"||g==="reconnecting"||g==="offline"||g==="auth_failed",A=c.length>0,w=t.length>0||r.length>0||n.length>0||a.length>0,j=e==="machines"?"Machines":"Chats",K=f?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",P=f?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",T=i.useCallback(async R=>{const I=Es(R);if(!I)return;const C=Array.isArray(R.messages)?R.messages:[],O=sl({activeConv:R,visibleMessages:C,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:C.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),_=await m(I,"get_chat_debug_bundle",{...is(R),delivery:"daemon_file",frontendSnapshot:O}),E=mn(_),U=al(E),Q=await nl(U);Q==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),nt.showToast(rl(E,{locatorCopyStatus:Q}),Q==="failed"?"warning":"success")},[d,m]),W=N||T,H=i.useCallback(()=>{S&&(b==null||b(S),v(null))},[S,b]);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:j}),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(jn,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:p,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(wn,{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] ${P}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:M?s.jsx(tr,{icon:s.jsx(Hi,{}),title:g==="offline"?"Network offline":g==="auth_failed"?"Session expired":"Reconnecting",subtitle:g==="offline"?"Waiting for network…":g==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):c.length===0?s.jsx(tr,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:f?"Waiting for your daemon":"Connect your machines",subtitle:f?"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:!f&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(ad,{})})}):s.jsx(js,{children:c.map((R,I)=>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] ${I>0?"border-t border-border-subtle/70":""}`,onClick:()=>y(R.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(R.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:R.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:R.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[R.unread," new"]}):R.total>0?`${R.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:R.subtitle}),R.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[R.total," chat",R.total!==1?"s":"",R.unread>0?` · ${R.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},R.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(Kr,{title:"Needs attention",className:"mb-0"}),s.jsx(js,{children:t.map((R,I)=>s.jsx("div",{className:I>0?"border-t border-border-subtle/70":"",children:s.jsx(Or,{item:R,type:"needs_attention",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:b?()=>v(R.conversation):void 0,onCollectChatDebugBundle:W})},R.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(Kr,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(js,{children:r.map((R,I)=>s.jsx("div",{className:I>0?"border-t border-border-subtle/70":"",children:s.jsx(Or,{item:R,type:"task_complete",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:b?()=>v(R.conversation):void 0,onCollectChatDebugBundle:W})},R.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(Kr,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(js,{children:n.map((R,I)=>s.jsx("div",{className:I>0?"border-t border-border-subtle/70":"",children:s.jsx(Or,{item:R,type:"working",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:b?()=>v(R.conversation):void 0,onCollectChatDebugBundle:W})},R.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(Kr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(js,{children:a.map((R,I)=>s.jsx("div",{className:I>0?"border-t border-border-subtle/70":"",children:s.jsx(Or,{item:R,type:"earlier",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:b?()=>v(R.conversation):void 0,onCollectChatDebugBundle:W})},R.conversation.tabKey))}):w?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):M?s.jsx(tr,{icon:s.jsx(Hi,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):A?s.jsx(tr,{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(zt,{size:20})}),title:"No conversations yet",subtitle:yl,children:k&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:k,"aria-label":Bt,title:Bt,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:Bt})]})}):s.jsx(tr,{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(js,{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:h,children:"Restore all"})]})})})]}),e==="chats"&&k&&w&&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:k,"aria-label":Bt,title:Bt,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&&s.jsx(Kb,{conversation:S,onCancel:()=>v(null),onConfirm:H}),s.jsx(od,{section:e,onSectionChange:x})]})}function Wb(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 id(e){const t=[e.workspace||"Workspace unknown"],r=bs(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=Wb(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function Pn({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:o="",confirmLabel:c="Use this folder",onClose:l,onNavigate:d,onConfirm:m}){const[u,h]=i.useState(r);i.useEffect(()=>{h(r)},[r]);const b=yb(r),k=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(vt,{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:()=>{!b||a||d(b)},disabled:!b||a,children:[s.jsx(eo,{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:y=>h(y.target.value),onKeyDown:y=>{y.key!=="Enter"||!k||a||(y.preventDefault(),d(k))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),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:()=>{!k||a||d(k)},disabled:!k||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(y=>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(y.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(xs,{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:y.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:y.path})]})]},y.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:()=>m(k||r),disabled:!k&&!r||a,children:c})]})]})})}function _o({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:d=!1,showArgsInput:m,argsValue:u,onArgsChange:h,showModelInput:b,modelValue:k,onModelChange:y,historyProviderNode:p,onConfirm:x,onCancel:g}){const f=n==null?void 0:n.find(N=>N.key===a);return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:g,"aria-label":"Close launch confirmation",children:s.jsx(vt,{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:N=>o(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:n.map(N=>s.jsx("option",{value:N.key,children:N.label},N.key))}),(f==null?void 0:f.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:f.description})]}),p,r.map(N=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:N.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:N.value})]},`${N.label}:${N.value}`)),b&&y&&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:k||"",onChange:N=>y(N.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),m&&h&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:u||"",onChange:N=>h(N.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled: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:g,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:x,disabled:d,children:[s.jsx(no,{size:14}),d?l:c]})]})]})})}function Ui(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function ps(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?"⭐ ":""}${Ui(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:Ui(c),description:c,workspaceId:null,workspacePath:c}),n){const d=`saved:${n}`;if(o.some(m=>m.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 Fb(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Hb(e){return[Fb(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Ub(e){return e.lastLaunchedAt?kn(e.lastLaunchedAt):""}function cd(e){return{metaText:Hb(e),updatedLabel:Ub(e)}}function ia(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function zb({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:o}){var tt,mt,ht,bt;const c=jr(),[l,d]=i.useState(!1),m=(((tt=e.detectedIdes)==null?void 0:tt.length)||0)>0,u=i.useMemo(()=>(e.workspaces||[]).map(Te=>({id:Te.id,path:Te.path,label:Te.label})),[e]),h=e.defaultWorkspaceId||null,[b,k]=i.useState(h||((mt=u[0])==null?void 0:mt.id)||""),[y,p]=i.useState(""),[x,g]=i.useState(""),[f,N]=i.useState([]),[S,v]=i.useState(!1),[M,A]=i.useState(""),[w,j]=i.useState(!1),[K,P]=i.useState(ia(m,t.length,r.length)),T=i.useRef(null),[W,H]=i.useState(null),R=i.useRef("__home__"),[I,C]=i.useState("__home__"),[O,_]=i.useState(""),[E,U]=i.useState(""),[Q,xe]=i.useState(""),[de,Z]=i.useState([]),[he,we]=i.useState(()=>jt().textQuery),[be,X]=i.useState(()=>jt().workspaceQuery),[ue,ge]=i.useState(()=>jt().modelQuery),[te,le]=i.useState(()=>jt().resumableOnly),[Ne,me]=i.useState(()=>jt().sortMode),[pe,oe]=i.useState(!1),[fe,ie]=i.useState(!1),D=i.useRef(null),z=i.useRef(null);i.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const ce=b==="__custom__"?y.trim():((ht=u.find(Te=>Te.id===b))==null?void 0:ht.path)||"",se=b==="__custom__"&&!!ce&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),q=b!=="__custom__"&&((bt=u.find(Te=>Te.id===b))==null?void 0:bt.path)||"",ke=i.useMemo(()=>(e.recentLaunches||[]).map(Te=>Te.workspace),[e]),ve=i.useCallback(async Te=>{v(!0),A("");try{const Ue=await a(Te);g(Ue.path),p(Ue.path),N(Ue.directories)}catch(Ue){A(Ue instanceof Error?Ue.message:"Could not load folder")}finally{v(!1)}},[a]),Le=i.useCallback(()=>{var Ue;k("__custom__"),j(!0);const Te=Ln(e.platform,An(y.trim(),q,ke,e.defaultWorkspacePath,(Ue=u.find(Qe=>Qe.id===h))==null?void 0:Ue.path,u.map(Qe=>Qe.path)));ve(Te)},[y,h,ve,ke,q,e.platform,u]),Ae=i.useCallback(Te=>{if(Te!=null&&Te.workspaceId){k(Te.workspaceId),p("");return}if(Te!=null&&Te.workspacePath){k("__custom__"),p(Te.workspacePath);return}k(""),p("")},[]),B=i.useCallback(Te=>{if(k(Te),Te==="__custom__"){Le();return}p("")},[Le]),Ie=i.useCallback(Te=>{k("__custom__"),p(Te)},[]),Pe=i.useCallback((Te,Ue)=>{T.current=Ue,R.current=Te.selectedWorkspaceKey||"__home__",C(Te.selectedWorkspaceKey||"__home__"),_(Te.initialArgs||""),U(Te.initialModel||""),xe(""),Z([]);const Qe=Te.providerType?`${e.id}:${Te.providerType}`:null;if(ph(z.current,Qe)){const ze=jt();we(ze.textQuery),X(ze.workspaceQuery),ge(ze.modelQuery),le(ze.resumableOnly),me(ze.sortMode)}z.current=Qe,H(Te),Te.providerType&&o&&(oe(!0),o(Te.providerType).then(ze=>Z(ze||[])).catch(ze=>console.warn("Failed to load saved sessions",ze)).finally(()=>oe(!1)))},[o,e.id]),Fe=i.useMemo(()=>vl(de,{textQuery:he,workspaceQuery:be,modelQuery:ue,resumableOnly:te,sortMode:Ne}),[ue,te,de,Ne,he,be]);i.useEffect(()=>{Q&&(Fe.some(Te=>Te.providerSessionId===Q)||xe(""))},[Fe,Q]);const He=i.useCallback(()=>{T.current&&(ie(!0),T.current().finally(()=>{T.current=null,ie(!1),H(null)}))},[]),qe=i.useCallback(()=>{T.current=null,H(null)},[]),Ye=i.useCallback(Te=>{R.current=Te,C(Te)},[]);return i.useEffect(()=>{var Te;D.current!==e.id&&(D.current=e.id,k(h||((Te=u[0])==null?void 0:Te.id)||"__custom__"),p(""),g(""),N([]),A(""),j(!1),we(jt().textQuery),X(jt().workspaceQuery),ge(jt().modelQuery),le(jt().resumableOnly),me(jt().sortMode),z.current=null,P(ia(m,t.length,r.length)))},[r.length,t.length,h,m,e.id,u]),i.useEffect(()=>{var Te;b!=="__custom__"&&(b&&u.some(Ue=>Ue.id===b)||k(h||((Te=u[0])==null?void 0:Te.id)||"__custom__"))},[h,b,u]),i.useEffect(()=>{K==="ide"&&m||K==="cli"&&t.length>0||K==="acp"&&r.length>0||P(ia(m,t.length,r.length))},[K,r.length,t.length,m]),{showAllRecent:l,setShowAllRecent:d,hasIdeOptions:m,workspaceRows:u,defaultWorkspaceId:h,workspaceChoice:b,customWorkspacePath:y,browseCurrentPath:x,browseDirectories:f,browseBusy:S,browseError:M,browseDialogOpen:w,activeLauncherKind:K,launchConfirm:W,launchConfirmWorkspaceKeyRef:R,launchConfirmWorkspaceKey:I,launchConfirmArgs:O,launchConfirmModel:E,launchConfirmResumeId:Q,launchConfirmSavedSessions:de,launchConfirmTextFilter:he,launchConfirmWorkspaceFilter:be,launchConfirmModelFilter:ue,launchConfirmResumableOnly:te,launchConfirmSortMode:Ne,filteredLaunchConfirmSavedSessions:Fe,launchConfirmSessionsLoading:pe,launchConfirmBusy:fe,resolvedWorkspacePath:ce,canCreateMissingWorkspace:se,openBrowseDialog:Le,loadBrowsePath:ve,handleWorkspaceChoiceChange:B,chooseCustomWorkspacePath:Ie,setCustomWorkspacePath:p,setBrowseDialogOpen:j,setActiveLauncherKind:P,openLaunchConfirm:Pe,handleConfirmLaunch:He,closeLaunchConfirm:qe,setWorkspaceSelectionFromOption:Ae,setLaunchConfirmWorkspaceKeyAndSync:Ye,setLaunchConfirmArgs:_,setLaunchConfirmModel:U,setLaunchConfirmResumeId:xe,setLaunchConfirmTextFilter:we,setLaunchConfirmWorkspaceFilter:X,setLaunchConfirmModelFilter:ge,setLaunchConfirmResumableOnly:le,setLaunchConfirmSortMode:me}}function Vb({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:c,machineAction:l,isStandalone:d,section:m,showBottomNav:u,onBack:h,onSectionChange:b,onOpenConversation:k,onOpenRecent:y,onOpenMachineDetails:p,onMachineUpgrade:x,onLaunchDetectedIde:g,onAddWorkspace:f,onBrowseDirectory:N,onLaunchWorkspaceProvider:S,onListSavedSessions:v}){const M=I=>I==="ide"?"IDE":I==="cli"?"CLI":"ACP",A=r.slice(0,4),w=t.slice(0,3),j=zb({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:N,onListSavedSessions:v}),K=i.useMemo(()=>A.map(I=>{const{metaText:C,updatedLabel:O}=cd(I);return{key:`recent-launch:${I.id}`,primary:I.label,secondary:C,updatedLabel:O,onClick:()=>{const{options:_,selectedKey:E}=ps({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspacePath:I.workspace});j.openLaunchConfirm({title:I.kind==="ide"?ls("restart-ide",I.label):I.providerSessionId?ko(I.label):ls("start-fresh",I.label),description:I.kind==="ide"?ds("restart-ide"):I.providerSessionId?So():ds("start-fresh"),confirmLabel:I.kind==="ide"?Bs("restart-ide"):I.providerSessionId?pn(!0):Bs("start-fresh"),busyLabel:I.kind==="ide"?Ks("restart-ide"):I.providerSessionId?wo(!0):Ks("start-fresh"),workspaceOptions:_,selectedWorkspaceKey:E,details:[{label:"Mode",value:M(I.kind)},...I.providerType?[{label:"Provider",value:I.providerType}]:[]]},async()=>{const U=_.find(Q=>Q.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption(U),await y({...I,workspace:(U==null?void 0:U.workspacePath)??null})})}}}),[j,y,A]),P=i.useMemo(()=>w.map(I=>({key:`recent-chat:${I.conversation.tabKey}`,primary:lt(I.conversation),secondary:Zp(I.conversation,{timestampLabel:I.timestamp?Kc(I.timestamp):null}),unread:I.unread,onClick:()=>k(I.conversation)})),[k,w]),T=j.showAllRecent?K:K.slice(0,4),W=K.length>0,H=P.length>0,R=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 ${R} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:h,type:"button","aria-label":"Back",children:s.jsx(eo,{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:It(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:P.map(I=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${I.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:I.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:I.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:I.secondary})]},I.key))})]}),W&&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:T.map(I=>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:I.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:I.primary}),I.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:I.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:I.secondary})]},I.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:()=>j.setShowAllRecent(I=>!I),children:j.showAllRecent?"Show fewer":`Show ${K.length-4} more`})})]}),(j.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:j.workspaceChoice,onChange:I=>j.handleWorkspaceChoiceChange(I.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:j.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[j.workspaceRows.map(I=>s.jsxs("option",{value:I.id,children:[I.id===j.defaultWorkspaceId?"⭐ ":"",Nn(I.path,I.label)||I.path]},I.id)),s.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):s.jsx("option",{value:"__custom__",children:"Select workspace…"})}),j.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(xs,{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:j.resolvedWorkspacePath||j.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:j.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:()=>{j.resolvedWorkspacePath&&f(j.resolvedWorkspacePath)},disabled:!j.resolvedWorkspacePath||j.browseBusy,children:"Save as workspace"})]})]}),j.resolvedWorkspacePath&&s.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath})]})}),s.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[j.hasIdeOptions&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${j.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:()=>j.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${j.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:()=>j.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${j.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:()=>j.setActiveLauncherKind("acp"),children:"ACP"})]}),j.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:j.activeLauncherKind==="ide"?"Choose an IDE":j.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),s.jsx("div",{className:"grid grid-cols-1 gap-2",children:j.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(I=>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:C,selectedKey:O}=ps({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspaceId:j.workspaceChoice!=="__custom__"?j.workspaceChoice:null,currentWorkspacePath:j.resolvedWorkspacePath});j.openLaunchConfirm({title:`Launch ${I.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:C,selectedWorkspaceKey:O,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:I.name}]},async()=>{const _=C.find(E=>E.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption(_),g(I.type,{workspacePath:(_==null?void 0:_.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:I.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath||"Use selected workspace"})]},I.type)):(j.activeLauncherKind==="cli"?n:a).map(I=>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 C=j.activeLauncherKind==="cli"?"cli":"acp",{options:O,selectedKey:_}=ps({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspaceId:j.workspaceChoice!=="__custom__"?j.workspaceChoice:null,currentWorkspacePath:j.resolvedWorkspacePath});j.openLaunchConfirm({title:`Launch ${I.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${C.toUpperCase()}`,workspaceOptions:O,selectedWorkspaceKey:_,details:[{label:"Mode",value:C.toUpperCase()},{label:"Provider",value:I.displayName}],showArgsInput:!0,showModelInput:C==="acp",initialArgs:"",initialModel:"",providerType:I.type},async()=>{const E=O.find(U=>U.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption(E),S(C,I.type,{workspaceId:(E==null?void 0:E.workspaceId)??null,workspacePath:(E==null?void 0:E.workspacePath)??null,args:j.launchConfirmArgs,model:j.launchConfirmModel,resumeSessionId:j.launchConfirmResumeId||null})})},children:[s.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[I.icon?`${I.icon} `:"",I.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath||"Use selected workspace"})]},I.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,j.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:()=>f(j.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:x,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:p,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),j.browseDialogOpen&&s.jsx(Pn,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:j.browseCurrentPath,directories:j.browseDirectories,busy:j.browseBusy,error:j.browseError,confirmLabel:"Use this folder",onClose:()=>j.setBrowseDialogOpen(!1),onNavigate:I=>{j.loadBrowsePath(I)},onConfirm:I=>{j.chooseCustomWorkspacePath(I),j.setBrowseDialogOpen(!1)}}),j.launchConfirm&&s.jsx(_o,{title:j.launchConfirm.title,description:j.launchConfirm.description,details:j.launchConfirm.details,workspaceOptions:j.launchConfirm.workspaceOptions,selectedWorkspaceKey:j.launchConfirmWorkspaceKey,onWorkspaceChange:j.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:j.launchConfirm.providerType?pn(!!j.launchConfirmResumeId):j.launchConfirm.confirmLabel,busyLabel:j.launchConfirm.providerType?void 0:j.launchConfirm.busyLabel,busy:j.launchConfirmBusy,showArgsInput:j.launchConfirm.showArgsInput,argsValue:j.launchConfirmArgs,onArgsChange:j.setLaunchConfirmArgs,showModelInput:j.launchConfirm.showModelInput,modelValue:j.launchConfirmModel,onModelChange:j.setLaunchConfirmModel,historyProviderNode:j.launchConfirm.providerType&&(j.launchConfirmSessionsLoading||j.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"}),j.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:jo()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:j.launchConfirmTextFilter,onChange:I=>j.setLaunchConfirmTextFilter(I.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:j.launchConfirmBusy||j.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:j.launchConfirmWorkspaceFilter,onChange:I=>j.setLaunchConfirmWorkspaceFilter(I.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:j.launchConfirmBusy||j.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:j.launchConfirmModelFilter,onChange:I=>j.setLaunchConfirmModelFilter(I.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:j.launchConfirmBusy||j.launchConfirmSessionsLoading}),s.jsxs("select",{value:j.launchConfirmSortMode,onChange:I=>j.setLaunchConfirmSortMode(I.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:j.launchConfirmBusy||j.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:j.launchConfirmResumableOnly,onChange:I=>j.setLaunchConfirmResumableOnly(I.target.checked),disabled:j.launchConfirmBusy||j.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:j.launchConfirmResumeId,onChange:I=>j.setLaunchConfirmResumeId(I.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:j.launchConfirmBusy||j.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:bh()}),j.filteredLaunchConfirmSavedSessions.map(I=>s.jsxs("option",{value:I.providerSessionId,disabled:!I.canResume,children:[I.title||I.providerSessionId," ",I.canResume?"":"(workspace missing)"]},I.providerSessionId))]}),!j.launchConfirmSessionsLoading&&j.launchConfirmSavedSessions.length>0&&j.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),j.launchConfirmResumeId&&(()=>{const I=j.filteredLaunchConfirmSavedSessions.find(O=>O.providerSessionId===j.launchConfirmResumeId);if(!I)return null;const C=id(I);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:C.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:C.providerSessionId}),s.jsx("div",{className:"mt-1",children:C.metaLine}),C.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:C.updatedLabel}),C.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:C.preview})]})})()]}),onConfirm:j.handleConfirmLaunch,onCancel:j.closeLaunchConfirm}),u&&s.jsx(od,{section:m,onSectionChange:b})]})}function Qr(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Gb(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:Qr(e)}function qb(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 Yb(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:bs(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;const a=br(n)?"cli":Ms(n)?"acp":"ide",o=bs(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(br(n)?n.cliName||n.type:Ms(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Ms(n)?o||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:n.lastMessageAt||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function Xb(e,t){const r=new Map;for(const n of t){const a=ws(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((h,b)=>b.timestamp-h.timestamp)[0]||null,c=(o==null?void 0:o.conversation)||null,l=Pa(n),d=a.filter(h=>h.unread||h.requiresAction).length,m=qb(n),u=[n.platform||"machine",m].filter(Boolean);return{id:n.id,label:It(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?eh(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 Jb(e){return e==="chat"}function Wr(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 Qb({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:o,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:b,onRequestedMobileSectionConsumed:k,setSelectedTabKey:y,setScreen:p,setSelectedMachineId:x,setSection:g,setMachineBackTarget:f,resetMachineAction:N}){const S=i.useRef(null),v=i.useCallback(M=>{if(!(M!=null&&M.sessionId))return;const A=cn(M,c),w=Math.max(Date.now(),fs(M),A.lastUpdated||0);Wr("mark_read:start",{tabKey:M.tabKey,sessionId:M.sessionId,displayPrimary:lt(M),inboxBucket:A.inboxBucket,unread:A.unread,lastSeenAt:A.lastSeenAt,lastUpdated:A.lastUpdated,activityAt:fs(M),readAt:w}),l(ws(M)||M.routeId,"mark_session_seen",{sessionId:M.sessionId,providerSessionId:M.providerSessionId,seenAt:w,completionMarker:A.completionMarker}).then(j=>{Wr("mark_read:result",{tabKey:M.tabKey,sessionId:M.sessionId,result:j})}).catch(j=>{Wr("mark_read:error",{tabKey:M.tabKey,sessionId:M.sessionId,error:j instanceof Error?j.message:String(j)})})},[c,l]);return i.useEffect(()=>{var A;if(!n){Jb(o)&&p("inbox"),y(((A=e[0])==null?void 0:A.tabKey)||null),S.current=null;return}if(o!=="chat"){S.current=null;return}const M=`${n.tabKey}:${n.sessionId||""}`;S.current!==M&&(S.current=M,v(n))},[e,v,o,n,p,y]),i.useEffect(()=>{if(!d)return;const M=e.find(A=>A.tabKey===d);M&&(y(M.tabKey),p("chat"),m==null||m())},[e,m,d,p,y]),i.useEffect(()=>{if(!u)return;const M=t.find(A=>A.id===u);M&&(x(M.id),N(),g("machines"),f("inbox"),p("machine"),h==null||h())},[t,h,u,N,f,p,g,x]),i.useEffect(()=>{b&&(g(b),p("inbox"),k==null||k())},[k,b,p,g]),i.useEffect(()=>{const M=r.filter(A=>A.inboxBucket==="task_complete"||A.unread);M.length!==0&&Wr("inbox_state",{screen:o,selectedTabKey:a,items:M.map(A=>{const w=cn(A.conversation,c);return{liveState:w,tabKey:A.conversation.tabKey,sessionId:A.conversation.sessionId,displayPrimary:lt(A.conversation),serverBucket:w.inboxBucket,computedBucket:A.inboxBucket,serverUnread:w.unread,computedUnread:A.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,activityAt:fs(A.conversation)}})})},[r,c,o,a]),{markConversationRead:v}}function Zb(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function zi(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function eg(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function tg({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const[a,o]=i.useState("idle"),[c,l]=i.useState(""),[d,m]=i.useState(null),u=i.useCallback(()=>{o("idle"),l(""),m(null)},[]),h=i.useCallback(async(f,N,S)=>{var v;try{o("loading"),l(`Launching ${N}…`);const M={ideType:N,enableCdp:!0};(v=S==null?void 0:S.workspacePath)!=null&&v.trim()&&(M.workspace=S.workspacePath.trim()),await e(f,"launch_ide",M),o("done"),l(`${N} launch requested`)}catch(M){o("error"),l(M instanceof Error?M.message:"Launch IDE failed"),console.error("Launch IDE failed",M)}},[e]),b=i.useCallback(async(f,N,S)=>{if(N.trim())try{o("loading"),l(S!=null&&S.createIfMissing?"Creating folder…":"Saving workspace…");const v=await e(f,"workspace_add",{path:N.trim(),createIfMissing:(S==null?void 0:S.createIfMissing)===!0});if(v!=null&&v.success){o("done"),l(S!=null&&S.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}o("error"),l((v==null?void 0:v.error)||"Could not save workspace")}catch(v){o("error"),l(v instanceof Error?v.message:"Could not save workspace")}},[e]),k=i.useCallback(async f=>{var N,S,v,M,A,w;try{o("loading"),l("Starting daemon upgrade…");const j=await e(f,"daemon_upgrade",{});if((N=j==null?void 0:j.result)!=null&&N.alreadyLatest){o("done"),l(`Already on v${((S=j==null?void 0:j.result)==null?void 0:S.version)||"latest"}.`);return}if((v=j==null?void 0:j.result)!=null&&v.upgraded||(M=j==null?void 0:j.result)!=null&&M.success){o("done"),l(`Upgrade to v${((A=j==null?void 0:j.result)==null?void 0:A.version)||"latest"} started. Daemon is restarting…`);return}o("error"),l(((w=j==null?void 0:j.result)==null?void 0:w.error)||"Upgrade failed")}catch(j){o("error"),l(j instanceof Error?j.message:"Upgrade failed")}},[e]),y=i.useCallback(async(f,N,S,v)=>{var w,j,K;const M=Date.now(),A={machineId:f,kind:N,providerType:S,workspaceId:(v==null?void 0:v.workspaceId)||null,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,startedAt:M};try{o("loading"),l(`Launching ${S}…`),m(A);const P={cliType:S};(w=v==null?void 0:v.workspacePath)!=null&&w.trim()?P.dir=v.workspacePath.trim():v!=null&&v.workspaceId&&(P.workspaceId=v.workspaceId),v!=null&&v.resumeSessionId&&(P.resumeSessionId=v.resumeSessionId),(j=v==null?void 0:v.args)!=null&&j.trim()&&(P.cliArgs=v.args.trim().split(/\s+/).filter(Boolean)),(K=v==null?void 0:v.model)!=null&&K.trim()&&(P.initialModel=v.model.trim());const T=await e(f,"launch_cli",P),W=(T==null?void 0:T.result)||T,H=(W==null?void 0:W.sessionId)||(W==null?void 0:W.id);if(T!=null&&T.success&&H){m(null),o("done"),l(`${S} launched`),t(Zt(H));return}if(T!=null&&T.success){o("loading"),l(`${S} launch requested — waiting for session…`);return}m(null),o("error"),l((T==null?void 0:T.error)||(W==null?void 0:W.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(P){if(eg(P)){o("loading"),l(`${S} launch requested — waiting for session…`);return}m(null),o("error"),l(P instanceof Error?P.message:`Could not launch ${N.toUpperCase()} workspace`)}},[t,e]),p=i.useCallback(async(f,N)=>{try{const S=await e(f,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),v=(S==null?void 0:S.result)??S;return Array.isArray(v==null?void 0:v.sessions)?v.sessions:[]}catch(S){return console.error("Failed to list saved sessions on mobile:",S),[]}},[e]),x=i.useCallback(async(f,N)=>Rn(e,f,N),[e]);i.useEffect(()=>{if(!d)return;const f=zi(d.workspacePath),N=r.find(v=>{var P,T,W,H;if(!v||v.type==="adhdev-daemon"||Zb(v.daemonId||v.id)!==d.machineId||(v.transport==="acp"?"acp":v.transport==="pty"?"cli":null)!==d.kind||String(v.agentType||v.type||"")!==d.providerType)return!1;const j=String(v.providerSessionId||"");if(d.resumeSessionId&&j)return j===d.resumeSessionId;if(f){const R=zi(v.workspace||v.runtimeWorkspaceLabel);return R?R===f:!1}return Number(v.lastUpdated||v._lastUpdate||v.timestamp||((H=(W=(T=(P=v.activeChat)==null?void 0:P.messages)==null?void 0:T.at)==null?void 0:W.call(T,-1))==null?void 0:H.timestamp)||0)>=d.startedAt-5e3});if(!N)return;const S=sd({entrySessionId:N.sessionId,entryInstanceId:N.instanceId,entryRouteId:N.id,conversations:n});S&&(m(null),o("done"),l(`${d.providerType} launched`),t(Zt(S)))},[n,r,t,d]),i.useEffect(()=>{if(!d)return;const f=window.setTimeout(()=>{m(N=>!N||N.startedAt!==d.startedAt?N:(o("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(f)},[d]);const g=i.useCallback(async(f,N)=>{if(N.kind==="ide"&&N.providerType){await h(f,N.providerType,{workspacePath:N.workspace||null});return}(N.kind==="cli"||N.kind==="acp")&&N.providerType&&await y(f,N.kind,N.providerType,{workspacePath:N.workspace||null,resumeSessionId:N.providerSessionId||null})},[h,y]);return{machineAction:{state:a,message:c},resetMachineAction:u,handleLaunchDetectedIde:h,handleAddWorkspace:b,handleMachineUpgrade:k,handleLaunchWorkspaceProvider:y,handleListSavedSessions:p,handleBrowseDirectory:x,handleOpenRecent:g}}function sg({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:o,setScreen:c,setSelectedMachineId:l,setSection:d,setMachineBackTarget:m}){const u=i.useCallback(g=>{o(g.tabKey),c("chat"),n(g)},[n,c,o]),h=i.useCallback(g=>{const f=e.find(N=>N.routeId===g.routeId&&N.streamSource==="native");f&&(o(f.tabKey),c("chat"),n(f))},[e,n,c,o]),b=i.useCallback(()=>{n(t),c("inbox")},[n,t,c]),k=i.useCallback((g,f="inbox")=>{l(g),a(),d("machines"),m(f),c("machine")},[a,m,c,d,l]),y=i.useCallback(g=>{const f=ws(g);f&&k(f,"chat")},[k]),p=i.useCallback(()=>{a(),c(r)},[r,a,c]),x=i.useCallback(g=>{d(g),c("inbox")},[c,d]);return{openConversation:u,openNativeConversation:h,backFromConversation:b,openMachine:k,openConversationMachine:y,backFromMachine:p,changeMachineSection:x}}function ys(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function rg(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function ng({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,userName:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:b,onRequestedMobileSectionConsumed:k,onOpenHistory:y,onOpenRemote:p,onStopCli:x,wsStatus:g,isConnected:f,onShowAllHiddenConversations:N,onHideConversation:S,onOpenNewSession:v,liveSessionInboxState:M,setCliViewModeOverrides:A}){const[w,j]=i.useState(()=>{var q;return((q=e[0])==null?void 0:q.tabKey)||null}),[K,P]=i.useState(()=>e[0]?"chat":"inbox"),[T,W]=i.useState("chats"),[H,R]=i.useState(null),[I,C]=i.useState("inbox"),O=i.useRef([]),_=Ws(),E="0.9.79",U=i.useMemo(()=>e.find(q=>q.tabKey===w)||e[0]||null,[e,w]),Q=i.useMemo(()=>U?r.find(q=>q.id===U.routeId):void 0,[r,U]),xe=i.useMemo(()=>!U||et(U)||!st(U)?null:Hs(U),[U]),de=i.useMemo(()=>r.filter(q=>q.type==="adhdev-daemon").sort(uo),[r]),Z=i.useMemo(()=>de.find(q=>q.id===H)||null,[de,H]),he=In({sendDaemonCommand:a,activeConv:U||void 0,setActionLogs:o,isStandalone:c}),we=tg({sendDaemonCommand:a,navigate:_,ides:r,conversations:e}),be=i.useMemo(()=>e.map(q=>{const ke=K==="chat"&&(U==null?void 0:U.tabKey)===q.tabKey,ve=Sn(q,M,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ke}),Le=fs(q),Ae=hl(q);return{conversation:q,timestamp:Le,preview:Ae,unread:ve.unread,requiresAction:ve.requiresAction,isWorking:ve.isWorking,inboxBucket:ve.inboxBucket}}),[e,M,K,U]),{markConversationRead:X}=Qb({conversations:e,machineEntries:de,items:be,selectedConversation:U,selectedTabKey:w,screen:K,liveSessionInboxState:M,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:b,onRequestedMobileSectionConsumed:k,setSelectedTabKey:j,setScreen:P,setSelectedMachineId:R,setSection:W,setMachineBackTarget:C,resetMachineAction:we.resetMachineAction}),ue=sg({conversations:e,selectedConversation:U,machineBackTarget:I,markConversationRead:X,resetMachineAction:we.resetMachineAction,setSelectedTabKey:j,setScreen:P,setSelectedMachineId:R,setSection:W,setMachineBackTarget:C}),ge=i.useMemo(()=>Qr(be.filter(q=>q.requiresAction)),[be]),te=i.useMemo(()=>Qr(be.filter(q=>q.unread&&!q.requiresAction)),[be]),le=i.useMemo(()=>Gb(be.filter(q=>!q.unread&&!q.requiresAction&&q.isWorking),O.current),[be]);i.useEffect(()=>{O.current=le.map(q=>q.conversation.tabKey)},[le]);const Ne=i.useMemo(()=>Qr(be.filter(q=>!q.unread&&!q.requiresAction&&!q.isWorking)),[be]),me=i.useMemo(()=>Z?be.filter(q=>ws(q.conversation)===Z.id):[],[be,Z]),pe=i.useMemo(()=>Yb(Z,r),[r,Z]),oe=(Z==null?void 0:Z.version)||null,fe=!!Z&&!!oe&&!0&&oe!==E,ie=i.useMemo(()=>(Z==null?void 0:Z.availableProviders)||[],[Z]),D=i.useMemo(()=>ie.filter(q=>ys(q,"cli")).map(q=>({type:q.type,displayName:q.displayName||q.type,icon:q.icon})),[ie]),z=i.useMemo(()=>ie.filter(q=>ys(q,"acp")).map(q=>({type:q.type,displayName:q.displayName||q.type,icon:q.icon})),[ie]),ce=i.useMemo(()=>Xb(de,be),[be,de]),se=i.useCallback(async q=>{Z&&await we.handleOpenRecent(Z.id,q)},[we,Z]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:K==="chat"&&U?s.jsx($b,{selectedConversation:U,isAcp:et(U),isStandalone:c,selectedIdeEntry:Q,actionLogs:n,userName:l,isSendingChat:he.isSendingChat,sendFeedbackMessage:he.sendFeedbackMessage,isFocusingAgent:he.isFocusingAgent,handleModalButton:he.handleModalButton,handleRelaunch:he.handleRelaunch,onBack:ue.backFromConversation,onOpenNativeConversation:ue.openNativeConversation,onOpenMachine:ue.openConversationMachine,onOpenHistory:y,onOpenRemote:p,onStopCli:x,cliViewMode:xe,onSetCliViewMode:async q=>{await Hl({conversation:U,mode:q,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:A})},handleSendChat:he.handleSendChat,handleFocusAgent:he.handleFocusAgent}):K==="machine"&&Z?s.jsx(Vb,{selectedMachineEntry:Z,selectedMachineConversations:me,selectedMachineRecentLaunches:pe,cliProviders:D,acpProviders:z,selectedMachineNeedsUpgrade:fe,appVersion:E,machineAction:we.machineAction,isStandalone:c,section:T,showBottomNav:I==="inbox",onBack:ue.backFromMachine,onSectionChange:ue.changeMachineSection,onOpenConversation:ue.openConversation,onOpenRecent:se,onOpenMachineDetails:()=>_(`/machines/${Z.id}`),onMachineUpgrade:()=>we.handleMachineUpgrade(Z.id),onLaunchDetectedIde:(q,ke)=>we.handleLaunchDetectedIde(Z.id,q,ke),onAddWorkspace:(q,ke)=>we.handleAddWorkspace(Z.id,q,ke),onBrowseDirectory:q=>we.handleBrowseDirectory(Z.id,q),onLaunchWorkspaceProvider:(q,ke,ve)=>we.handleLaunchWorkspaceProvider(Z.id,q,ke,ve),onListSavedSessions:q=>we.handleListSavedSessions(Z.id,q)}):s.jsx(Ob,{section:T,attentionItems:ge,unreadItems:te,workingItems:le,completedItems:Ne,hiddenConversations:t,machineCards:ce,getAvatarText:rg,actionLogs:n,sendDaemonCommand:a,onOpenConversation:ue.openConversation,onShowAllHidden:N,onHideConversation:S,onOpenNewSession:v,onOpenMachine:ue.openMachine,onOpenSettings:()=>_("/settings"),onSectionChange:W,wsStatus:g,isConnected:f,isStandalone:c})})}function ca(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function ag({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:o}){const c=i.useRef(0),[l,d]=i.useState(!1),[m,u]=i.useState(null),h=i.useCallback(()=>{c.current=0,d(!1),u(null)},[]);i.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const b=i.useCallback(x=>{x.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,d(!0))},[]),k=i.useCallback(x=>{if(!x.dataTransfer.types.includes("text/tab-key"))return;if(x.preventDefault(),!ca(t,r)){u("merge");return}const g=x.currentTarget.getBoundingClientRect(),f=x.clientX-g.left,N=g.width/3;f<N?u("split-left"):f>N*2?u("split-right"):u("merge")},[t,r]),y=i.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,d(!1),u(null))},[]),p=i.useCallback(x=>{c.current=0,d(!1);const g=x.dataTransfer.getData("text/tab-key"),f=g?e.some(S=>S.tabKey===g):!1,N=m;if(u(null),o(),!!g){if(x.preventDefault(),N==="split-left"&&ca(t,r)){r==null||r(g,"split-left");return}if(N==="split-right"&&ca(t,r)){r==null||r(g,"split-right");return}if(f){a(g);return}n==null||n(g)}},[e,m,t,r,n,a,o]);return{dragOver:l,dropAction:m,resetDragState:h,handleDragEnter:b,handleDragOver:k,handleDragLeave:y,handleDrop:p}}function og(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 ig({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[o,c]=i.useState(t??null),[l,d]=i.useState(r??[]),[m,u]=i.useState(null),h=i.useRef(null),b=i.useRef(null),k=i.useRef(n),y=i.useRef(a);i.useEffect(()=>{k.current=n},[n]),i.useEffect(()=>{y.current=a},[a]),i.useEffect(()=>{t&&t!==o&&c(t)},[t,o]),i.useEffect(()=>{d(A=>{const w=og(A,e);return w.length===A.length&&w.every((j,K)=>j===A[K])?A:w})},[e]);const p=i.useMemo(()=>{const A=m??l;if(A.length===0)return e;const w=new Map(A.map((j,K)=>[j,K]));return[...e].sort((j,K)=>{const P=w.get(j.tabKey)??999,T=w.get(K.tabKey)??999;return P-T})},[e,m,l]);i.useEffect(()=>{var w,j;if(p.length===0){o!==null&&(c(null),(w=k.current)==null||w.call(k,null));return}if(o&&p.some(K=>K.tabKey===o))return;const A=p[0].tabKey;A!==o&&(c(A),(j=k.current)==null||j.call(k,A))},[p,o]);const x=i.useMemo(()=>p.find(A=>A.tabKey===o),[p,o]),g=i.useCallback(A=>{var w;c(A),(w=k.current)==null||w.call(k,A)},[]),f=i.useCallback((A,w,j)=>{d(K=>{var H;const P=K.filter(R=>R!==A),T=P.indexOf(w);if(T<0)return K;const W=j==="left"?T:T+1;return P.splice(W,0,A),(H=y.current)==null||H.call(y,P),P}),u(null)},[]),N=i.useCallback((A,w,j)=>{const P=(l.length>0?l:e.map(H=>H.tabKey)).filter(H=>H!==A),T=P.indexOf(w);if(T<0)return;const W=j==="left"?T:T+1;P.splice(W,0,A),h.current=P,u(P)},[l,e]),S=i.useCallback(()=>{var w;const A=h.current;A&&(d(A),(w=y.current)==null||w.call(y,A))},[]),v=i.useCallback(()=>{h.current=null,u(null)},[]),M=i.useCallback(A=>{d(w=>{var K;const j=w.filter(P=>P!==A);return j.push(A),(K=y.current)==null||K.call(y,j),j})},[]);return{activeTabId:o,activeConv:x,sortedConversations:p,previewOrderRef:h,draggingTabRef:b,selectTab:g,handleTabReorder:f,updatePreviewOrder:N,commitPreviewOrder:S,clearPreviewOrder:v,moveTabToEnd:M,setDraggingTabKey:A=>{b.current=A}}}function cg({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 Do({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",m=n?yl: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:m}),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:Bt,"aria-label":Bt,children:[s.jsx(Ac,{size:14}),s.jsx("span",{children:Bt})]})}),c&&s.jsx(ad,{}),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 ld="adhdev-tab-shortcuts";function dd(){try{return JSON.parse(localStorage.getItem(ld)||"{}")}catch{return{}}}function ud({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,c]=i.useState(()=>dd()),[l,d]=i.useState(null),m=i.useCallback(h=>{const b=[];return h.metaKey&&b.push(a?"⌘":"Meta"),h.ctrlKey&&b.push("Ctrl"),h.altKey&&b.push(a?"⌥":"Alt"),h.shiftKey&&b.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(b.push(h.key.length===1?h.key.toUpperCase():h.key),b.join("+"))},[a]),u=i.useCallback(h=>{c(h);try{localStorage.setItem(ld,JSON.stringify(h))}catch{}},[]);return i.useEffect(()=>{if(!e||!l)return;const h=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){d(null);return}const k=m(b);if(!k)return;const y={...o};for(const[p,x]of Object.entries(y))x===k&&delete y[p];y[l]=k,u(y),d(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,l,o,u,m]),i.useEffect(()=>{if(!e)return;const h=b=>{if(!(!b.ctrlKey&&!b.metaKey&&!b.altKey)){for(const[k,y]of Object.entries(o))if(t.includes(k)&&m(b)===y){b.preventDefault(),r(),n(k);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,o,t,r,n,m]),{isMac:a,tabShortcuts:o,shortcutListening:l,setShortcutListening:d,saveShortcuts:u}}const la=e=>{e.preventDefault()},lg=i.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:o,conversationKeys:c,draggingTabRef:l,onFocus:d,onSelectTab:m,onConversationActivated:u,onPreviewReorder:h,onReorderTab:b,onCommitPreviewOrder:k,onClearPreviewOrder:y,onDragStateReset:p,onDragTabKeyChange:x,onReceiveTab:g,onOpenContextMenu:f,longPressTimer:N,isGroupActive:S}){const v=Fs(t),M=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",A=v.isReconnecting,w=i.useCallback(C=>{l.current=t.tabKey,x(t.tabKey),C.dataTransfer.setData("text/tab-key",t.tabKey),C.dataTransfer.effectAllowed="move"},[t.tabKey,l,x]),j=i.useCallback(()=>{l.current=null,x(null),k(),y(),p()},[l,x,k,y,p]),K=i.useCallback(C=>{const O=l.current;if(!(!O||O===t.tabKey)&&C.dataTransfer.types.includes("text/tab-key")){C.preventDefault(),C.stopPropagation();const _=C.currentTarget.getBoundingClientRect(),E=C.clientX<_.left+_.width/2?"left":"right";h(O,t.tabKey,E)}},[t.tabKey,l,h]),P=i.useCallback(C=>{C.preventDefault(),C.stopPropagation();const O=C.dataTransfer.getData("text/tab-key");if(O&&O!==t.tabKey){const _=C.currentTarget.getBoundingClientRect(),E=C.clientX<_.left+_.width/2?"left":"right";c.includes(O)?b(O,t.tabKey,E):g&&g(O)}y()},[t.tabKey,c,b,g,y]),T=i.useCallback(C=>{C.stopPropagation(),d(),m(t.tabKey),u(t)},[t,u,d,m]),W=i.useCallback(C=>{C.preventDefault(),f(C.clientX,C.clientY,t.tabKey)},[t.tabKey,f]),H=i.useCallback(C=>{const O=C.touches[0];N.current=setTimeout(()=>{f(O.clientX,O.clientY,t.tabKey)},600)},[t.tabKey,N,f]),R=i.useCallback(()=>{N.current&&clearTimeout(N.current)},[N]),I=["adhdev-dockview-tab",M,r&&"is-active",S&&"is-group-active",A&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:I,draggable:!0,onDragStart:w,onDragEnd:j,onDragOver:K,onDrop:P,onClick:T,onContextMenu:W,onTouchStart:H,onTouchEnd:R,onTouchMove:R,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:v.isGenerating?s.jsx("div",{className:"tab-spinner"}):v.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):A?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):v.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:lt(t),children:lt(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[A?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:cs(t)}):v.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[cs(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:cs(t)}),s.jsx($s,{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 dg({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:o,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:h,onDragStateReset:b,onDragTabKeyChange:k,onReceiveTab:y,onHideTab:p,isGroupActive:x,allowTabShortcuts:g=!0}){const[f,N]=i.useState(null),S=i.useRef(null),v=i.useRef(null),M=i.useMemo(()=>e.map(W=>W.tabKey),[e]);vr("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(f==null?void 0:f.tabKey)||null});const{isMac:A,tabShortcuts:w,shortcutListening:j,setShortcutListening:K,saveShortcuts:P}=ud({enabled:g,sortedTabKeys:e.map(W=>W.tabKey),onFocus:o,onSelectTab:c});i.useEffect(()=>{if(!f)return;const W=H=>{const R=document.querySelector("[data-pane-context-menu]");R&&R.contains(H.target)||N(null)};return window.addEventListener("mousedown",W,!0),()=>window.removeEventListener("mousedown",W,!0)},[f]),i.useEffect(()=>{const W=v.current;if(!W)return;const H=R=>{Math.abs(R.deltaY)<=Math.abs(R.deltaX)||(R.preventDefault(),W.scrollLeft+=R.deltaY)};return W.addEventListener("wheel",H,{passive:!1}),()=>W.removeEventListener("wheel",H)},[]);const T=i.useCallback((W,H,R)=>{N({x:W,y:H,tabKey:R})},[]);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:v,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(W=>s.jsx(lg,{conv:W,isActive:t===W.tabKey,isDraggedTab:a.current===W.tabKey,isTaskCompleteUnread:n.has(W.tabKey),shortcut:g?w[W.tabKey]:void 0,conversationKeys:M,draggingTabRef:a,onFocus:o,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:h,onDragStateReset:b,onDragTabKeyChange:k,onReceiveTab:y,onOpenContextMenu:T,longPressTimer:S,isGroupActive:x},W.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),f&&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:f.x,top:f.y},children:[g&&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:la,onClick:W=>{W.stopPropagation(),K(f.tabKey),N(null)},children:["⌨ ",w[f.tabKey]?`Change shortcut (${w[f.tabKey]})`:"Set shortcut"]}),w[f.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:la,onClick:()=>{const W={...w};delete W[f.tabKey],P(W),N(null)},children:"✕ Remove shortcut"})]}),p&&s.jsxs(s.Fragment,{children:[g&&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:la,onClick:()=>{p(f.tabKey),N(null)},children:"🚫 Hide from Dashboard"})]})]}),g&&j&&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:W=>W.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. ",A?"⌘+1":"Ctrl+1",", ",A?"⌥+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 ug({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,hasRegisteredMachines:l,userName:d,groupIndex:m,onFocus:u,isSplitMode:h,numGroups:b,onMoveTab:k,onReceiveTab:y,style:p,onActiveTabChange:x,initialActiveTabId:g,initialTabOrder:f,onTabOrderChange:N,onHideTab:S,isFocused:v,allowTabShortcuts:M=!0,onOpenNewSession:A,liveSessionInboxState:w}){const{sendCommand:j}=gt(),K=i.useRef(null),{activeTabId:P,activeConv:T,sortedConversations:W,draggingTabRef:H,selectTab:R,handleTabReorder:I,updatePreviewOrder:C,commitPreviewOrder:O,clearPreviewOrder:_,moveTabToEnd:E,setDraggingTabKey:U}=ig({conversations:e,initialActiveTabId:g,initialTabOrder:f,onActiveTabChange:x,onTabOrderChange:N}),Q=In({sendDaemonCommand:a,activeConv:T,setActionLogs:o,isStandalone:c}),{dragOver:xe,dropAction:de,resetDragState:Z,handleDragEnter:he,handleDragOver:we,handleDragLeave:be,handleDrop:X}=ag({conversations:e,numGroups:b,onMoveTab:k,onReceiveTab:y,onOwnTabDrop:E,onClearPreviewOrder:_}),ue=T&&!et(T)&&Hs(T)==="terminal",ge=i.useMemo(()=>T?t.find(me=>me.id===T.routeId):void 0,[t,T]),te=i.useMemo(()=>T?n.filter(me=>me.routeId===T.tabKey):[],[n,T]),le=i.useMemo(()=>new Set(W.filter(me=>Wm(me,w,{isOpenConversation:me.tabKey===P})).map(me=>me.tabKey)),[P,w,W]);vr("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:P,dragOver:xe});const Ne=i.useCallback(me=>{me.streamSource==="agent-stream"&&me.agentType&&j(me.routeId,tl(),{agentType:me.agentType,...me.sessionId&&{targetSessionId:me.sessionId}}).catch(()=>{})},[j]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...p,outline:xe?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(dg,{conversations:W,activeTabId:P,groupIndex:m,numGroups:b,unreadTabKeys:le,draggingTabRef:H,onFocus:u,onSelectTab:R,onConversationActivated:Ne,onPreviewReorder:C,onReorderTab:I,onCommitPreviewOrder:O,onClearPreviewOrder:_,onDragStateReset:Z,onDragTabKeyChange:U,onMoveTab:k,onReceiveTab:y,onHideTab:S,isGroupActive:v??!1,allowTabShortcuts:M}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:he,onDragOver:we,onDragLeave:be,onDrop:X,children:[xe&&s.jsx(cg,{dropAction:de,canSplit:!!(b<4&&k)}),T?s.jsx(Po,{activeConv:T,clearToken:r[T.tabKey]||0,isCliTerminal:!!ue,ideEntry:ge,terminalRef:K,handleModalButton:Q.handleModalButton,handleRelaunch:Q.handleRelaunch,handleSendChat:Q.handleSendChat,isSendingChat:Q.isSendingChat,sendFeedbackMessage:Q.sendFeedbackMessage,handleFocusAgent:Q.handleFocusAgent,isFocusingAgent:Q.isFocusingAgent,actionLogs:te,userName:d,isInputActive:!h||!!v}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(Do,{conversationsCount:e.length,isSplitMode:h,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:A})})]})]})}function mg({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:o,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:h,userName:b,focusedGroup:k,focusGroup:y,moveTabToGroup:p,splitTabRelative:x,closeGroup:g,handleResizeStart:f,groupActiveTabIds:N,setGroupActiveTab:S,groupTabOrders:v,setGroupTabOrder:M,toggleHiddenTab:A,onOpenNewSession:w,allowTabShortcuts:j=!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((P,T)=>{const W=t&&n.length===r?`${n[T]}%`:void 0;return s.jsxs(Ct.Fragment,{children:[t&&T>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=>f(T-1,H),onDoubleClick:()=>g(T),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(ug,{style:t?{flexBasis:W??`${100/r}%`,flexGrow:W?0:1,flexShrink:W?0:1}:void 0,conversations:P,clearedTabs:o,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:h,userName:b,groupIndex:T,isFocused:t&&k===T,onFocus:()=>y(T),isSplitMode:t,numGroups:r,onMoveTab:(H,R)=>{R==="left"&&T>0?p(H,T-1):R==="right"&&T<r-1?p(H,T+1):R==="split-left"&&r<4?x(H,T,"left"):R==="split-right"&&r<4&&x(H,T,"right")},onReceiveTab:H=>p(H,T),onActiveTabChange:H=>S(T,H),initialActiveTabId:N[T],initialTabOrder:v[T],onTabOrderChange:H=>M(T,H),onHideTab:A,onOpenNewSession:w,allowTabShortcuts:j,liveSessionInboxState:K})]},T)})})}function md({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,o]=i.useState(null),[c,l]=i.useState(null);i.useEffect(()=>e?ut.onScreenshot("ide-page",(u,h)=>{if(u!==e)return;const b=new FileReader;b.onload=()=>o(b.result),b.readAsDataURL(h)}):void 0,[e]),i.useEffect(()=>{r!=="connected"&&o(null)},[r]),i.useEffect(()=>{var u;return e?((u=ut.onStatus)==null?void 0:u.call(ut,(h,b)=>{h===e&&b!=null&&b.screenshotUsage&&l(b.screenshotUsage)}))||(()=>{}):void 0},[e]),i.useEffect(()=>{o(null)},[e,t]),i.useEffect(()=>{const m=e?ut.get(e):null;if(!(!m||r!=="connected"))return n!=="chat"&&t?m.startScreenshots(t):m.stopScreenshots(t),()=>{m.stopScreenshots(t)}},[n,r,t,e]);const d=i.useCallback(async(m,u)=>{const h=e?ut.get(e):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(m,u,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:d}}const fd="adhdev-dashboard-action-shortcuts",fg=1200,pg=[["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 hg(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function at(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 pd(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:at("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:at("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:at("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:at("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:at("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:at("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:at("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:at("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:at("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:at("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:at("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:at("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:at("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:at("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:at("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:at("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:at("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:at("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:at("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:at("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:at("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:at("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:at("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:at("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:at("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:at("toggleCliView",e)}]}function Va(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function yn(e){const t=Object.fromEntries(pd(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(fd)||"{}"),n={...t,...r};for(const[a,o]of pg)n[a]===o&&(n[a]=t[a]);return n}catch{return t}}function hd(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function xg({enabled:e=!0,onTrigger:t}){const r=hg(),[n,a]=i.useState(()=>yn(r)),[o,c]=i.useState(null),[l,d]=i.useState([]),m=i.useRef({parts:[],timer:null}),u=i.useCallback(p=>{const x=[];return p.metaKey&&x.push(r?"⌘":"Meta"),p.ctrlKey&&x.push("Ctrl"),p.altKey&&x.push(r?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&x.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(x.push(hd(p.key)),x.join("+"))},[r]),h=i.useCallback(p=>{a(p);try{localStorage.setItem(fd,JSON.stringify(p))}catch{}},[]);i.useEffect(()=>{const p=yn(r),x=Object.entries(n),g=Object.entries(p);x.length===g.length&&x.every(([f,N])=>p[f]===N)||h(p)},[n,r,h]);const b=i.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),k=i.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},fg))},[]);i.useEffect(()=>{if(!o)return;const p=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){c(null),d([]);return}const g=u(x);if(!g)return;const N=!(x.metaKey||x.ctrlKey||x.altKey)&&/^[A-Z0-9]$/.test(g);if(l.length===0&&N){d([g]);return}const v=[...l,g].slice(0,2).join(" "),M={...n};for(const[A,w]of Object.entries(M))w===v&&delete M[A];M[o]=v,h(M),c(null),d([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,u,h,o,l]),i.useEffect(()=>{if(!e||o)return;const p=x=>{if(x.defaultPrevented)return;const g=u(x);if(!g)return;const f=x.metaKey||x.ctrlKey||x.altKey;if(Va(x.target))return;const N=m.current.parts,S=f?[g]:[...N.slice(-1),g].slice(-2),v=S.join(" "),M=S[S.length-1],A=Object.entries(n).filter(([,T])=>!!T),w=A.find(([,T])=>T===v);if(w){x.preventDefault(),b(),t(w[0]);return}if(A.some(([,T])=>T.startsWith(`${v} `))){x.preventDefault(),m.current.parts=S,k();return}const K=A.find(([,T])=>T===M);if(K){x.preventDefault(),b(),t(K[0]);return}if(A.some(([,T])=>T.startsWith(`${M} `))){x.preventDefault(),m.current.parts=[M],k();return}b()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,k,e,u,t,b,o]),i.useEffect(()=>()=>b(),[b]);const y=i.useMemo(()=>pd(r),[r]);return{isMac:r,actionDefinitions:y,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:d,saveShortcuts:h}}function bg({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 xd(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Vi({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!xd(n):!0}function gg({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:xd(r)}const bd=1e3,yg=4;function Gi(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function qi(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function vg({detachDelayMs:e=bd,stillnessThresholdPx:t=yg,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,c=null,l=null,d=null,m=null,u=!1;const h=()=>{m!=null&&(a(m),m=null)},b=()=>{h(),l=null},k=()=>{h(),o=null,c=null,l=null,d=null,u=!1},y=()=>{!o||!l||!d||u||m!=null||(m=n(()=>{m=null,!(!o||!l||!d||u)&&Gi(d,c)&&(qi(l,d,t)||(u=!0,r({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},p=g=>{if(!(!o||u)){if(!Gi(g,c)){d={clientX:g.clientX,clientY:g.clientY},b();return}(!l||qi(l,g,t))&&(h(),l={clientX:g.clientX,clientY:g.clientY}),d={clientX:g.clientX,clientY:g.clientY},y()}},x=g=>{!o||u||(g&&(d={clientX:g.clientX,clientY:g.clientY}),b())};return{startDrag:g=>{h(),o=g.panelId,c=g.selfPanelBounds??null,l=null,d={clientX:g.clientX,clientY:g.clientY},u=!1},markSelfPanel:p,markNonSelfPanel:x,markNoDropTarget:x,markDockTarget:x,endDrag:k,isDragging:()=>o!=null,hasDetached:()=>u,dispose:k}}function wg(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Fr(e){return e.isActive}function Yi(e){return e.isVisible}const gd=i.createContext(null);function _n(){const e=i.useContext(gd);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Zr(e){return lt(e)||e.tabKey}function jg(e){return`remote:${e}`}function Pt(e){return e.startsWith("remote:")}function Xi(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function kg(e){e.preventDefault()}function da(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 ua(e,t){e.classList.remove(Ca.className,Ia.className),e.classList.add(t==="light"?Ca.className:Ia.className)}function Ji(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 Sg(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 Ng(e,t,r){var c;const n=[t];let a;for(const l of n){let d;for(const m of l){const u=e.addPanel({id:m.tabKey,component:"conversation",title:Zr(m),params:{kind:"conversation",tabKey:m.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 Qi(e,t){const r=new Set(t.map(a=>a.tabKey)),n=new Map;for(const a of t)n.set(a.tabKey,(n.get(a.tabKey)||0)+1);for(const a of[...e.panels])Pt(a.id)||r.has(a.id)||e.removePanel(a);for(const a of t){const o=e.getPanel(a.tabKey);if(o){(n.get(a.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:a.tabKey,daemonId:a.daemonId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,panelId:o.id}),o.update({params:{tabKey:a.tabKey}}),o.title!==Zr(a)&&o.api.setTitle(Zr(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:Zr(a),params:{kind:"conversation",tabKey:a.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 Zi(e,t,r){var d,m;const n=r?jg(r):null;for(const u of[...e.panels])Pt(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=Et(t,r);if(!a&&e.totalPanels===0)return;const o=e.getPanel(n),c=gl(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)??((m=e.panels.find(u=>!Pt(u.id)))==null?void 0:m.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function Cg({params:e,api:t}){var k;const r=_n(),n=i.useRef(null),[a,o]=i.useState(()=>Fr(t)),[c,l]=i.useState(()=>Yi(t)),d=r.conversationsByTabKey.get(e.tabKey),m=In({sendDaemonCommand:r.sendDaemonCommand,activeConv:d,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});i.useEffect(()=>{o(Fr(t)),l(Yi(t));const y=[t.onDidActiveChange(p=>o(p.isActive)),t.onDidActiveGroupChange(p=>{if(!Fr(t)&&!p.isActive){o(!1);return}o(Fr(t))}),t.onDidVisibilityChange(p=>l(p.isVisible))];return()=>{for(const p of y)p.dispose()}},[t]);const u=i.useMemo(()=>d?r.ides.find(y=>y.id===d.routeId):void 0,[r.ides,d]),h=i.useMemo(()=>d?r.actionLogs.filter(y=>y.routeId===d.tabKey):[],[r.actionLogs,d]);if(!d)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(Do,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const b=!et(d)&&Hs(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(Po,{activeConv:d,clearToken:r.clearedTabs[d.tabKey]||0,isCliTerminal:b,ideEntry:u,terminalRef:n,handleModalButton:m.handleModalButton,handleRelaunch:m.handleRelaunch,handleSendChat:m.handleSendChat,isSendingChat:m.isSendingChat,handleFocusAgent:m.handleFocusAgent,isFocusingAgent:m.isFocusingAgent,actionLogs:h,userName:r.userName,scrollToBottomRequestNonce:((k=r.scrollToBottomRequest)==null?void 0:k.tabKey)===d.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:c})})}function Ig({params:e}){var d;const t=_n(),r=i.useMemo(()=>Et([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=i.useMemo(()=>t.ides.find(m=>m.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}=md({doId:a,targetSessionId:r?el(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(Bc,{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 Tg(){const e=_n();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(Do,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function Mg(e){var k,y;Sg(e);const t=_n(),r=i.useCallback(p=>{"button"in p&&p.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const p=Et([...t.conversationsByTabKey.values()],e.params.routeId),x=((k=e.api.group.activePanel)==null?void 0:k.id)===e.api.id,g=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${x?" is-active":""}${g?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(p==null?void 0:p.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:p!=null&&p.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:p.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const n=t.conversationsByTabKey.get(e.params.tabKey);if(!n)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const a=((y=e.api.group.activePanel)==null?void 0:y.id)===e.api.id,o=e.api.isGroupActive,c=Sn(n,t.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,d=c.isConnecting,m=c.isGenerating,u=c.isWaiting,h=c.unread,b=t.tabShortcuts[n.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${o?" is-group-active":""}${l?" is-reconnecting":""}`,title:lt(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:p=>{var x;p.preventDefault(),r(p),t.openTabContextMenu({x:p.clientX,y:p.clientY,tabKey:n.tabKey,sourceDocument:((x=p.target)==null?void 0:x.ownerDocument)??document})},children:[h&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:m?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:lt(n)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:cs(n)}):d?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:cs(n)}):s.jsx("span",{children:cs(n)})})]}),b&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:b,children:b})]})}function Ag({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:d,userName:m,toggleHiddenTab:u,actionShortcuts:h,registerActionHandlers:b,onActiveTabChange:k,onOpenNewSession:y,onRequestScrollToBottom:p,requestedActiveTabKey:x,requestedRemoteIdeId:g,onRequestedActiveTabConsumed:f,scrollToBottomRequest:N,liveSessionInboxState:S,layoutProfile:v}){var Qe,ze,rt;const{theme:M}=Io(),{sendCommand:A}=gt(),w=i.useRef(null),j=i.useRef(null),K=i.useRef(null),P=i.useRef(!1),T=i.useRef(!1),W=i.useRef(!1),H=i.useRef(null),R=i.useRef([]),[I,C]=i.useState(null),[O,_]=i.useState(0),E=i.useRef(typeof window>"u"?{}:qx(v)),U=i.useMemo(()=>new Map(e.map(F=>[F.tabKey,F])),[e]),Q=i.useMemo(()=>{const F=w.current;return F?F.groups.some(V=>{try{const J=V.model.location.type;return J!=="floating"&&J!=="popout"?!1:V.panels.some(re=>U.has(re.id))}catch{return!1}}):!1},[U,O,e]),xe=i.useCallback(()=>{var F;(F=w.current)==null||F.focus()},[]),de=i.useCallback((F,V)=>{p==null||p(F,V)},[p]),Z=i.useCallback(F=>{const V=document,J=F.document;for(const ne of V.querySelectorAll('link[rel="stylesheet"]')){const Se=J.createElement("link");Se.rel="stylesheet",Se.href=ne.href,ne.crossOrigin&&(Se.crossOrigin=ne.crossOrigin),J.head.appendChild(Se)}for(const ne of V.querySelectorAll("style")){const Se=J.createElement("style");Se.textContent=ne.textContent,J.head.appendChild(Se)}const re=[];for(const ne of V.styleSheets)try{for(const Se of ne.cssRules)Se instanceof CSSStyleRule&&(Se.selectorText===":root"||Se.selectorText==="html")&&re.push(Se.cssText)}catch{}if(re.length>0){const ne=J.createElement("style");ne.textContent=re.join(`
53
+ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:j,onCancel:()=>u(null)})]})}const ex=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function tx(){const{preference:e,setPreference:t}=Io();return s.jsx("div",{className:"flex gap-2",children:ex.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 sx(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 rx(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Zn(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Li(e){const{r:t,g:r,b:n}=rx(e);return .2126*Zn(t)+.7152*Zn(r)+.0722*Zn(n)}function Ri(e,t){const r=Li(e),n=Li(t),a=Math.max(r,n),o=Math.min(r,n);return(a+.05)/(o+.05)}function Pl(e){const t=sx(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return Ri(t,r)>=Ri(t,n)?r:n}const Wa={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},Fa={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},nx=[{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"}}}],_l="adhdev-chat-theme",Dl="adhdev-chat-theme-custom";function Xr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(_l)||"ember"}catch{return"ember"}}function Dt(e){try{const t=localStorage.getItem(Dl);if(t){const r=JSON.parse(t);return{...e==="dark"?Wa:Fa,...r[e]}}}catch{}return e==="dark"?Wa:Fa}function Er(e,t){try{localStorage.setItem(Dl,JSON.stringify({dark:e,light:t}))}catch{}}function At(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 bn(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 ax={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function mr(e,t){var a;const r=(a=ax[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",bn(r,24)),n.style.setProperty("--accent-on-primary",Pl(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${bn(r,18)})`),n.style.setProperty("--border-accent",At(r,.35)),n.style.setProperty("--nav-active-bg",At(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${At(r,.06)}`)}function us(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",At(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",At(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",At(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",At(e.borderSubtle,.5)),t.style.setProperty("--border-default",At(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",bn(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Pl(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${bn(e.accentColor,40)})`),t.style.setProperty("--border-accent",At(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",At(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${At(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 ${At(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 To(){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 ox(e){try{localStorage.setItem(_l,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ms()?"dark":"light";us(Dt(t))}else To(),mr(e,ms()?"dark":"light")}function ix(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Xr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ms()?"dark":"light";us(Dt(t))}else To(),mr(e,ms()?"dark":"light")}function ms(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function kt({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 Zs({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 cx({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=i.useState(()=>Dt(r));i.useEffect(()=>{a(Dt(r))},[r]);const o=i.useCallback((c,l)=>{a(d=>{const m={...d,[c]:l},h=Dt(r==="dark"?"light":"dark");return r==="dark"?Er(m,h):Er(h,m),us(m),t(m),m})},[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(Zs,{title:"App Background",children:[s.jsx(kt,{label:"Background",value:n.bgPrimary,onChange:c=>o("bgPrimary",c)}),s.jsx(kt,{label:"Surface",value:n.bgSecondary,onChange:c=>o("bgSecondary",c)}),s.jsx(kt,{label:"Card",value:n.surfacePrimary,onChange:c=>o("surfacePrimary",c)})]}),s.jsxs(Zs,{title:"App Text",children:[s.jsx(kt,{label:"Primary",value:n.textPrimary,onChange:c=>o("textPrimary",c)}),s.jsx(kt,{label:"Secondary",value:n.textSecondary,onChange:c=>o("textSecondary",c)}),s.jsx(kt,{label:"Muted",value:n.textMuted,onChange:c=>o("textMuted",c)})]}),s.jsxs(Zs,{title:"Borders & Accent",children:[s.jsx(kt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>o("borderSubtle",c)}),s.jsx(kt,{label:"Border default",value:n.borderDefault,onChange:c=>o("borderDefault",c)}),s.jsx(kt,{label:"Accent",value:n.accentColor,onChange:c=>o("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Zs,{title:"Chat Bubbles",children:[s.jsx(kt,{label:"User bubble",value:n.userBubble,onChange:c=>o("userBubble",c)}),s.jsx(kt,{label:"User text",value:n.userText,onChange:c=>o("userText",c)}),s.jsx(kt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>o("assistantBubble",c)}),s.jsx(kt,{label:"Agent text",value:n.assistantText,onChange:c=>o("assistantText",c)})]}),s.jsxs(Zs,{title:"Chat Layout",children:[s.jsx(kt,{label:"Chat BG",value:n.containerBg,onChange:c=>o("containerBg",c)}),s.jsx(kt,{label:"Send button",value:n.sendButton,onChange:c=>o("sendButton",c)}),s.jsx(kt,{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?Wa:Fa,d=Dt(e?"light":"dark");e?Er(c,d):Er(d,c),a(c),us(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 lx(){const[e,t]=i.useState(Xr),[r,n]=i.useState(!0),[a,o]=i.useState(()=>Dt("dark"));i.useEffect(()=>{n(ms());const d=new MutationObserver(()=>{const h=ms();n(h);const b=Xr();b==="custom"?us(Dt(h?"dark":"light")):mr(b,h?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const h=ms();n(h);const b=Xr();b==="custom"?us(Dt(h?"dark":"light")):mr(b,h?"dark":"light")};return m.addEventListener("change",u),()=>{d.disconnect(),m.removeEventListener("change",u)}},[]),i.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?us(Dt(r?"dark":"light")):(To(),mr(e,r?"dark":"light"))},[e,r]),i.useEffect(()=>{o(Dt(r?"dark":"light"))},[r]);const c=d=>{t(d),ox(d)},l=[...nx,{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 m=e===d.id,u=r?d.preview.dark:d.preview.light,h=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:m?"var(--bg-glass-hover)":"var(--bg-glass)",border:m?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:m?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:h},children:"Fix the bug please"}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"On it! ✨"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[m&&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(cx,{dark:r,onColorsChange:d=>o(d)})]})}const Mo="adhdev_mobileDashboardMode_v1",Ha="adhdev:mobile-dashboard-mode-change";function Ao(){try{return localStorage.getItem(Mo)==="workspace"?"workspace":"chat"}catch{return"chat"}}function dx(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??Ao())},r=a=>{const o=a.detail;t(o)},n=a=>{a.key&&a.key!==Mo||t()};return window.addEventListener(Ha,r),window.addEventListener("storage",n),()=>{window.removeEventListener(Ha,r),window.removeEventListener("storage",n)}}function ux(e){try{localStorage.setItem(Mo,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ha,{detail:e}))}function mx(){const[e,t]=i.useState(!0);return i.useEffect(()=>{t(Ao()==="chat")},[]),s.jsx(as,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(zt,{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),ux(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const ea=new Map,Pi=new Map;function fx(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 px(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 El(){const{sendCommand:e}=gt(),{injectEntries:t,getIdes:r}=hr();return i.useCallback(async(n,a)=>{if(!n)return;const o=(a==null?void 0:a.minFreshMs)??dp,c=Pi.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<o)return;const l=ea.get(n);if(l)return l;const d=(async()=>{const m=await e(n,"get_machine_runtime_stats"),u=fx(m);if(!u)return;const h=r().find(k=>k.id===n),b=px(h,n,u.machine,u.timestamp||Date.now());t([b]),Pi.set(n,Date.now())})().finally(()=>{ea.delete(n)});return ea.set(n,d),d},[r,t,e])}function hx(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 xx(e,t){const{sendData:r}=gt(),{injectEntries:n,getIdes:a}=hr(),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=>Ut.subscribe({sendData:r},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const h=a().find(k=>k.id===d),b=hx(h,d,u);n([b])}));return()=>{l.forEach(d=>d())}},[o,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function bx(e,t){const{sendData:r}=gt(),[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=Ut.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}:{}}},m=>{l&&(clearTimeout(l),l=null),a(m.diagnostics),c(!1)});return d.initialSendAccepted?l=setTimeout(()=>{c(!1)},pp):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 gx(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function $l(e){const{sendData:t}=gt(),[r,n]=i.useState({});return i.useEffect(()=>{const a=gx(e);if(!a||!e.sessionId||!t){n({});return}const o=Ut.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}),Rs.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 Bl="adhdev_hiddenTabs",Kl="adhdev_autoHiddenMeshTabs";function yx(){try{const e=localStorage.getItem(Bl);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ss(e){try{localStorage.setItem(Bl,JSON.stringify([...e]))}catch{}}function vx(){try{const e=localStorage.getItem(Kl);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function _i(e){try{localStorage.setItem(Kl,JSON.stringify([...e]))}catch{}}function or(e){return go(e)}function Mn(e,t){return Ls(t).some(r=>e.has(r))}function wx(e){var t,r,n;return((t=e.settings)==null?void 0:t.launchedByCoordinator)===!0&&typeof((r=e.settings)==null?void 0:r.meshNodeFor)=="string"&&e.settings.meshNodeFor.trim().length>0&&((n=e.settings)==null?void 0:n.spawnedSessionVisibility)==="hidden"}function jx(e,t,r=new Set){return e.filter(n=>{if(!wx(n))return!1;const a=or(n);return r.has(a)?!1:!Mn(t,n)})}function kx(){const[e,t]=i.useState(yx),[r,n]=i.useState(vx),a=i.useCallback(b=>{const k=or(b);t(y=>{const p=new Set(y);return p.has(k)?p.delete(k):p.add(k),ss(p),p})},[]),o=i.useCallback(b=>{const k=or(b);t(y=>{if(y.has(k))return y;const p=new Set(y);return p.add(k),ss(p),p})},[]),c=i.useCallback(b=>{const k=or(b);t(y=>{if(y.has(k))return y;const p=new Set(y);return p.add(k),ss(p),p}),n(y=>{if(y.has(k))return y;const p=new Set(y);return p.add(k),_i(p),p})},[]),l=i.useCallback(b=>{const k=or(b);t(y=>{if(!y.has(k))return y;const p=new Set(y);return p.delete(k),ss(p),p}),n(y=>{if(y.has(k))return y;const p=new Set(y);return p.add(k),_i(p),p})},[]),d=i.useCallback(()=>{t(b=>{if(b.size===0)return b;const k=new Set;return ss(k),k})},[]),m=i.useCallback((b,k)=>{t(y=>{const p=new Set(y);for(const x of k)p.add(x);return ss(p),p})},[]),u=i.useCallback((b,k)=>{t(y=>{const p=new Set(y);for(const x of k)p.delete(x);return ss(p),p})},[]),h=i.useCallback(b=>Mn(e,b),[e]);return{hiddenTabs:e,autoHiddenTabs:r,toggleTarget:a,hideTarget:o,autoHideTarget:c,showTarget:l,showAllTabs:d,hideAllForDaemon:m,showAllForDaemon:u,isHidden:h}}function Ol(e){return e instanceof Error?e.message:String(e||"")}function Wl(e){const t=Ol(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 Fl(e){const t=Ol(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||!st(e)||et(e))return;const o=Hs(e);if(o===t)return;const c=e.sessionId;c&&a(l=>({...l,[c]:t}));try{await n(ws(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Ot(e),mode:t})}catch(l){const d=Fl(l);c&&!d&&a(m=>{const u={...m};return o===Ul(r,c)?delete u[c]:u[c]=o,u}),Wl(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 Di(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 Sx(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=Di(a,t),c=Array.isArray(a.childSessions)?a.childSessions.map(d=>Di(d,t)):a.childSessions,l=c!==a.childSessions;return o!==a||l?(r=!0,{...o,...l?{childSessions:c}:{}}):a});return r?n:e}function Ul(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 Nx(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))Ul(t,a)===o&&(delete n[a],r=!0);return r?n:e}function Cx({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){i.useEffect(()=>{zc()},[]);const a=i.useMemo(()=>e.map(o=>({id:o.tabKey,name:bl(o),status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null})),[e]);return pf(a),i.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{r(l=>{const d=Date.now(),m={};for(const[u,h]of Object.entries(l))d-h<5e3&&(m[u]=h);return Object.keys(m).length===Object.keys(l).length?l:m})},5500);return()=>clearTimeout(c)},[t,r]),i.useEffect(()=>{const o=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const d=l.filter(m=>m.timestamp>c).slice(-100);return d.length===l.length?l:d})},6e4);return()=>clearInterval(o)},[n]),null}function Ei(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 fs(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=Ei(t==null?void 0:t.receivedAt)||Ei(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function Ua(e,t=0){return fs(e)||e.lastUpdated||t||0}function zl(e){return fs(e)||e.lastUpdated||0}function Vl(e,t,r=zl){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 za(e){var r;const t=xt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function Ix(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!za(e)&&!e.title.trim()}function Tx(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(za(r))-Number(za(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:Vl(t,r)})[0]||null}function Et(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=Tx(a);return n?o&&Ix(n)?o:n:o||r[0]||null}function Mx(e){const t=String(e.daemonId||"").trim(),r=String(e.id||"").trim();return!t||r.startsWith(`${t}:`)?r:`${t}:${r}`}function Ax(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=Mx(n),o=r.get(a);if(!o){r.set(a,n);continue}const c=(o.workspace?1:0)+(o.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>c||(n.timestamp||0)>(o.timestamp||0))&&r.set(a,n)}return Array.from(r.values())}function ta(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 Lx(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 $i(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?Lx(Ps(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 Rx(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||""),$i(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||""),$i(r.activeChat)].join(":"))].join("|")}function Px(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 _x(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const o of Ls({routeId:n.routeId}))r.set(o,a);for(const o of Ls({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(o,n.streamSource==="native"?a:n);for(const o of Ls({tabKey:n.tabKey}))r.set(o,n)}return r}function Dx(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Ex(e){const t=Dx(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=Ps(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function $x({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=i.useMemo(()=>Ax(e),[e]),o=i.useMemo(()=>Sl(e),[e]),c=i.useRef([]),l=i.useRef([]),d=i.useRef([]),m=i.useRef(new Map),u=i.useRef(new Map),h=i.useMemo(()=>{const S=new Map,v=[];for(const j of a){const{connectionState:K="new",machineName:P}=Nl(j,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),T=Rx(j),W=m.current.get(j.id);if(W&&W.ide===j&&W.sourceSignature===T&&W.connectionState===K&&W.machineName===P){S.set(j.id,W),v.push(...W.conversations);continue}const H=Co(j,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),R={ide:j,sourceSignature:T,connectionState:K,machineName:P,conversations:H};S.set(j.id,R),v.push(...H)}m.current=S;const M=new Map,A=j=>{const K=Ex(j),P=u.current.get(j.tabKey);if(P&&P.signature===K)return M.set(j.tabKey,P),P.timestamp;const T={signature:K,timestamp:zl(j)||(P==null?void 0:P.timestamp)||0};return M.set(j.tabKey,T),T.timestamp},w=[...v].sort((j,K)=>Vl(j,K,A));return u.current=M,w},[a,t,o]),b=i.useMemo(()=>{const S=Px(h,r);return ta(c.current,S)?c.current:(c.current=S,S)},[h,r]),k=i.useMemo(()=>{const S=new Map,v=Array.from(new Set(b.map(M=>M.routeId)));for(const M of v){const A=Et(b,M);A&&S.set(M,A)}return S},[b]),y=i.useMemo(()=>{const S=new Map;for(const v of b){const M=k.get(v.routeId),A=v.streamSource==="native"&&M?M:v;for(const w of Ls({providerSessionId:v.providerSessionId,sessionId:v.sessionId,tabKey:v.tabKey}))S.set(w,A)}return S},[b,k]),p=i.useMemo(()=>_x(b,k),[b,k]),x=i.useCallback(S=>{if(S)return y.get(S)},[y]),g=i.useCallback(S=>{if(S)return p.get(S)},[p]),f=i.useMemo(()=>{const S=b.filter(v=>!Mn(n,v));return ta(l.current,S)?l.current:(l.current=S,S)},[b,n]),N=i.useMemo(()=>{const S=f.map(v=>v.tabKey);return ta(d.current,S)?d.current:(d.current=S,S)},[f]);return{chatIdes:a,conversations:b,visibleConversations:f,visibleTabKeys:N,resolveConversationBySessionId:x,resolveConversationByTarget:g}}function Bx({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 Kx({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){i.useEffect(()=>{nt.setIdes(e)},[e]),i.useEffect(()=>{nt.setResolveAction((a,o,c)=>{t(a,o,c).catch(()=>{})})},[t]),i.useEffect(()=>{const a=nt.onToast(o=>{r(l=>l.some(m=>m.message===o.message&&o.timestamp-m.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=pl.on("status_event",o=>{nt.handleRawEvent(o,"ws")});return()=>{a()}},[]),i.useEffect(()=>{var o;const a=c=>{var p;const l=c.data;if((l==null?void 0:l.type)!=="notification_action"||typeof l.action!="string"||!l.action.startsWith("approval_")||!(l.daemonId||l.targetSessionId||l.targetKey))return;const d=l.targetSessionId||l.targetKey||l.daemonId,m=n(d),u=(m==null?void 0:m.routeId)||l.daemonId;if(!u)return;const h=Number(l.buttonIndex),b=l.button||((p=m==null?void 0:m.modalButtons)==null?void 0:p[h])||"Approve",k=String(b).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),y=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(k);t(u,"resolve_action",{action:y?"approve":"reject",button:b,...Number.isFinite(h)&&{buttonIndex:h},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(x=>console.error("[SW Action] approval failed:",x))};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 Ox="adhdev_dashboardLayout_v1",Wx="adhdev_dashboardDockview_v1",Fx="adhdev_dashboardDockviewHiddenRestore_v1",er={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Lo(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function Hx(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Gl(e){return`${Ox}:${e}`}function Ux(e){const t=Gl(e);return Lo(t,null)}function zx(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=Gl(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function ql(e){return`${Wx}:${e}`}function Vx(e){const t=ql(e);return Lo(t,null)}function Gx(e,t){try{const r=ql(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Yl(e){return`${Fx}:${e}`}function qx(e){const t=Yl(e);return Lo(t,{})}function Yx(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 Xx(){return{groupAssignments:[...er.groupAssignments],focusedGroup:er.focusedGroup,groupActiveTabIds:{...er.groupActiveTabIds},groupTabOrders:{...er.groupTabOrders},groupSizes:[...er.groupSizes]}}function Jx(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function Qx(){const[e]=i.useState(()=>Hx(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({}),[m,u]=i.useState([]),[h,b]=i.useState(()=>typeof window<"u"&&window.innerWidth<768),[k,y]=i.useState(!1),p=i.useCallback(()=>{if(k)return;const j=Ux(e)??Xx();r(new Map(j.groupAssignments)),a(j.focusedGroup),c(j.groupActiveTabIds),d(j.groupTabOrders),u(j.groupSizes),y(!0)},[k,e]);i.useEffect(()=>{k&&zx(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:l,groupSizes:m})},[k,e,t,n,o,l,m]),i.useEffect(()=>{const j=window.matchMedia("(max-width: 767px)"),K=P=>b(P.matches);return j.addEventListener("change",K),()=>j.removeEventListener("change",K)},[]);const x=i.useCallback(j=>{r(j)},[]),g=i.useCallback(j=>{a(j)},[]),f=i.useCallback(j=>{c(j)},[]),N=i.useCallback(j=>{d(j)},[]),S=i.useCallback(j=>{u(j)},[]),v=i.useCallback(j=>{g(j)},[g]),M=i.useCallback((j,K)=>{c(P=>(P[j]??null)===(K??null)?P:{...P,[j]:K})},[]),A=i.useCallback((j,K)=>{d(P=>{const T=P[j];return Jx(T,K)?P:{...P,[j]:K}})},[]),w=i.useCallback((j,K)=>{const P=K.get(j)??0;return M(P,j),v(P),P},[v,M]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:x,focusedGroup:n,updateFocusedGroup:g,focusGroup:v,groupActiveTabIds:o,updateGroupActiveTabIds:f,setGroupActiveTab:M,groupTabOrders:l,updateGroupTabOrders:N,setGroupTabOrder:A,groupSizes:m,updateGroupSizes:S,isMobile:h,hasHydratedStoredLayout:k,hydrateStoredLayout:p,focusConversationTab:w}}function Zx(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=bo(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function eb({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:c,setSearchParams:l,historyModalOpen:d,activeConv:m,isRefreshingHistory:u,ides:h,handleRefreshHistory:b}){const k=i.useRef(!1),y=i.useRef(!1),p=i.useRef(null),x=i.useRef(!1);i.useEffect(()=>{if(!e||k.current||t.length===0)return;if(!a){o();return}const g=r(e);g&&(c(g.tabKey,n),k.current=!0,y.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),l(f=>{const N=new URLSearchParams(f);return N.delete("activeTab"),N},{replace:!0}))},[e,t,r,n,a,o,c,l]),i.useEffect(()=>{if(!(y.current||a)&&t.length!==0){if(!e){o(),y.current=!0;return}if(k.current){y.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(y.current||a)&&(o(),y.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,t.length,a,o]),i.useEffect(()=>{if(!d){x.current=!1;return}if(!m||x.current||u)return;const g=h.find(f=>f.id===m.routeId);g&&(!g.chats||g.chats.length===0||Zx(g.chats,m))&&(x.current=!0,b())},[d,m,u,h,b])}function sa(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=bo(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Xl({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:o}){const[c,l]=i.useState(!1),[d,m]=i.useState(!1),u=i.useCallback(async y=>{try{await e("standalone","launch_ide",{ideType:y,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),h=i.useCallback(async(y,p)=>{try{const x=y||(t==null?void 0:t.daemonId)||"",g=await e(x,"switch_chat",{id:p,sessionId:p,...is(t)}),f=g==null?void 0:g.result;if((g==null?void 0:g.success)===!0||f==="switched"||f==="switched-by-title")return;f===!1||f==="not_found"?Xs(a,"⚠️ Session tab not found — try refreshing history"):typeof f=="string"&&f.startsWith("error:")?Xs(a,`⚠️ Switch error: ${f}`):Xs(a,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),Xs(a,`❌ Switch failed: ${x.message||"connection error"}`)}},[t,e,a]),b=i.useCallback(async()=>{if(!(!t||c)){l(!0);try{const y=Es(t);await e(y,"new_chat",{...is(t)}),o(p=>({...p,[t.tabKey]:Date.now()}))}catch(y){console.error("New chat failed",y)}finally{l(!1)}}},[t,c,e,o]),k=i.useCallback(async()=>{var y,p;if(!(!t||d)){m(!0);try{const x=Es(t),g=async()=>e(x,"list_chats",{forceExpand:!0,...is(t)});let f=await g(),N=(f==null?void 0:f.chats)||((y=f==null?void 0:f.result)==null?void 0:y.chats);sa(N,t)&&(await new Promise(S=>setTimeout(S,450)),f=await g(),N=(f==null?void 0:f.chats)||((p=f==null?void 0:f.result)==null?void 0:p.chats)),f!=null&&f.success&&Array.isArray(N)&&(n(t.routeId,N),sa(N,t)&&!sa(r,t)&&Xs(a,"⚠️ History dialog did not fully open — try once more"))}catch(x){console.error("Refresh history failed",x)}finally{m(!1)}}},[t,r,d,e,n,a]);return{isCreatingChat:c,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:h,handleNewChat:b,handleRefreshHistory:k}}function tb(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 sb(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function Bi(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 $r(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 Ki(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 rb(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 nb(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 Oi(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 Wi(e){return Array(e).fill(100/e)}function ab({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:c,isMobile:l,visibleConversations:d,visibleTabKeys:m}){const u=i.useRef(null),h=i.useMemo(()=>$r(e,m),[e,m]),b=h.assignments,k=i.useMemo(()=>l?1:h.groupCount,[h.groupCount,l]),y=k>1,p=i.useCallback((v,M)=>{t(A=>{const w=new Map($r(A,m).assignments);return M===0?w.delete(v):w.set(v,M),w}),n(A=>({...A,[M]:v})),r(M)},[t,m,n,r]),x=i.useCallback(v=>{t(M=>{const A=$r(M,m).assignments,w=new Map;for(const[j,K]of A)K!==v&&(K>v?w.set(j,K-1):w.set(j,K));return w}),c(M=>{if(M.length<=1)return[];const A=[...M];A.splice(v,1);const w=A.reduce((j,K)=>j+K,0);return w>0?A.map(j=>j/w*100):[]}),r(0)},[t,m,c,r]),g=i.useCallback((v,M)=>{M.preventDefault();const A=u.current;if(!A)return;const w=M.clientX,j=A.offsetWidth,K=o.length===k?[...o]:Wi(k),P=W=>{const R=(W.clientX-w)/j*100,I=[...K];I[v]=Math.max(15,K[v]+R),I[v+1]=Math.max(15,K[v+1]-R),c(I)},T=()=>{document.removeEventListener("mousemove",P),document.removeEventListener("mouseup",T),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",P),document.addEventListener("mouseup",T)},[o,k,c]),f=i.useCallback((v,M,A)=>{if(k>=4)return;const w=A==="left"?M:M+1;t(j=>{const K=$r(j,m).assignments,P=new Map;for(const T of d){const W=K.get(T.tabKey)??0,H=W>=w?W+1:W;H>0&&P.set(T.tabKey,H)}return w>0&&P.set(v,w),P}),c(j=>{const K=j.length===k?[...j]:Wi(k),P=K[M]??100/k,T=Math.max(15,P/2),W=Math.max(15,P/2),H=[...K];H[M]=T,H.splice(w,0,W);const R=H.reduce((I,C)=>I+C,0);return H.map(I=>I/R*100)}),n(j=>{const K=Oi(j,w);return K[w]=v,K}),a(j=>{const K=Oi(j,w);return K[w]=[v],K}),r(w)},[k,t,m,d,c,n,a,r]);i.useEffect(()=>{tb(e,b)||t(b)},[e,b,t]),i.useEffect(()=>{const{mapping:v,usedGroups:M}=h;n(A=>{const w=Ki(A,v);return Bi(A,w)?A:w}),a(A=>{const w=Ki(A,v);return Bi(A,w)?A:w}),r(A=>{const w=l?0:rb(A,M,v);return A===w?A:w}),c(A=>{const w=l?[]:nb(A,M,h.groupCount);return sb(A,w)?A:w})},[h,l,n,a,r,c]);const N=i.useMemo(()=>{const v=Array.from({length:k},()=>[]);for(const M of d){const A=b.get(M.tabKey)??0,w=Math.min(A,k-1);v[w].push(M)}return v},[d,b,k]),S=i.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:u,normalizedGroupAssignments:b,numGroups:k,isSplitMode:y,groupedConvs:N,moveTabToGroup:p,closeGroup:x,handleResizeStart:g,splitTabRelative:f,clearAllSplits:S}}function ra(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="stable"||t==="latest"?"stable":t==="preview"||t==="next"?"preview":null}function ob(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="latest"||t==="stable"?"latest":t==="next"||t==="preview"?"next":null}function Br(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Ro(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},r=ra(t.channel)||ra(e.updateChannel)||ra(e.releaseChannel)||void 0,n=ob(t.npmTag)||(r==="preview"?"next":r==="stable"?"latest":void 0),a=Br(t.targetVersion)||Br(e.serverVersion)||void 0,o=Br(t.minVersion)||void 0,c=Br(t.updateCommand)||(r?`adhdev update --channel ${r}`:void 0);return{...r?{channel:r}:{},...n?{npmTag:n}:{},...a?{targetVersion:a}:{},...o?{minVersion:o}:{},...c?{updateCommand:c}:{}}}function Cs(e,t=null){return Ro(e).targetVersion||t}function Jl(e){return Ro(e).channel||null}function Ql(e){const t=Ro(e);return{...t.channel?{channel:t.channel}:{},...t.npmTag?{npmTag:t.npmTag}:{},...t.targetVersion?{targetVersion:t.targetVersion}:{},...Object.keys(t).length>0?{updatePolicy:t}:{}}}function ib({ides:e,sendDaemonCommand:t}){const r="0.9.80",n=i.useMemo(()=>e.filter(h=>h.type!=="adhdev-daemon"?!1:Rl(h,Cs(h,r))).sort((h,b)=>Number(ur(b,Cs(b,r)))-Number(ur(h,Cs(h,r)))),[r,e]),a=i.useMemo(()=>n.some(h=>ur(h,Cs(h,r))),[r,n]),o=i.useMemo(()=>n.map(h=>Cs(h,r)).find(h=>typeof h=="string"&&h.trim().length>0)||r,[r,n]),[c,l]=i.useState(!1),[d,m]=i.useState({}),u=i.useCallback(async h=>{var k,y;const b=e.find(p=>p.id===h);if(b){m(p=>({...p,[h]:"upgrading"}));try{const p=await t(h,"daemon_upgrade",Ql(b));(k=p==null?void 0:p.result)!=null&&k.upgraded||(y=p==null?void 0:p.result)!=null&&y.success?m(x=>({...x,[h]:"done"})):m(x=>({...x,[h]:"error"}))}catch{m(p=>({...p,[h]:"error"}))}}},[e,t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:c,setVersionBannerDismissed:l,upgradingDaemons:d,handleBannerUpgrade:u}}const Zl=80;function Jr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function cb(e){return{...e,createdAt:Jr(e.createdAt),updatedAt:Jr(e.updatedAt,e.createdAt),lastEventAt:Jr(e.lastEventAt,e.updatedAt||e.createdAt)}}function lb(e){const t=go(e);return t==="unknown:"?e.id:t}function db(e){return[e.type,il(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function ub(e,t=Zl){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=lb(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 mb(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=Sn(a,t),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const d=Jr(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,r),m=db({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(cb({id:m,dedupKey:m,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Jc(a),preview:Ff(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return ub(n)}function fb(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function pb(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=Zl}=e,a=i.useMemo(()=>mb(t,r).slice(0,Math.max(0,n)),[t,r,n]),o=i.useMemo(()=>fb(a),[a]);return{notifications:a,unreadCount:o}}function hb({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}}const xb=i.createContext(null);function bb(){return i.useContext(xb)}function An(...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 gb(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 Ln(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=gb(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 yb(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 vb(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Rn(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=vb(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=(m,u)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${u}`:m==="/"||m==="\\"?`${c}${u}`:`${m.replace(/[\\/]+$/,"")}${c}${u}`,d=Array.isArray(a==null?void 0:a.files)?a.files.filter(m=>(m==null?void 0:m.type)==="directory"&&typeof(m==null?void 0:m.name)=="string").map(m=>({name:m.name,path:typeof(m==null?void 0:m.path)=="string"&&m.path.trim()?m.path:l(o,m.name)})).sort((m,u)=>m.name.localeCompare(u.name)):[];return{path:o,directories:d}}function wb(e,t){const r={meshId:t.meshId||"",workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp"};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand)\s*\}\}/g,(n,a)=>r[a]||"")}function ed(e,t={}){const r=e==null?void 0:e.mcpConfig;return(r==null?void 0:r.mode)!=="manual"?null:{serverName:r.serverName||"adhdev-mesh",configFormat:r.format,configPathCommand:r.configPathCommand,requiresRestart:r.requiresRestart===!0,instructions:r.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:wb(r.template||"",{...t,serverName:r.serverName||"adhdev-mesh"})}}function jb(e){if(!e||typeof e!="object")return null;const t=e,r=typeof t.instructions=="string"?t.instructions:"",n=typeof t.template=="string"?t.template:"";return!r&&!n?null:{serverName:typeof t.serverName=="string"?t.serverName:void 0,configFormat:typeof t.configFormat=="string"?t.configFormat:void 0,configPathCommand:typeof t.configPathCommand=="string"?t.configPathCommand:void 0,requiresRestart:t.requiresRestart===!0,instructions:r||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:n}}function Zt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function td(e){return kr(e)||e.tabKey||e.routeId||null}function sd(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",a=e.conversations.find(o=>{if(n&&o.routeId!==n)return!1;const c=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey].map(l=>typeof l=="string"?l.trim():"").filter(Boolean);return!!(t&&c.includes(t)||r&&c.includes(r)||n&&o.routeId===n)});if(a!=null&&a.tabKey)return a.tabKey;if(n){const o=Et(e.conversations,n)||e.conversations.find(c=>c.routeId===n);if(o!=null&&o.tabKey)return o.tabKey}return t||r||n||null}function Yt(e){return String(e||"").trim()}function rd(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function gn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function kb(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function Sb(e,t){const r=Yt(e.providerSessionId),n=Yt(e.targetSessionId),a=t.find(o=>{const c=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(Yt).filter(Boolean);return!!(r&&c.includes(r)||n&&c.includes(n))});return a?a.tabKey:n||r||null}function Nb(e,t,r){if(t.event!=="agent:generating_completed")return null;const n=rd(t.daemonId);if(n&&n!==e.machineId)return null;const a=Yt(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=Yt(e.resumeSessionId),c=Yt(e.launchedSessionId),l=Yt(t.providerSessionId),d=Yt(t.targetSessionId);if(o&&o!==l&&o!==d||c&&c!==l&&c!==d)return null;const m=gn(e.workspacePath);if(m){const u=gn(t.workspaceName);if(u&&!kb(u,m))return null}return Sb(t,r)}function Fi(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Cb({ides:e,conversations:t,onOpenSession:r}){const[n,a]=i.useState(null),o=i.useRef(null),c=i.useCallback(()=>{o.current=null,a(null)},[]),l=i.useCallback(d=>{o.current=d,a(d)},[]);return i.useEffect(()=>{if(!n)return;const d=gn(n.workspacePath),m=e.find(h=>{var x,g,f,N;if(!h||h.type==="adhdev-daemon"||rd(h.daemonId||h.id)!==n.machineId||(br(h)?"cli":Ms(h)?"acp":"ide")!==n.kind)return!1;const y=String(h.agentType||h.type||"");if(n.providerType&&y!==n.providerType)return!1;if(n.resumeSessionId)return String(h.providerSessionId||"")===n.resumeSessionId;if(n.launchedSessionId){const S=String(n.launchedSessionId||"");return[h.providerSessionId,h.sessionId,h.instanceId,h.id].map(M=>String(M||"")).filter(Boolean).includes(S)}if(d){const S=gn(h.workspace||h.runtimeWorkspaceLabel);return S?S===d:!1}return Number(h.lastUpdated||h._lastUpdate||h.timestamp||((N=(f=(g=(x=h.activeChat)==null?void 0:x.messages)==null?void 0:g.at)==null?void 0:f.call(g,-1))==null?void 0:N.timestamp)||0)>=n.startedAt-5e3});if(!m)return;const u=sd({entrySessionId:m.sessionId,entryInstanceId:m.instanceId,entryRouteId:m.id,conversations:t});u&&(c(),r(u))},[c,t,e,r,n]),i.useEffect(()=>nt.onStatusEvent(d=>{const m=o.current;if(!m)return;const u=Nb(m,d,t);u&&(c(),r(u))}),[c,t,r]),i.useEffect(()=>{if(!n)return;const d=window.setTimeout(()=>{a(m=>!m||m.startedAt!==n.startedAt?m:(o.current=null,null))},45e3);return()=>window.clearTimeout(d)},[n]),{trackPendingLaunch:l}}function Ib({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:o}){const c=bb(),l=i.useCallback(async(p,x)=>Rn(e,p,x),[e]),d=i.useCallback(async(p,x)=>{if(!x.trim())return{ok:!1,error:"Choose a workspace path first."};try{const g=await e(p,"workspace_add",{path:x.trim()});return g!=null&&g.success?{ok:!0}:{ok:!1,error:(g==null?void 0:g.error)||"Could not save workspace"}}catch(g){return{ok:!1,error:g instanceof Error?g.message:"Could not save workspace"}}},[e]),m=i.useCallback(async(p,x,g)=>{var f;try{const N={ideType:x,enableCdp:!0};(f=g==null?void 0:g.workspacePath)!=null&&f.trim()&&(N.workspace=g.workspacePath.trim());const S=await e(p,"launch_ide",N);return!(S!=null&&S.success)&&(S==null?void 0:S.success)!==void 0?{ok:!1,error:(S==null?void 0:S.error)||"Could not launch IDE"}:(t({machineId:p,kind:"ide",providerType:x,workspacePath:(g==null?void 0:g.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(N){return{ok:!1,error:N instanceof Error?N.message:"Could not launch IDE"}}},[e,t]),u=i.useCallback(async(p,x,g,f)=>{var S,v,M;const N=Date.now();try{const A={cliType:g};(S=f==null?void 0:f.workspacePath)!=null&&S.trim()?A.dir=f.workspacePath.trim():f!=null&&f.workspaceId&&(A.workspaceId=f.workspaceId),(v=f==null?void 0:f.resumeSessionId)!=null&&v.trim()&&(A.resumeSessionId=f.resumeSessionId.trim()),Array.isArray(f==null?void 0:f.cliArgs)&&f.cliArgs.length>0&&(A.cliArgs=f.cliArgs),(M=f==null?void 0:f.initialModel)!=null&&M.trim()&&(A.initialModel=f.initialModel.trim());const w=await e(p,"launch_cli",A),j=(w==null?void 0:w.result)||w,K=(j==null?void 0:j.sessionId)||(j==null?void 0:j.id);return w!=null&&w.success&&K?(t({machineId:p,kind:x,providerType:g,workspacePath:(f==null?void 0:f.workspacePath)||null,resumeSessionId:(f==null?void 0:f.resumeSessionId)||null,launchedSessionId:K,startedAt:N}),{ok:!0}):w!=null&&w.success?(t({machineId:p,kind:x,providerType:g,workspacePath:(f==null?void 0:f.workspacePath)||null,resumeSessionId:(f==null?void 0:f.resumeSessionId)||null,startedAt:N}),{ok:!0}):{ok:!1,error:(w==null?void 0:w.error)||(j==null?void 0:j.error)||`Could not launch ${x.toUpperCase()} session`}}catch(A){return Fi(A)?(t({machineId:p,kind:x,providerType:g,workspacePath:(f==null?void 0:f.workspacePath)||null,resumeSessionId:(f==null?void 0:f.resumeSessionId)||null,startedAt:N}),{ok:!0}):{ok:!1,error:A instanceof Error?A.message:`Could not launch ${x.toUpperCase()} session`}}},[r,e,t]),h=i.useCallback(async p=>{var x;if(c!=null&&c.listMeshes)return c.listMeshes(p);if(!p)return[];try{const g=await e(p,"list_meshes",{}),f=(g==null?void 0:g.result)??g;if((f==null?void 0:f.success)===!1)throw new Error((f==null?void 0:f.error)||"Could not load meshes");return(Array.isArray(f==null?void 0:f.meshes)?f.meshes:Array.isArray((x=f==null?void 0:f.result)==null?void 0:x.meshes)?f.result.meshes:[]).map(S=>{var v;return{id:String((S==null?void 0:S.id)||""),name:String((S==null?void 0:S.name)||(S==null?void 0:S.id)||"Untitled mesh"),repoIdentity:(S==null?void 0:S.repoIdentity)||(S==null?void 0:S.repo_identity)||null,workspace:Array.isArray(S==null?void 0:S.nodes)&&S.nodes.length>0?String(((v=S.nodes[0])==null?void 0:v.workspace)||""):null,nodesCount:Array.isArray(S==null?void 0:S.nodes)?S.nodes.length:void 0,status:(S==null?void 0:S.status)||null}}).filter(S=>S.id)}catch(g){throw console.error("List meshes failed",g),g}},[c,e]),b=i.useCallback(async(p,x,g)=>{if(!x.trim())return{ok:!1,error:"Choose a mesh first."};if(c!=null&&c.launchMeshCoordinator)return c.launchMeshCoordinator(p,x,g);const f=Date.now();try{const N={meshId:x.trim()};g.trim()&&(N.cliType=g.trim());const S=await e(p,"launch_mesh_coordinator",N),v=(S==null?void 0:S.result)??S;if((v==null?void 0:v.success)===!1||(S==null?void 0:S.success)===!1){const A=String((v==null?void 0:v.code)||(S==null?void 0:S.code)||""),w=jb((v==null?void 0:v.meshCoordinatorSetup)||(v==null?void 0:v.manualSetup)||(S==null?void 0:S.meshCoordinatorSetup)||(S==null?void 0:S.manualSetup));return{ok:!1,error:(v==null?void 0:v.error)||(S==null?void 0:S.error)||"Could not launch mesh coordinator",code:A||void 0,manualSetup:w}}const M=(v==null?void 0:v.sessionId)||(v==null?void 0:v.id);return M?r(M):t({machineId:p,kind:"cli",providerType:(v==null?void 0:v.cliType)||g.trim()||void 0,workspacePath:(v==null?void 0:v.workspace)||null,startedAt:f}),{ok:!0}}catch(N){return Fi(N)?(t({machineId:p,kind:"cli",providerType:g.trim()||void 0,startedAt:f}),{ok:!0}):{ok:!1,error:N instanceof Error?N.message:"Could not launch mesh coordinator"}}},[c,r,e,t]),k=i.useCallback(async(p,x)=>{if(!p||!x)return[];try{const g=await e(p,"list_saved_sessions",{providerType:x,kind:"cli",limit:30}),f=(g==null?void 0:g.result)??g;return Array.isArray(f==null?void 0:f.sessions)?f.sessions:[]}catch(g){return console.error("List saved sessions failed",g),[]}},[e]),y=i.useCallback(async p=>{await Hl({conversation:n,mode:p,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[n,a,e,o]);return{handleBrowseMachineDirectory:l,handleSaveMachineWorkspace:d,handleLaunchMachineIde:m,handleLaunchMachineProvider:u,handleListMachineMeshes:h,handleLaunchMeshCoordinator:b,handleListMachineSavedSessions:k,setActiveCliViewMode:y}}function Tb(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 Mb(e,t,r=Date.now()){return!e||!Tb(t)?null:{tabKey:e,nonce:r}}function Ab({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:o,setSearchParams:c}){const[l,d]=i.useState(null),[m,u]=i.useState(null),h=i.useMemo(()=>{var x,g;if(!e){if(l){const f=t.find(N=>N.tabKey===l);if(f)return f}return r[0]}const p=n[a];if(p){const f=t.find(N=>N.tabKey===p);if(f)return f}return((x=o[a])==null?void 0:x[0])||((g=o[0])==null?void 0:g[0])},[t,l,a,n,o,e,r]),b=i.useCallback(p=>{d(p)},[]),k=i.useCallback(p=>{d(p.tabKey),c(x=>{const g=new URLSearchParams(x),f=Uf(p);return f?g.set("activeTab",f):g.delete("activeTab"),g},{replace:!0})},[c]),y=i.useCallback((p,x)=>{const g=Mb(p,x);g&&u(g)},[]);return{activeConv:h,openDesktopConversation:k,requestScrollToBottom:y,scrollToBottomRequest:m,setDesktopActiveTab:b}}function Lb(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 Rb(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 Pb({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 m=()=>{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){m(),a.current=null;return}if(!(e!=null&&e.sessionId)){m(),a.current=null;return}const u=cn(e,r),h=Rb({tabKey:e.tabKey,historySessionId:kr(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:fs(e),liveState:u}),b=h.autoReadKey,k=Lb({autoReadKey:b,shouldMarkSeen:h.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!h.shouldMarkSeen){k.shouldCancelPending&&m(),a.current=b;return}if(!k.shouldSchedule)return;k.shouldCancelPending&&m();const y=()=>{if(document.visibilityState!=="visible"||a.current===b)return;a.current=b,o.current=null,c.current=null,l.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const x=h.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:x,completionMarker:h.completionMarker}).catch(()=>{})};if(o.current=k.nextPendingKey,document.visibilityState==="visible"){c.current=setTimeout(y,1500);const x=()=>{document.visibilityState!=="visible"&&c.current&&(clearTimeout(c.current),c.current=null)};d.current=x,document.addEventListener("visibilitychange",x);return}const p=()=>{document.visibilityState==="visible"&&(l.current&&clearTimeout(l.current),l.current=setTimeout(y,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=p,document.addEventListener("visibilitychange",p)},[e,t,r,n]),i.useEffect(()=>()=>{c.current&&clearTimeout(c.current),l.current&&clearTimeout(l.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function na(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 _b({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:o,setToasts:c,setClearedTabs:l,setSearchParams:d}){var C;const[m,u]=i.useState(!1),[h,b]=i.useState([]),[k,y]=i.useState(()=>jt()),[p,x]=i.useState(!1),[g,f]=i.useState(null),N=i.useRef(null),S=i.useMemo(()=>r||t||e,[e,r,t]),v=!!S&&st(S)&&!et(S),M=i.useMemo(()=>{if(!S||!v)return null;const O=S.daemonId||S.routeId||"",_=Ot(S),E=na(S);return`${O}:${_}:${S.providerSessionId||""}:${E}`},[S,v]),A=i.useMemo(()=>!S||!v?"":na(S),[S,v]),{isCreatingChat:w,isRefreshingHistory:j,handleSwitchSession:K,handleNewChat:P,handleRefreshHistory:T}=Xl({sendDaemonCommand:a,activeConv:S,chats:(C=n.find(O=>O.id===(S==null?void 0:S.routeId)))==null?void 0:C.chats,updateRouteChats:o,setToasts:c,setClearedTabs:l}),W=i.useCallback(()=>{u(!0)},[]),H=i.useCallback(()=>{u(!1)},[]),R=i.useCallback(async()=>{if(!(!S||!v||p)){x(!0);try{const O=S.daemonId||S.routeId,_=Ot(S),E=na(S),U=await a(O,"list_saved_sessions",{agentType:_,providerType:_,kind:"cli",limit:50,...S.providerSessionId?{providerSessionId:S.providerSessionId}:{},...E?{workspace:E}:{}}),Q=(U==null?void 0:U.result)??U;b(Array.isArray(Q==null?void 0:Q.sessions)?Q.sessions:[])}catch(O){console.error("Refresh saved sessions failed",O),b([])}finally{x(!1)}}},[S,p,v,a]);i.useEffect(()=>{if(!m){N.current=null;return}if(!v){N.current=null,b([]),x(!1);return}!M||p||N.current!==M&&(N.current=M,R())},[R,m,p,v,M]);const I=i.useCallback(async O=>{if(!S||!v||!O.providerSessionId||!O.workspace)return;const _=S.daemonId||S.routeId,E=Ot(S);try{f(O.providerSessionId);const U=await a(_,"launch_cli",{cliType:E,dir:O.workspace,resumeSessionId:O.providerSessionId,initialModel:Hc(O.summaryMetadata,"model",{preferShortValue:!0})||void 0}),Q=(U==null?void 0:U.result)??U,xe=typeof(Q==null?void 0:Q.sessionId)=="string"?Q.sessionId:typeof(Q==null?void 0:Q.id)=="string"?Q.id:"";xe&&d(de=>{const Z=new URLSearchParams(de);return Z.set("activeTab",xe),Z},{replace:!0}),H()}catch(U){console.error("Resume saved session failed",U)}finally{f(null)}},[H,S,v,a,d]);return{historyModalOpen:m,openHistoryModal:W,closeHistoryModal:H,historyTargetConv:S,isSavedSessionHistoryTarget:v,isHistoryCreatingChat:w,isHistoryRefreshingHistory:j,handleHistorySwitchSession:K,handleHistoryNewChat:P,handleHistoryRefresh:T,savedHistorySessions:h,savedHistoryFilters:k,setSavedHistoryFilters:y,missingWorkspaceResumePath:A,isSavedHistoryLoading:p,resumingSavedHistorySessionId:g,handleRefreshSavedHistory:R,handleResumeSavedHistorySession:I}}function Db({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l}){const[d,m]=i.useState(null),[u,h]=i.useState(null),b=i.useMemo(()=>{if(e||!n)return null;const g=l(n);return g&&!st(g)&&!et(g)?g:null},[e,n,l]),k=i.useMemo(()=>{const g=d==null?void 0:d.routeId;if(!g)return null;const f=d!=null&&d.tabKey?o.find(N=>N.tabKey===d.tabKey):a?o.find(N=>N.tabKey===a):null;return(f==null?void 0:f.routeId)===g?f:Et(o,g)},[o,d,a]),y=i.useMemo(()=>{if(k)return c.find(g=>g.id===k.routeId)},[c,k]);i.useEffect(()=>{b&&(m({routeId:b.routeId,tabKey:fi(b)}),h(b),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,b]);const p=i.useCallback(g=>{g&&(m({routeId:g.routeId,tabKey:fi(g)}),h(g))},[]),x=i.useCallback(()=>{m(null),h(null)},[]);return{remoteDialogConv:k,remoteDialogIdeEntry:y,remoteDialogActiveConv:u,setRemoteDialogActiveConv:h,openRemoteDialog:p,closeRemoteDialog:x}}function Eb({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l,activeConv:d,sendDaemonCommand:m}){const{remoteDialogConv:u,remoteDialogIdeEntry:h,remoteDialogActiveConv:b,setRemoteDialogActiveConv:k,openRemoteDialog:y,closeRemoteDialog:p}=Db({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l}),[x,g]=i.useState(!1),[f,N]=i.useState(null),S=i.useCallback(async A=>{const w=A||d;!w||!st(w)&&!et(w)||(N(w),g(!0))},[d]),v=i.useCallback(()=>{g(!1),N(null)},[]),M=i.useCallback(async A=>{const w=f||d;if(!w||!st(w)&&!et(w)){v();return}g(!1);try{const j=Ot(w),K=w.routeId||w.daemonId||"";await m(K,"stop_cli",{cliType:j,targetSessionId:w.sessionId,mode:A})}catch(j){console.error("Stop CLI failed:",j)}finally{N(null)}},[d,v,f,m]);return{remoteDialogConv:u,remoteDialogIdeEntry:h,remoteDialogActiveConv:b,setRemoteDialogActiveConv:k,openRemoteDialog:y,closeRemoteDialog:p,cliStopDialogOpen:x,cliStopTargetConv:f,requestCliStop:S,cancelCliStop:v,confirmCliStop:M}}function nd({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0,meshOnly:o=!1}){var N,S;const c=Ws(),l=ws(e),d=o?null:Xc(e),m=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),u=!o&&e.streamSource==="agent-stream"&&!!e.agentName,h=!o&&!u&&(e.transport==="pty"||e.transport==="acp"),b=Ds(e),k=Hf(e),y=(N=e.settings)==null?void 0:N.meshNodeFor,p=e.meshQueueStats,x=(S=e.settings)==null?void 0:S.meshCoordinatorFor;if(!m&&!u&&!h&&!d&&!y&&!p)return null;const g=i.useCallback(()=>{if(n){n();return}l&&c("/dashboard",{state:{openMachineId:l}})},[l,c,n]),f=i.useCallback(()=>{if(r){r();return}const v=td(e);v&&c(Zt(v))},[e,c,r]);return s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[m&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:f,title:k,children:[s.jsx(Tt,{size:12}),s.jsx("span",{children:k})]}):s.jsxs("span",{className:"conversation-meta-chip",title:k,children:[s.jsx(Tt,{size:12}),s.jsx("span",{children:k})]})),u&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:b,children:[s.jsx(_s,{size:12}),s.jsx("span",{children:b})]}),h&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:b,children:[s.jsx(_s,{size:12}),s.jsx("span",{children:b})]}),d&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:g,title:d,children:[s.jsx(Jt,{size:12}),s.jsx("span",{children:d})]}):s.jsxs("span",{className:"conversation-meta-chip",title:d,children:[s.jsx(Jt,{size:12}),s.jsx("span",{children:d})]})),y&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(Jt,{size:12}),s.jsx("span",{children:"Mesh Node"})]}),x&&p&&s.jsxs("span",{className:`conversation-meta-chip ${p.pending>0?"is-active":""}`,style:p.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${p.pending} pending, ${p.assigned} assigned, ${p.completed} completed, ${p.failed} failed`,children:[s.jsx(Fu,{size:12}),s.jsxs("span",{children:[p.pending," Pending"]})]})]})}function aa(e,t=!0){return(e??!0)&&t}const Po=i.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:o,handleModalButton:c,handleRelaunch:l,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u=null,handleFocusAgent:h,isFocusingAgent:b,actionLogs:k,userName:y,scrollToBottomRequestNonce:p,isInputActive:x=!0,isVisible:g=!0}){const f=n,N=!n,S=aa(g,f),v=aa(g,N),M=aa(g),A=$l(t),w=A.status||A.modalMessage||A.modalButtons?{...t,...A.status?{status:A.status}:{},...A.modalMessage!==void 0?{modalMessage:A.modalMessage}:{},...A.modalButtons!==void 0?{modalButtons:A.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(Oc,{activeConv:w,onModalButton:c}),s.jsx(nd,{conversation:w,className:"chat-pane-meta-row mx-3 mt-1",meshOnly:!0}),w.transport!=="pty"&&w.transport!=="acp"&&w.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(xr,{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,w.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:f?"visible":"hidden",pointerEvents:f?"auto":"none"},children:s.jsx(rh,{activeConv:w,clearToken:r,terminalRef:o,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,isVisible:S,isInputActive:x&&S})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:N?"visible":"hidden",pointerEvents:N?"auto":"none"},children:s.jsx(Ba,{activeConv:w,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:h,isFocusingAgent:b,actionLogs:k,userName:y,scrollToBottomRequestNonce:p,isInputActive:x&&v,isVisible:v})})]}):s.jsx(Ba,{activeConv:w,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:h,isFocusingAgent:b,actionLogs:k,userName:y,scrollToBottomRequestNonce:p,isInputActive:x&&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 $b({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:o,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:d,onBack:m,onOpenNativeConversation:u,onOpenMachine:h,onOpenHistory:b,onOpenRemote:k,onStopCli:y,cliViewMode:p,onSetCliViewMode:x,handleSendChat:g,handleFocusAgent:f,handleModalButton:N,handleRelaunch:S}){const v=i.useRef(null),M=st(e)&&!t,A=M&&p==="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:m,type:"button","aria-label":"Back",children:s.jsx(eo,{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:lt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(nd,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>h(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[M&&p&&s.jsx(vo,{mode:p,onChange:x,compact:!0}),M&&y&&s.jsx("button",{onClick:()=>{y(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(vt,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>b(e),type:"button",children:s.jsx(to,{size:14})}),!t&&!M&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>k(e),type:"button",children:s.jsx(Tt,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(Po,{activeConv:e,clearToken:0,isCliTerminal:A,ideEntry:n,terminalRef:v,handleModalButton:N,handleRelaunch:S,handleSendChat:g,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:f,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const oa={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 Bb(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function ad(){const[e,t]=i.useState("unix"),[r,n]=i.useState("powershell"),[a,o]=i.useState(!1),c=e==="unix"?"unix":r;i.useEffect(()=>{t(Bb())},[]);const l=i.useCallback(()=>{navigator.clipboard.writeText(oa[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:oa[c].prompt}),s.jsx("span",{className:"flex-1 break-all",children:oa[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 od({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Tt},{key:"chats",label:"Chats",icon:zt}];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 Kr({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 js({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 tr({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 Kb({conversation:e,onCancel:t,onConfirm:r}){const n=lt(e),a=gs(e);return s.jsxs("div",{className:"fixed inset-0 z-[1400] 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",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:t}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-hide-confirm-title",className:"fade-in relative w-full sm:w-[min(92vw,420px)] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] border border-border-subtle bg-bg-primary shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-border-subtle bg-[var(--surface-primary)] px-4 py-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base font-extrabold text-text-primary",children:"Hide this chat from the inbox?"}),s.jsx("div",{className:"mt-1 text-[13px] leading-relaxed text-text-muted",children:"This only collapses the chat locally. You can restore it from Hidden tabs."})]}),s.jsx("button",{type:"button",className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary text-text-secondary transition-colors hover:bg-surface-primary hover:text-text-primary",onClick:t,"aria-label":"Cancel hide chat",children:s.jsx(vt,{size:16})})]}),s.jsx("div",{className:"px-4 py-4",children:s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary/60 px-3.5 py-3",children:[s.jsx("div",{className:"truncate text-sm font-bold text-text-primary",children:n}),s.jsx("div",{className:"mt-1 truncate text-xs text-text-muted",children:a})]})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 border-t border-border-subtle bg-bg-secondary px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))]",children:[s.jsx("button",{type:"button",className:"btn btn-secondary min-h-[40px] px-4 text-sm",onClick:t,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary min-h-[40px] px-4 text-sm",onClick:r,children:"Hide tab"})]})]})]})}function Or({item:e,type:t,getAvatarText:r,onOpenConversation:n,onRequestHideConversation:a,onCollectChatDebugBundle:o}){const c=t==="needs_attention"||t==="task_complete",l=t==="working",d=t==="earlier",m=t==="task_complete",{isReconnecting:u,isConnecting:h}=Fs(e.conversation),b=lt(e.conversation),k=gs(e.conversation),y=xl(e.conversation,{requiresAction:t==="needs_attention"}),p=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",x=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",g=d?"text-text-secondary":"text-text-primary",f=d?"text-text-muted":"text-text-secondary",N=d?"text-text-secondary opacity-80":"text-text-muted",S=d?"text-text-muted opacity-80":"text-text-muted",v=!l&&!m,M="text-[color:var(--status-warning)]",A=w=>{if(!o)return;w.preventDefault(),w.stopPropagation();const j=o==null?void 0:o(e.conversation);Promise.resolve(j).catch(K=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",K)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${p}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",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.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${x}`,style:c?{color:"var(--accent-on-primary)"}:void 0,children:r(b)}),a&&s.jsxs("button",{type:"button",className:"mobile-inbox-hide-button inline-flex min-h-7 items-center justify-center gap-1 rounded-full border border-border-subtle bg-bg-primary/70 px-2 text-[10px] font-semibold text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:w=>{w.preventDefault(),w.stopPropagation(),a()},"aria-label":`Hide ${b}`,title:"Hide conversation",children:[s.jsx(so,{size:11}),s.jsx("span",{children:"Hide"})]})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>n(e.conversation),onContextMenu:A,type:"button",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${g}`,children:b}),v&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${S}`,children:Kc(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${f}`,children:[s.jsx("span",{className:"truncate",children:k}),s.jsx($s,{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…"})]}):h?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):y==="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] ${N}`,children:e.preview})]}),c&&!m&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),m&&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"})]})},e.conversation.tabKey)}function Hi({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 Ob({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:o,machineCards:c,getAvatarText:l,actionLogs:d,sendDaemonCommand:m,onOpenConversation:u,onShowAllHidden:h,onHideConversation:b,onOpenNewSession:k,onOpenMachine:y,onOpenSettings:p,onSectionChange:x,wsStatus:g="connected",isStandalone:f=!1,onCollectChatDebugBundle:N}){const[S,v]=i.useState(null),M=g==="disconnected"||g==="reconnecting"||g==="offline"||g==="auth_failed",A=c.length>0,w=t.length>0||r.length>0||n.length>0||a.length>0,j=e==="machines"?"Machines":"Chats",K=f?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",P=f?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",T=i.useCallback(async R=>{const I=Es(R);if(!I)return;const C=Array.isArray(R.messages)?R.messages:[],O=sl({activeConv:R,visibleMessages:C,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:C.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),_=await m(I,"get_chat_debug_bundle",{...is(R),delivery:"daemon_file",frontendSnapshot:O}),E=mn(_),U=al(E),Q=await nl(U);Q==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),nt.showToast(rl(E,{locatorCopyStatus:Q}),Q==="failed"?"warning":"success")},[d,m]),W=N||T,H=i.useCallback(()=>{S&&(b==null||b(S),v(null))},[S,b]);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:j}),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(jn,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:p,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(wn,{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] ${P}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:M?s.jsx(tr,{icon:s.jsx(Hi,{}),title:g==="offline"?"Network offline":g==="auth_failed"?"Session expired":"Reconnecting",subtitle:g==="offline"?"Waiting for network…":g==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):c.length===0?s.jsx(tr,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:f?"Waiting for your daemon":"Connect your machines",subtitle:f?"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:!f&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(ad,{})})}):s.jsx(js,{children:c.map((R,I)=>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] ${I>0?"border-t border-border-subtle/70":""}`,onClick:()=>y(R.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(R.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:R.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:R.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[R.unread," new"]}):R.total>0?`${R.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:R.subtitle}),R.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[R.total," chat",R.total!==1?"s":"",R.unread>0?` · ${R.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},R.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(Kr,{title:"Needs attention",className:"mb-0"}),s.jsx(js,{children:t.map((R,I)=>s.jsx("div",{className:I>0?"border-t border-border-subtle/70":"",children:s.jsx(Or,{item:R,type:"needs_attention",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:b?()=>v(R.conversation):void 0,onCollectChatDebugBundle:W})},R.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(Kr,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(js,{children:r.map((R,I)=>s.jsx("div",{className:I>0?"border-t border-border-subtle/70":"",children:s.jsx(Or,{item:R,type:"task_complete",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:b?()=>v(R.conversation):void 0,onCollectChatDebugBundle:W})},R.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(Kr,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(js,{children:n.map((R,I)=>s.jsx("div",{className:I>0?"border-t border-border-subtle/70":"",children:s.jsx(Or,{item:R,type:"working",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:b?()=>v(R.conversation):void 0,onCollectChatDebugBundle:W})},R.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(Kr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(js,{children:a.map((R,I)=>s.jsx("div",{className:I>0?"border-t border-border-subtle/70":"",children:s.jsx(Or,{item:R,type:"earlier",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:b?()=>v(R.conversation):void 0,onCollectChatDebugBundle:W})},R.conversation.tabKey))}):w?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):M?s.jsx(tr,{icon:s.jsx(Hi,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):A?s.jsx(tr,{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(zt,{size:20})}),title:"No conversations yet",subtitle:yl,children:k&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:k,"aria-label":Bt,title:Bt,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:Bt})]})}):s.jsx(tr,{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(js,{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:h,children:"Restore all"})]})})})]}),e==="chats"&&k&&w&&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:k,"aria-label":Bt,title:Bt,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&&s.jsx(Kb,{conversation:S,onCancel:()=>v(null),onConfirm:H}),s.jsx(od,{section:e,onSectionChange:x})]})}function Wb(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 id(e){const t=[e.workspace||"Workspace unknown"],r=bs(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=Wb(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function Pn({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:o="",confirmLabel:c="Use this folder",onClose:l,onNavigate:d,onConfirm:m}){const[u,h]=i.useState(r);i.useEffect(()=>{h(r)},[r]);const b=yb(r),k=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(vt,{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:()=>{!b||a||d(b)},disabled:!b||a,children:[s.jsx(eo,{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:y=>h(y.target.value),onKeyDown:y=>{y.key!=="Enter"||!k||a||(y.preventDefault(),d(k))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),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:()=>{!k||a||d(k)},disabled:!k||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(y=>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(y.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(xs,{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:y.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:y.path})]})]},y.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:()=>m(k||r),disabled:!k&&!r||a,children:c})]})]})})}function _o({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:d=!1,showArgsInput:m,argsValue:u,onArgsChange:h,showModelInput:b,modelValue:k,onModelChange:y,historyProviderNode:p,onConfirm:x,onCancel:g}){const f=n==null?void 0:n.find(N=>N.key===a);return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:g,"aria-label":"Close launch confirmation",children:s.jsx(vt,{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:N=>o(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:n.map(N=>s.jsx("option",{value:N.key,children:N.label},N.key))}),(f==null?void 0:f.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:f.description})]}),p,r.map(N=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:N.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:N.value})]},`${N.label}:${N.value}`)),b&&y&&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:k||"",onChange:N=>y(N.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),m&&h&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:u||"",onChange:N=>h(N.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled: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:g,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:x,disabled:d,children:[s.jsx(no,{size:14}),d?l:c]})]})]})})}function Ui(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function ps(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?"⭐ ":""}${Ui(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:Ui(c),description:c,workspaceId:null,workspacePath:c}),n){const d=`saved:${n}`;if(o.some(m=>m.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 Fb(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Hb(e){return[Fb(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Ub(e){return e.lastLaunchedAt?kn(e.lastLaunchedAt):""}function cd(e){return{metaText:Hb(e),updatedLabel:Ub(e)}}function ia(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function zb({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:o}){var tt,mt,ht,bt;const c=jr(),[l,d]=i.useState(!1),m=(((tt=e.detectedIdes)==null?void 0:tt.length)||0)>0,u=i.useMemo(()=>(e.workspaces||[]).map(Te=>({id:Te.id,path:Te.path,label:Te.label})),[e]),h=e.defaultWorkspaceId||null,[b,k]=i.useState(h||((mt=u[0])==null?void 0:mt.id)||""),[y,p]=i.useState(""),[x,g]=i.useState(""),[f,N]=i.useState([]),[S,v]=i.useState(!1),[M,A]=i.useState(""),[w,j]=i.useState(!1),[K,P]=i.useState(ia(m,t.length,r.length)),T=i.useRef(null),[W,H]=i.useState(null),R=i.useRef("__home__"),[I,C]=i.useState("__home__"),[O,_]=i.useState(""),[E,U]=i.useState(""),[Q,xe]=i.useState(""),[de,Z]=i.useState([]),[he,we]=i.useState(()=>jt().textQuery),[be,X]=i.useState(()=>jt().workspaceQuery),[ue,ge]=i.useState(()=>jt().modelQuery),[te,le]=i.useState(()=>jt().resumableOnly),[Ne,me]=i.useState(()=>jt().sortMode),[pe,oe]=i.useState(!1),[fe,ie]=i.useState(!1),D=i.useRef(null),z=i.useRef(null);i.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const ce=b==="__custom__"?y.trim():((ht=u.find(Te=>Te.id===b))==null?void 0:ht.path)||"",se=b==="__custom__"&&!!ce&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),q=b!=="__custom__"&&((bt=u.find(Te=>Te.id===b))==null?void 0:bt.path)||"",ke=i.useMemo(()=>(e.recentLaunches||[]).map(Te=>Te.workspace),[e]),ve=i.useCallback(async Te=>{v(!0),A("");try{const Ue=await a(Te);g(Ue.path),p(Ue.path),N(Ue.directories)}catch(Ue){A(Ue instanceof Error?Ue.message:"Could not load folder")}finally{v(!1)}},[a]),Le=i.useCallback(()=>{var Ue;k("__custom__"),j(!0);const Te=Ln(e.platform,An(y.trim(),q,ke,e.defaultWorkspacePath,(Ue=u.find(Qe=>Qe.id===h))==null?void 0:Ue.path,u.map(Qe=>Qe.path)));ve(Te)},[y,h,ve,ke,q,e.platform,u]),Ae=i.useCallback(Te=>{if(Te!=null&&Te.workspaceId){k(Te.workspaceId),p("");return}if(Te!=null&&Te.workspacePath){k("__custom__"),p(Te.workspacePath);return}k(""),p("")},[]),B=i.useCallback(Te=>{if(k(Te),Te==="__custom__"){Le();return}p("")},[Le]),Ie=i.useCallback(Te=>{k("__custom__"),p(Te)},[]),Pe=i.useCallback((Te,Ue)=>{T.current=Ue,R.current=Te.selectedWorkspaceKey||"__home__",C(Te.selectedWorkspaceKey||"__home__"),_(Te.initialArgs||""),U(Te.initialModel||""),xe(""),Z([]);const Qe=Te.providerType?`${e.id}:${Te.providerType}`:null;if(ph(z.current,Qe)){const ze=jt();we(ze.textQuery),X(ze.workspaceQuery),ge(ze.modelQuery),le(ze.resumableOnly),me(ze.sortMode)}z.current=Qe,H(Te),Te.providerType&&o&&(oe(!0),o(Te.providerType).then(ze=>Z(ze||[])).catch(ze=>console.warn("Failed to load saved sessions",ze)).finally(()=>oe(!1)))},[o,e.id]),Fe=i.useMemo(()=>vl(de,{textQuery:he,workspaceQuery:be,modelQuery:ue,resumableOnly:te,sortMode:Ne}),[ue,te,de,Ne,he,be]);i.useEffect(()=>{Q&&(Fe.some(Te=>Te.providerSessionId===Q)||xe(""))},[Fe,Q]);const He=i.useCallback(()=>{T.current&&(ie(!0),T.current().finally(()=>{T.current=null,ie(!1),H(null)}))},[]),qe=i.useCallback(()=>{T.current=null,H(null)},[]),Ye=i.useCallback(Te=>{R.current=Te,C(Te)},[]);return i.useEffect(()=>{var Te;D.current!==e.id&&(D.current=e.id,k(h||((Te=u[0])==null?void 0:Te.id)||"__custom__"),p(""),g(""),N([]),A(""),j(!1),we(jt().textQuery),X(jt().workspaceQuery),ge(jt().modelQuery),le(jt().resumableOnly),me(jt().sortMode),z.current=null,P(ia(m,t.length,r.length)))},[r.length,t.length,h,m,e.id,u]),i.useEffect(()=>{var Te;b!=="__custom__"&&(b&&u.some(Ue=>Ue.id===b)||k(h||((Te=u[0])==null?void 0:Te.id)||"__custom__"))},[h,b,u]),i.useEffect(()=>{K==="ide"&&m||K==="cli"&&t.length>0||K==="acp"&&r.length>0||P(ia(m,t.length,r.length))},[K,r.length,t.length,m]),{showAllRecent:l,setShowAllRecent:d,hasIdeOptions:m,workspaceRows:u,defaultWorkspaceId:h,workspaceChoice:b,customWorkspacePath:y,browseCurrentPath:x,browseDirectories:f,browseBusy:S,browseError:M,browseDialogOpen:w,activeLauncherKind:K,launchConfirm:W,launchConfirmWorkspaceKeyRef:R,launchConfirmWorkspaceKey:I,launchConfirmArgs:O,launchConfirmModel:E,launchConfirmResumeId:Q,launchConfirmSavedSessions:de,launchConfirmTextFilter:he,launchConfirmWorkspaceFilter:be,launchConfirmModelFilter:ue,launchConfirmResumableOnly:te,launchConfirmSortMode:Ne,filteredLaunchConfirmSavedSessions:Fe,launchConfirmSessionsLoading:pe,launchConfirmBusy:fe,resolvedWorkspacePath:ce,canCreateMissingWorkspace:se,openBrowseDialog:Le,loadBrowsePath:ve,handleWorkspaceChoiceChange:B,chooseCustomWorkspacePath:Ie,setCustomWorkspacePath:p,setBrowseDialogOpen:j,setActiveLauncherKind:P,openLaunchConfirm:Pe,handleConfirmLaunch:He,closeLaunchConfirm:qe,setWorkspaceSelectionFromOption:Ae,setLaunchConfirmWorkspaceKeyAndSync:Ye,setLaunchConfirmArgs:_,setLaunchConfirmModel:U,setLaunchConfirmResumeId:xe,setLaunchConfirmTextFilter:we,setLaunchConfirmWorkspaceFilter:X,setLaunchConfirmModelFilter:ge,setLaunchConfirmResumableOnly:le,setLaunchConfirmSortMode:me}}function Vb({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:c,machineAction:l,isStandalone:d,section:m,showBottomNav:u,onBack:h,onSectionChange:b,onOpenConversation:k,onOpenRecent:y,onOpenMachineDetails:p,onMachineUpgrade:x,onLaunchDetectedIde:g,onAddWorkspace:f,onBrowseDirectory:N,onLaunchWorkspaceProvider:S,onListSavedSessions:v}){const M=I=>I==="ide"?"IDE":I==="cli"?"CLI":"ACP",A=r.slice(0,4),w=t.slice(0,3),j=zb({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:N,onListSavedSessions:v}),K=i.useMemo(()=>A.map(I=>{const{metaText:C,updatedLabel:O}=cd(I);return{key:`recent-launch:${I.id}`,primary:I.label,secondary:C,updatedLabel:O,onClick:()=>{const{options:_,selectedKey:E}=ps({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspacePath:I.workspace});j.openLaunchConfirm({title:I.kind==="ide"?ls("restart-ide",I.label):I.providerSessionId?ko(I.label):ls("start-fresh",I.label),description:I.kind==="ide"?ds("restart-ide"):I.providerSessionId?So():ds("start-fresh"),confirmLabel:I.kind==="ide"?Bs("restart-ide"):I.providerSessionId?pn(!0):Bs("start-fresh"),busyLabel:I.kind==="ide"?Ks("restart-ide"):I.providerSessionId?wo(!0):Ks("start-fresh"),workspaceOptions:_,selectedWorkspaceKey:E,details:[{label:"Mode",value:M(I.kind)},...I.providerType?[{label:"Provider",value:I.providerType}]:[]]},async()=>{const U=_.find(Q=>Q.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption(U),await y({...I,workspace:(U==null?void 0:U.workspacePath)??null})})}}}),[j,y,A]),P=i.useMemo(()=>w.map(I=>({key:`recent-chat:${I.conversation.tabKey}`,primary:lt(I.conversation),secondary:Zp(I.conversation,{timestampLabel:I.timestamp?Kc(I.timestamp):null}),unread:I.unread,onClick:()=>k(I.conversation)})),[k,w]),T=j.showAllRecent?K:K.slice(0,4),W=K.length>0,H=P.length>0,R=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 ${R} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:h,type:"button","aria-label":"Back",children:s.jsx(eo,{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:It(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:P.map(I=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${I.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:I.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:I.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:I.secondary})]},I.key))})]}),W&&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:T.map(I=>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:I.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:I.primary}),I.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:I.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:I.secondary})]},I.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:()=>j.setShowAllRecent(I=>!I),children:j.showAllRecent?"Show fewer":`Show ${K.length-4} more`})})]}),(j.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:j.workspaceChoice,onChange:I=>j.handleWorkspaceChoiceChange(I.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:j.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[j.workspaceRows.map(I=>s.jsxs("option",{value:I.id,children:[I.id===j.defaultWorkspaceId?"⭐ ":"",Nn(I.path,I.label)||I.path]},I.id)),s.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):s.jsx("option",{value:"__custom__",children:"Select workspace…"})}),j.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(xs,{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:j.resolvedWorkspacePath||j.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:j.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:()=>{j.resolvedWorkspacePath&&f(j.resolvedWorkspacePath)},disabled:!j.resolvedWorkspacePath||j.browseBusy,children:"Save as workspace"})]})]}),j.resolvedWorkspacePath&&s.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath})]})}),s.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[j.hasIdeOptions&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${j.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:()=>j.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${j.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:()=>j.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${j.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:()=>j.setActiveLauncherKind("acp"),children:"ACP"})]}),j.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:j.activeLauncherKind==="ide"?"Choose an IDE":j.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),s.jsx("div",{className:"grid grid-cols-1 gap-2",children:j.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(I=>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:C,selectedKey:O}=ps({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspaceId:j.workspaceChoice!=="__custom__"?j.workspaceChoice:null,currentWorkspacePath:j.resolvedWorkspacePath});j.openLaunchConfirm({title:`Launch ${I.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:C,selectedWorkspaceKey:O,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:I.name}]},async()=>{const _=C.find(E=>E.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption(_),g(I.type,{workspacePath:(_==null?void 0:_.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:I.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath||"Use selected workspace"})]},I.type)):(j.activeLauncherKind==="cli"?n:a).map(I=>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 C=j.activeLauncherKind==="cli"?"cli":"acp",{options:O,selectedKey:_}=ps({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspaceId:j.workspaceChoice!=="__custom__"?j.workspaceChoice:null,currentWorkspacePath:j.resolvedWorkspacePath});j.openLaunchConfirm({title:`Launch ${I.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${C.toUpperCase()}`,workspaceOptions:O,selectedWorkspaceKey:_,details:[{label:"Mode",value:C.toUpperCase()},{label:"Provider",value:I.displayName}],showArgsInput:!0,showModelInput:C==="acp",initialArgs:"",initialModel:"",providerType:I.type},async()=>{const E=O.find(U=>U.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption(E),S(C,I.type,{workspaceId:(E==null?void 0:E.workspaceId)??null,workspacePath:(E==null?void 0:E.workspacePath)??null,args:j.launchConfirmArgs,model:j.launchConfirmModel,resumeSessionId:j.launchConfirmResumeId||null})})},children:[s.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[I.icon?`${I.icon} `:"",I.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath||"Use selected workspace"})]},I.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,j.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:()=>f(j.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:x,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:p,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),j.browseDialogOpen&&s.jsx(Pn,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:j.browseCurrentPath,directories:j.browseDirectories,busy:j.browseBusy,error:j.browseError,confirmLabel:"Use this folder",onClose:()=>j.setBrowseDialogOpen(!1),onNavigate:I=>{j.loadBrowsePath(I)},onConfirm:I=>{j.chooseCustomWorkspacePath(I),j.setBrowseDialogOpen(!1)}}),j.launchConfirm&&s.jsx(_o,{title:j.launchConfirm.title,description:j.launchConfirm.description,details:j.launchConfirm.details,workspaceOptions:j.launchConfirm.workspaceOptions,selectedWorkspaceKey:j.launchConfirmWorkspaceKey,onWorkspaceChange:j.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:j.launchConfirm.providerType?pn(!!j.launchConfirmResumeId):j.launchConfirm.confirmLabel,busyLabel:j.launchConfirm.providerType?void 0:j.launchConfirm.busyLabel,busy:j.launchConfirmBusy,showArgsInput:j.launchConfirm.showArgsInput,argsValue:j.launchConfirmArgs,onArgsChange:j.setLaunchConfirmArgs,showModelInput:j.launchConfirm.showModelInput,modelValue:j.launchConfirmModel,onModelChange:j.setLaunchConfirmModel,historyProviderNode:j.launchConfirm.providerType&&(j.launchConfirmSessionsLoading||j.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"}),j.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:jo()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:j.launchConfirmTextFilter,onChange:I=>j.setLaunchConfirmTextFilter(I.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:j.launchConfirmBusy||j.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:j.launchConfirmWorkspaceFilter,onChange:I=>j.setLaunchConfirmWorkspaceFilter(I.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:j.launchConfirmBusy||j.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:j.launchConfirmModelFilter,onChange:I=>j.setLaunchConfirmModelFilter(I.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:j.launchConfirmBusy||j.launchConfirmSessionsLoading}),s.jsxs("select",{value:j.launchConfirmSortMode,onChange:I=>j.setLaunchConfirmSortMode(I.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:j.launchConfirmBusy||j.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:j.launchConfirmResumableOnly,onChange:I=>j.setLaunchConfirmResumableOnly(I.target.checked),disabled:j.launchConfirmBusy||j.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:j.launchConfirmResumeId,onChange:I=>j.setLaunchConfirmResumeId(I.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:j.launchConfirmBusy||j.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:bh()}),j.filteredLaunchConfirmSavedSessions.map(I=>s.jsxs("option",{value:I.providerSessionId,disabled:!I.canResume,children:[I.title||I.providerSessionId," ",I.canResume?"":"(workspace missing)"]},I.providerSessionId))]}),!j.launchConfirmSessionsLoading&&j.launchConfirmSavedSessions.length>0&&j.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),j.launchConfirmResumeId&&(()=>{const I=j.filteredLaunchConfirmSavedSessions.find(O=>O.providerSessionId===j.launchConfirmResumeId);if(!I)return null;const C=id(I);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:C.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:C.providerSessionId}),s.jsx("div",{className:"mt-1",children:C.metaLine}),C.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:C.updatedLabel}),C.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:C.preview})]})})()]}),onConfirm:j.handleConfirmLaunch,onCancel:j.closeLaunchConfirm}),u&&s.jsx(od,{section:m,onSectionChange:b})]})}function Qr(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Gb(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:Qr(e)}function qb(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 Yb(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:bs(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;const a=br(n)?"cli":Ms(n)?"acp":"ide",o=bs(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(br(n)?n.cliName||n.type:Ms(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Ms(n)?o||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:n.lastMessageAt||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function Xb(e,t){const r=new Map;for(const n of t){const a=ws(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((h,b)=>b.timestamp-h.timestamp)[0]||null,c=(o==null?void 0:o.conversation)||null,l=Pa(n),d=a.filter(h=>h.unread||h.requiresAction).length,m=qb(n),u=[n.platform||"machine",m].filter(Boolean);return{id:n.id,label:It(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?eh(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 Jb(e){return e==="chat"}function Wr(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 Qb({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:o,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:b,onRequestedMobileSectionConsumed:k,setSelectedTabKey:y,setScreen:p,setSelectedMachineId:x,setSection:g,setMachineBackTarget:f,resetMachineAction:N}){const S=i.useRef(null),v=i.useCallback(M=>{if(!(M!=null&&M.sessionId))return;const A=cn(M,c),w=Math.max(Date.now(),fs(M),A.lastUpdated||0);Wr("mark_read:start",{tabKey:M.tabKey,sessionId:M.sessionId,displayPrimary:lt(M),inboxBucket:A.inboxBucket,unread:A.unread,lastSeenAt:A.lastSeenAt,lastUpdated:A.lastUpdated,activityAt:fs(M),readAt:w}),l(ws(M)||M.routeId,"mark_session_seen",{sessionId:M.sessionId,providerSessionId:M.providerSessionId,seenAt:w,completionMarker:A.completionMarker}).then(j=>{Wr("mark_read:result",{tabKey:M.tabKey,sessionId:M.sessionId,result:j})}).catch(j=>{Wr("mark_read:error",{tabKey:M.tabKey,sessionId:M.sessionId,error:j instanceof Error?j.message:String(j)})})},[c,l]);return i.useEffect(()=>{var A;if(!n){Jb(o)&&p("inbox"),y(((A=e[0])==null?void 0:A.tabKey)||null),S.current=null;return}if(o!=="chat"){S.current=null;return}const M=`${n.tabKey}:${n.sessionId||""}`;S.current!==M&&(S.current=M,v(n))},[e,v,o,n,p,y]),i.useEffect(()=>{if(!d)return;const M=e.find(A=>A.tabKey===d);M&&(y(M.tabKey),p("chat"),m==null||m())},[e,m,d,p,y]),i.useEffect(()=>{if(!u)return;const M=t.find(A=>A.id===u);M&&(x(M.id),N(),g("machines"),f("inbox"),p("machine"),h==null||h())},[t,h,u,N,f,p,g,x]),i.useEffect(()=>{b&&(g(b),p("inbox"),k==null||k())},[k,b,p,g]),i.useEffect(()=>{const M=r.filter(A=>A.inboxBucket==="task_complete"||A.unread);M.length!==0&&Wr("inbox_state",{screen:o,selectedTabKey:a,items:M.map(A=>{const w=cn(A.conversation,c);return{liveState:w,tabKey:A.conversation.tabKey,sessionId:A.conversation.sessionId,displayPrimary:lt(A.conversation),serverBucket:w.inboxBucket,computedBucket:A.inboxBucket,serverUnread:w.unread,computedUnread:A.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,activityAt:fs(A.conversation)}})})},[r,c,o,a]),{markConversationRead:v}}function Zb(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function zi(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function eg(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function tg({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const[a,o]=i.useState("idle"),[c,l]=i.useState(""),[d,m]=i.useState(null),u=i.useCallback(()=>{o("idle"),l(""),m(null)},[]),h=i.useCallback(async(f,N,S)=>{var v;try{o("loading"),l(`Launching ${N}…`);const M={ideType:N,enableCdp:!0};(v=S==null?void 0:S.workspacePath)!=null&&v.trim()&&(M.workspace=S.workspacePath.trim()),await e(f,"launch_ide",M),o("done"),l(`${N} launch requested`)}catch(M){o("error"),l(M instanceof Error?M.message:"Launch IDE failed"),console.error("Launch IDE failed",M)}},[e]),b=i.useCallback(async(f,N,S)=>{if(N.trim())try{o("loading"),l(S!=null&&S.createIfMissing?"Creating folder…":"Saving workspace…");const v=await e(f,"workspace_add",{path:N.trim(),createIfMissing:(S==null?void 0:S.createIfMissing)===!0});if(v!=null&&v.success){o("done"),l(S!=null&&S.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}o("error"),l((v==null?void 0:v.error)||"Could not save workspace")}catch(v){o("error"),l(v instanceof Error?v.message:"Could not save workspace")}},[e]),k=i.useCallback(async f=>{var N,S,v,M,A,w;try{o("loading"),l("Starting daemon upgrade…");const j=await e(f,"daemon_upgrade",{});if((N=j==null?void 0:j.result)!=null&&N.alreadyLatest){o("done"),l(`Already on v${((S=j==null?void 0:j.result)==null?void 0:S.version)||"latest"}.`);return}if((v=j==null?void 0:j.result)!=null&&v.upgraded||(M=j==null?void 0:j.result)!=null&&M.success){o("done"),l(`Upgrade to v${((A=j==null?void 0:j.result)==null?void 0:A.version)||"latest"} started. Daemon is restarting…`);return}o("error"),l(((w=j==null?void 0:j.result)==null?void 0:w.error)||"Upgrade failed")}catch(j){o("error"),l(j instanceof Error?j.message:"Upgrade failed")}},[e]),y=i.useCallback(async(f,N,S,v)=>{var w,j,K;const M=Date.now(),A={machineId:f,kind:N,providerType:S,workspaceId:(v==null?void 0:v.workspaceId)||null,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,startedAt:M};try{o("loading"),l(`Launching ${S}…`),m(A);const P={cliType:S};(w=v==null?void 0:v.workspacePath)!=null&&w.trim()?P.dir=v.workspacePath.trim():v!=null&&v.workspaceId&&(P.workspaceId=v.workspaceId),v!=null&&v.resumeSessionId&&(P.resumeSessionId=v.resumeSessionId),(j=v==null?void 0:v.args)!=null&&j.trim()&&(P.cliArgs=v.args.trim().split(/\s+/).filter(Boolean)),(K=v==null?void 0:v.model)!=null&&K.trim()&&(P.initialModel=v.model.trim());const T=await e(f,"launch_cli",P),W=(T==null?void 0:T.result)||T,H=(W==null?void 0:W.sessionId)||(W==null?void 0:W.id);if(T!=null&&T.success&&H){m(null),o("done"),l(`${S} launched`),t(Zt(H));return}if(T!=null&&T.success){o("loading"),l(`${S} launch requested — waiting for session…`);return}m(null),o("error"),l((T==null?void 0:T.error)||(W==null?void 0:W.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(P){if(eg(P)){o("loading"),l(`${S} launch requested — waiting for session…`);return}m(null),o("error"),l(P instanceof Error?P.message:`Could not launch ${N.toUpperCase()} workspace`)}},[t,e]),p=i.useCallback(async(f,N)=>{try{const S=await e(f,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),v=(S==null?void 0:S.result)??S;return Array.isArray(v==null?void 0:v.sessions)?v.sessions:[]}catch(S){return console.error("Failed to list saved sessions on mobile:",S),[]}},[e]),x=i.useCallback(async(f,N)=>Rn(e,f,N),[e]);i.useEffect(()=>{if(!d)return;const f=zi(d.workspacePath),N=r.find(v=>{var P,T,W,H;if(!v||v.type==="adhdev-daemon"||Zb(v.daemonId||v.id)!==d.machineId||(v.transport==="acp"?"acp":v.transport==="pty"?"cli":null)!==d.kind||String(v.agentType||v.type||"")!==d.providerType)return!1;const j=String(v.providerSessionId||"");if(d.resumeSessionId&&j)return j===d.resumeSessionId;if(f){const R=zi(v.workspace||v.runtimeWorkspaceLabel);return R?R===f:!1}return Number(v.lastUpdated||v._lastUpdate||v.timestamp||((H=(W=(T=(P=v.activeChat)==null?void 0:P.messages)==null?void 0:T.at)==null?void 0:W.call(T,-1))==null?void 0:H.timestamp)||0)>=d.startedAt-5e3});if(!N)return;const S=sd({entrySessionId:N.sessionId,entryInstanceId:N.instanceId,entryRouteId:N.id,conversations:n});S&&(m(null),o("done"),l(`${d.providerType} launched`),t(Zt(S)))},[n,r,t,d]),i.useEffect(()=>{if(!d)return;const f=window.setTimeout(()=>{m(N=>!N||N.startedAt!==d.startedAt?N:(o("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(f)},[d]);const g=i.useCallback(async(f,N)=>{if(N.kind==="ide"&&N.providerType){await h(f,N.providerType,{workspacePath:N.workspace||null});return}(N.kind==="cli"||N.kind==="acp")&&N.providerType&&await y(f,N.kind,N.providerType,{workspacePath:N.workspace||null,resumeSessionId:N.providerSessionId||null})},[h,y]);return{machineAction:{state:a,message:c},resetMachineAction:u,handleLaunchDetectedIde:h,handleAddWorkspace:b,handleMachineUpgrade:k,handleLaunchWorkspaceProvider:y,handleListSavedSessions:p,handleBrowseDirectory:x,handleOpenRecent:g}}function sg({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:o,setScreen:c,setSelectedMachineId:l,setSection:d,setMachineBackTarget:m}){const u=i.useCallback(g=>{o(g.tabKey),c("chat"),n(g)},[n,c,o]),h=i.useCallback(g=>{const f=e.find(N=>N.routeId===g.routeId&&N.streamSource==="native");f&&(o(f.tabKey),c("chat"),n(f))},[e,n,c,o]),b=i.useCallback(()=>{n(t),c("inbox")},[n,t,c]),k=i.useCallback((g,f="inbox")=>{l(g),a(),d("machines"),m(f),c("machine")},[a,m,c,d,l]),y=i.useCallback(g=>{const f=ws(g);f&&k(f,"chat")},[k]),p=i.useCallback(()=>{a(),c(r)},[r,a,c]),x=i.useCallback(g=>{d(g),c("inbox")},[c,d]);return{openConversation:u,openNativeConversation:h,backFromConversation:b,openMachine:k,openConversationMachine:y,backFromMachine:p,changeMachineSection:x}}function ys(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function rg(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function ng({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,userName:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:b,onRequestedMobileSectionConsumed:k,onOpenHistory:y,onOpenRemote:p,onStopCli:x,wsStatus:g,isConnected:f,onShowAllHiddenConversations:N,onHideConversation:S,onOpenNewSession:v,liveSessionInboxState:M,setCliViewModeOverrides:A}){const[w,j]=i.useState(()=>{var q;return((q=e[0])==null?void 0:q.tabKey)||null}),[K,P]=i.useState(()=>e[0]?"chat":"inbox"),[T,W]=i.useState("chats"),[H,R]=i.useState(null),[I,C]=i.useState("inbox"),O=i.useRef([]),_=Ws(),E="0.9.80",U=i.useMemo(()=>e.find(q=>q.tabKey===w)||e[0]||null,[e,w]),Q=i.useMemo(()=>U?r.find(q=>q.id===U.routeId):void 0,[r,U]),xe=i.useMemo(()=>!U||et(U)||!st(U)?null:Hs(U),[U]),de=i.useMemo(()=>r.filter(q=>q.type==="adhdev-daemon").sort(uo),[r]),Z=i.useMemo(()=>de.find(q=>q.id===H)||null,[de,H]),he=In({sendDaemonCommand:a,activeConv:U||void 0,setActionLogs:o,isStandalone:c}),we=tg({sendDaemonCommand:a,navigate:_,ides:r,conversations:e}),be=i.useMemo(()=>e.map(q=>{const ke=K==="chat"&&(U==null?void 0:U.tabKey)===q.tabKey,ve=Sn(q,M,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ke}),Le=fs(q),Ae=hl(q);return{conversation:q,timestamp:Le,preview:Ae,unread:ve.unread,requiresAction:ve.requiresAction,isWorking:ve.isWorking,inboxBucket:ve.inboxBucket}}),[e,M,K,U]),{markConversationRead:X}=Qb({conversations:e,machineEntries:de,items:be,selectedConversation:U,selectedTabKey:w,screen:K,liveSessionInboxState:M,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:b,onRequestedMobileSectionConsumed:k,setSelectedTabKey:j,setScreen:P,setSelectedMachineId:R,setSection:W,setMachineBackTarget:C,resetMachineAction:we.resetMachineAction}),ue=sg({conversations:e,selectedConversation:U,machineBackTarget:I,markConversationRead:X,resetMachineAction:we.resetMachineAction,setSelectedTabKey:j,setScreen:P,setSelectedMachineId:R,setSection:W,setMachineBackTarget:C}),ge=i.useMemo(()=>Qr(be.filter(q=>q.requiresAction)),[be]),te=i.useMemo(()=>Qr(be.filter(q=>q.unread&&!q.requiresAction)),[be]),le=i.useMemo(()=>Gb(be.filter(q=>!q.unread&&!q.requiresAction&&q.isWorking),O.current),[be]);i.useEffect(()=>{O.current=le.map(q=>q.conversation.tabKey)},[le]);const Ne=i.useMemo(()=>Qr(be.filter(q=>!q.unread&&!q.requiresAction&&!q.isWorking)),[be]),me=i.useMemo(()=>Z?be.filter(q=>ws(q.conversation)===Z.id):[],[be,Z]),pe=i.useMemo(()=>Yb(Z,r),[r,Z]),oe=(Z==null?void 0:Z.version)||null,fe=!!Z&&!!oe&&!0&&oe!==E,ie=i.useMemo(()=>(Z==null?void 0:Z.availableProviders)||[],[Z]),D=i.useMemo(()=>ie.filter(q=>ys(q,"cli")).map(q=>({type:q.type,displayName:q.displayName||q.type,icon:q.icon})),[ie]),z=i.useMemo(()=>ie.filter(q=>ys(q,"acp")).map(q=>({type:q.type,displayName:q.displayName||q.type,icon:q.icon})),[ie]),ce=i.useMemo(()=>Xb(de,be),[be,de]),se=i.useCallback(async q=>{Z&&await we.handleOpenRecent(Z.id,q)},[we,Z]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:K==="chat"&&U?s.jsx($b,{selectedConversation:U,isAcp:et(U),isStandalone:c,selectedIdeEntry:Q,actionLogs:n,userName:l,isSendingChat:he.isSendingChat,sendFeedbackMessage:he.sendFeedbackMessage,isFocusingAgent:he.isFocusingAgent,handleModalButton:he.handleModalButton,handleRelaunch:he.handleRelaunch,onBack:ue.backFromConversation,onOpenNativeConversation:ue.openNativeConversation,onOpenMachine:ue.openConversationMachine,onOpenHistory:y,onOpenRemote:p,onStopCli:x,cliViewMode:xe,onSetCliViewMode:async q=>{await Hl({conversation:U,mode:q,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:A})},handleSendChat:he.handleSendChat,handleFocusAgent:he.handleFocusAgent}):K==="machine"&&Z?s.jsx(Vb,{selectedMachineEntry:Z,selectedMachineConversations:me,selectedMachineRecentLaunches:pe,cliProviders:D,acpProviders:z,selectedMachineNeedsUpgrade:fe,appVersion:E,machineAction:we.machineAction,isStandalone:c,section:T,showBottomNav:I==="inbox",onBack:ue.backFromMachine,onSectionChange:ue.changeMachineSection,onOpenConversation:ue.openConversation,onOpenRecent:se,onOpenMachineDetails:()=>_(`/machines/${Z.id}`),onMachineUpgrade:()=>we.handleMachineUpgrade(Z.id),onLaunchDetectedIde:(q,ke)=>we.handleLaunchDetectedIde(Z.id,q,ke),onAddWorkspace:(q,ke)=>we.handleAddWorkspace(Z.id,q,ke),onBrowseDirectory:q=>we.handleBrowseDirectory(Z.id,q),onLaunchWorkspaceProvider:(q,ke,ve)=>we.handleLaunchWorkspaceProvider(Z.id,q,ke,ve),onListSavedSessions:q=>we.handleListSavedSessions(Z.id,q)}):s.jsx(Ob,{section:T,attentionItems:ge,unreadItems:te,workingItems:le,completedItems:Ne,hiddenConversations:t,machineCards:ce,getAvatarText:rg,actionLogs:n,sendDaemonCommand:a,onOpenConversation:ue.openConversation,onShowAllHidden:N,onHideConversation:S,onOpenNewSession:v,onOpenMachine:ue.openMachine,onOpenSettings:()=>_("/settings"),onSectionChange:W,wsStatus:g,isConnected:f,isStandalone:c})})}function ca(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function ag({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:o}){const c=i.useRef(0),[l,d]=i.useState(!1),[m,u]=i.useState(null),h=i.useCallback(()=>{c.current=0,d(!1),u(null)},[]);i.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const b=i.useCallback(x=>{x.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,d(!0))},[]),k=i.useCallback(x=>{if(!x.dataTransfer.types.includes("text/tab-key"))return;if(x.preventDefault(),!ca(t,r)){u("merge");return}const g=x.currentTarget.getBoundingClientRect(),f=x.clientX-g.left,N=g.width/3;f<N?u("split-left"):f>N*2?u("split-right"):u("merge")},[t,r]),y=i.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,d(!1),u(null))},[]),p=i.useCallback(x=>{c.current=0,d(!1);const g=x.dataTransfer.getData("text/tab-key"),f=g?e.some(S=>S.tabKey===g):!1,N=m;if(u(null),o(),!!g){if(x.preventDefault(),N==="split-left"&&ca(t,r)){r==null||r(g,"split-left");return}if(N==="split-right"&&ca(t,r)){r==null||r(g,"split-right");return}if(f){a(g);return}n==null||n(g)}},[e,m,t,r,n,a,o]);return{dragOver:l,dropAction:m,resetDragState:h,handleDragEnter:b,handleDragOver:k,handleDragLeave:y,handleDrop:p}}function og(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 ig({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[o,c]=i.useState(t??null),[l,d]=i.useState(r??[]),[m,u]=i.useState(null),h=i.useRef(null),b=i.useRef(null),k=i.useRef(n),y=i.useRef(a);i.useEffect(()=>{k.current=n},[n]),i.useEffect(()=>{y.current=a},[a]),i.useEffect(()=>{t&&t!==o&&c(t)},[t,o]),i.useEffect(()=>{d(A=>{const w=og(A,e);return w.length===A.length&&w.every((j,K)=>j===A[K])?A:w})},[e]);const p=i.useMemo(()=>{const A=m??l;if(A.length===0)return e;const w=new Map(A.map((j,K)=>[j,K]));return[...e].sort((j,K)=>{const P=w.get(j.tabKey)??999,T=w.get(K.tabKey)??999;return P-T})},[e,m,l]);i.useEffect(()=>{var w,j;if(p.length===0){o!==null&&(c(null),(w=k.current)==null||w.call(k,null));return}if(o&&p.some(K=>K.tabKey===o))return;const A=p[0].tabKey;A!==o&&(c(A),(j=k.current)==null||j.call(k,A))},[p,o]);const x=i.useMemo(()=>p.find(A=>A.tabKey===o),[p,o]),g=i.useCallback(A=>{var w;c(A),(w=k.current)==null||w.call(k,A)},[]),f=i.useCallback((A,w,j)=>{d(K=>{var H;const P=K.filter(R=>R!==A),T=P.indexOf(w);if(T<0)return K;const W=j==="left"?T:T+1;return P.splice(W,0,A),(H=y.current)==null||H.call(y,P),P}),u(null)},[]),N=i.useCallback((A,w,j)=>{const P=(l.length>0?l:e.map(H=>H.tabKey)).filter(H=>H!==A),T=P.indexOf(w);if(T<0)return;const W=j==="left"?T:T+1;P.splice(W,0,A),h.current=P,u(P)},[l,e]),S=i.useCallback(()=>{var w;const A=h.current;A&&(d(A),(w=y.current)==null||w.call(y,A))},[]),v=i.useCallback(()=>{h.current=null,u(null)},[]),M=i.useCallback(A=>{d(w=>{var K;const j=w.filter(P=>P!==A);return j.push(A),(K=y.current)==null||K.call(y,j),j})},[]);return{activeTabId:o,activeConv:x,sortedConversations:p,previewOrderRef:h,draggingTabRef:b,selectTab:g,handleTabReorder:f,updatePreviewOrder:N,commitPreviewOrder:S,clearPreviewOrder:v,moveTabToEnd:M,setDraggingTabKey:A=>{b.current=A}}}function cg({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 Do({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",m=n?yl: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:m}),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:Bt,"aria-label":Bt,children:[s.jsx(Ac,{size:14}),s.jsx("span",{children:Bt})]})}),c&&s.jsx(ad,{}),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 ld="adhdev-tab-shortcuts";function dd(){try{return JSON.parse(localStorage.getItem(ld)||"{}")}catch{return{}}}function ud({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,c]=i.useState(()=>dd()),[l,d]=i.useState(null),m=i.useCallback(h=>{const b=[];return h.metaKey&&b.push(a?"⌘":"Meta"),h.ctrlKey&&b.push("Ctrl"),h.altKey&&b.push(a?"⌥":"Alt"),h.shiftKey&&b.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(b.push(h.key.length===1?h.key.toUpperCase():h.key),b.join("+"))},[a]),u=i.useCallback(h=>{c(h);try{localStorage.setItem(ld,JSON.stringify(h))}catch{}},[]);return i.useEffect(()=>{if(!e||!l)return;const h=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){d(null);return}const k=m(b);if(!k)return;const y={...o};for(const[p,x]of Object.entries(y))x===k&&delete y[p];y[l]=k,u(y),d(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,l,o,u,m]),i.useEffect(()=>{if(!e)return;const h=b=>{if(!(!b.ctrlKey&&!b.metaKey&&!b.altKey)){for(const[k,y]of Object.entries(o))if(t.includes(k)&&m(b)===y){b.preventDefault(),r(),n(k);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,o,t,r,n,m]),{isMac:a,tabShortcuts:o,shortcutListening:l,setShortcutListening:d,saveShortcuts:u}}const la=e=>{e.preventDefault()},lg=i.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:o,conversationKeys:c,draggingTabRef:l,onFocus:d,onSelectTab:m,onConversationActivated:u,onPreviewReorder:h,onReorderTab:b,onCommitPreviewOrder:k,onClearPreviewOrder:y,onDragStateReset:p,onDragTabKeyChange:x,onReceiveTab:g,onOpenContextMenu:f,longPressTimer:N,isGroupActive:S}){const v=Fs(t),M=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",A=v.isReconnecting,w=i.useCallback(C=>{l.current=t.tabKey,x(t.tabKey),C.dataTransfer.setData("text/tab-key",t.tabKey),C.dataTransfer.effectAllowed="move"},[t.tabKey,l,x]),j=i.useCallback(()=>{l.current=null,x(null),k(),y(),p()},[l,x,k,y,p]),K=i.useCallback(C=>{const O=l.current;if(!(!O||O===t.tabKey)&&C.dataTransfer.types.includes("text/tab-key")){C.preventDefault(),C.stopPropagation();const _=C.currentTarget.getBoundingClientRect(),E=C.clientX<_.left+_.width/2?"left":"right";h(O,t.tabKey,E)}},[t.tabKey,l,h]),P=i.useCallback(C=>{C.preventDefault(),C.stopPropagation();const O=C.dataTransfer.getData("text/tab-key");if(O&&O!==t.tabKey){const _=C.currentTarget.getBoundingClientRect(),E=C.clientX<_.left+_.width/2?"left":"right";c.includes(O)?b(O,t.tabKey,E):g&&g(O)}y()},[t.tabKey,c,b,g,y]),T=i.useCallback(C=>{C.stopPropagation(),d(),m(t.tabKey),u(t)},[t,u,d,m]),W=i.useCallback(C=>{C.preventDefault(),f(C.clientX,C.clientY,t.tabKey)},[t.tabKey,f]),H=i.useCallback(C=>{const O=C.touches[0];N.current=setTimeout(()=>{f(O.clientX,O.clientY,t.tabKey)},600)},[t.tabKey,N,f]),R=i.useCallback(()=>{N.current&&clearTimeout(N.current)},[N]),I=["adhdev-dockview-tab",M,r&&"is-active",S&&"is-group-active",A&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:I,draggable:!0,onDragStart:w,onDragEnd:j,onDragOver:K,onDrop:P,onClick:T,onContextMenu:W,onTouchStart:H,onTouchEnd:R,onTouchMove:R,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:v.isGenerating?s.jsx("div",{className:"tab-spinner"}):v.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):A?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):v.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:lt(t),children:lt(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[A?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:cs(t)}):v.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[cs(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:cs(t)}),s.jsx($s,{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 dg({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:o,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:h,onDragStateReset:b,onDragTabKeyChange:k,onReceiveTab:y,onHideTab:p,isGroupActive:x,allowTabShortcuts:g=!0}){const[f,N]=i.useState(null),S=i.useRef(null),v=i.useRef(null),M=i.useMemo(()=>e.map(W=>W.tabKey),[e]);vr("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(f==null?void 0:f.tabKey)||null});const{isMac:A,tabShortcuts:w,shortcutListening:j,setShortcutListening:K,saveShortcuts:P}=ud({enabled:g,sortedTabKeys:e.map(W=>W.tabKey),onFocus:o,onSelectTab:c});i.useEffect(()=>{if(!f)return;const W=H=>{const R=document.querySelector("[data-pane-context-menu]");R&&R.contains(H.target)||N(null)};return window.addEventListener("mousedown",W,!0),()=>window.removeEventListener("mousedown",W,!0)},[f]),i.useEffect(()=>{const W=v.current;if(!W)return;const H=R=>{Math.abs(R.deltaY)<=Math.abs(R.deltaX)||(R.preventDefault(),W.scrollLeft+=R.deltaY)};return W.addEventListener("wheel",H,{passive:!1}),()=>W.removeEventListener("wheel",H)},[]);const T=i.useCallback((W,H,R)=>{N({x:W,y:H,tabKey:R})},[]);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:v,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(W=>s.jsx(lg,{conv:W,isActive:t===W.tabKey,isDraggedTab:a.current===W.tabKey,isTaskCompleteUnread:n.has(W.tabKey),shortcut:g?w[W.tabKey]:void 0,conversationKeys:M,draggingTabRef:a,onFocus:o,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:h,onDragStateReset:b,onDragTabKeyChange:k,onReceiveTab:y,onOpenContextMenu:T,longPressTimer:S,isGroupActive:x},W.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),f&&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:f.x,top:f.y},children:[g&&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:la,onClick:W=>{W.stopPropagation(),K(f.tabKey),N(null)},children:["⌨ ",w[f.tabKey]?`Change shortcut (${w[f.tabKey]})`:"Set shortcut"]}),w[f.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:la,onClick:()=>{const W={...w};delete W[f.tabKey],P(W),N(null)},children:"✕ Remove shortcut"})]}),p&&s.jsxs(s.Fragment,{children:[g&&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:la,onClick:()=>{p(f.tabKey),N(null)},children:"🚫 Hide from Dashboard"})]})]}),g&&j&&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:W=>W.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. ",A?"⌘+1":"Ctrl+1",", ",A?"⌥+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 ug({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,hasRegisteredMachines:l,userName:d,groupIndex:m,onFocus:u,isSplitMode:h,numGroups:b,onMoveTab:k,onReceiveTab:y,style:p,onActiveTabChange:x,initialActiveTabId:g,initialTabOrder:f,onTabOrderChange:N,onHideTab:S,isFocused:v,allowTabShortcuts:M=!0,onOpenNewSession:A,liveSessionInboxState:w}){const{sendCommand:j}=gt(),K=i.useRef(null),{activeTabId:P,activeConv:T,sortedConversations:W,draggingTabRef:H,selectTab:R,handleTabReorder:I,updatePreviewOrder:C,commitPreviewOrder:O,clearPreviewOrder:_,moveTabToEnd:E,setDraggingTabKey:U}=ig({conversations:e,initialActiveTabId:g,initialTabOrder:f,onActiveTabChange:x,onTabOrderChange:N}),Q=In({sendDaemonCommand:a,activeConv:T,setActionLogs:o,isStandalone:c}),{dragOver:xe,dropAction:de,resetDragState:Z,handleDragEnter:he,handleDragOver:we,handleDragLeave:be,handleDrop:X}=ag({conversations:e,numGroups:b,onMoveTab:k,onReceiveTab:y,onOwnTabDrop:E,onClearPreviewOrder:_}),ue=T&&!et(T)&&Hs(T)==="terminal",ge=i.useMemo(()=>T?t.find(me=>me.id===T.routeId):void 0,[t,T]),te=i.useMemo(()=>T?n.filter(me=>me.routeId===T.tabKey):[],[n,T]),le=i.useMemo(()=>new Set(W.filter(me=>Wm(me,w,{isOpenConversation:me.tabKey===P})).map(me=>me.tabKey)),[P,w,W]);vr("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:P,dragOver:xe});const Ne=i.useCallback(me=>{me.streamSource==="agent-stream"&&me.agentType&&j(me.routeId,tl(),{agentType:me.agentType,...me.sessionId&&{targetSessionId:me.sessionId}}).catch(()=>{})},[j]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...p,outline:xe?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(dg,{conversations:W,activeTabId:P,groupIndex:m,numGroups:b,unreadTabKeys:le,draggingTabRef:H,onFocus:u,onSelectTab:R,onConversationActivated:Ne,onPreviewReorder:C,onReorderTab:I,onCommitPreviewOrder:O,onClearPreviewOrder:_,onDragStateReset:Z,onDragTabKeyChange:U,onMoveTab:k,onReceiveTab:y,onHideTab:S,isGroupActive:v??!1,allowTabShortcuts:M}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:he,onDragOver:we,onDragLeave:be,onDrop:X,children:[xe&&s.jsx(cg,{dropAction:de,canSplit:!!(b<4&&k)}),T?s.jsx(Po,{activeConv:T,clearToken:r[T.tabKey]||0,isCliTerminal:!!ue,ideEntry:ge,terminalRef:K,handleModalButton:Q.handleModalButton,handleRelaunch:Q.handleRelaunch,handleSendChat:Q.handleSendChat,isSendingChat:Q.isSendingChat,sendFeedbackMessage:Q.sendFeedbackMessage,handleFocusAgent:Q.handleFocusAgent,isFocusingAgent:Q.isFocusingAgent,actionLogs:te,userName:d,isInputActive:!h||!!v}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(Do,{conversationsCount:e.length,isSplitMode:h,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:A})})]})]})}function mg({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:o,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:h,userName:b,focusedGroup:k,focusGroup:y,moveTabToGroup:p,splitTabRelative:x,closeGroup:g,handleResizeStart:f,groupActiveTabIds:N,setGroupActiveTab:S,groupTabOrders:v,setGroupTabOrder:M,toggleHiddenTab:A,onOpenNewSession:w,allowTabShortcuts:j=!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((P,T)=>{const W=t&&n.length===r?`${n[T]}%`:void 0;return s.jsxs(Ct.Fragment,{children:[t&&T>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=>f(T-1,H),onDoubleClick:()=>g(T),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(ug,{style:t?{flexBasis:W??`${100/r}%`,flexGrow:W?0:1,flexShrink:W?0:1}:void 0,conversations:P,clearedTabs:o,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:h,userName:b,groupIndex:T,isFocused:t&&k===T,onFocus:()=>y(T),isSplitMode:t,numGroups:r,onMoveTab:(H,R)=>{R==="left"&&T>0?p(H,T-1):R==="right"&&T<r-1?p(H,T+1):R==="split-left"&&r<4?x(H,T,"left"):R==="split-right"&&r<4&&x(H,T,"right")},onReceiveTab:H=>p(H,T),onActiveTabChange:H=>S(T,H),initialActiveTabId:N[T],initialTabOrder:v[T],onTabOrderChange:H=>M(T,H),onHideTab:A,onOpenNewSession:w,allowTabShortcuts:j,liveSessionInboxState:K})]},T)})})}function md({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,o]=i.useState(null),[c,l]=i.useState(null);i.useEffect(()=>e?ut.onScreenshot("ide-page",(u,h)=>{if(u!==e)return;const b=new FileReader;b.onload=()=>o(b.result),b.readAsDataURL(h)}):void 0,[e]),i.useEffect(()=>{r!=="connected"&&o(null)},[r]),i.useEffect(()=>{var u;return e?((u=ut.onStatus)==null?void 0:u.call(ut,(h,b)=>{h===e&&b!=null&&b.screenshotUsage&&l(b.screenshotUsage)}))||(()=>{}):void 0},[e]),i.useEffect(()=>{o(null)},[e,t]),i.useEffect(()=>{const m=e?ut.get(e):null;if(!(!m||r!=="connected"))return n!=="chat"&&t?m.startScreenshots(t):m.stopScreenshots(t),()=>{m.stopScreenshots(t)}},[n,r,t,e]);const d=i.useCallback(async(m,u)=>{const h=e?ut.get(e):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(m,u,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:d}}const fd="adhdev-dashboard-action-shortcuts",fg=1200,pg=[["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 hg(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function at(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 pd(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:at("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:at("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:at("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:at("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:at("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:at("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:at("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:at("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:at("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:at("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:at("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:at("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:at("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:at("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:at("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:at("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:at("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:at("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:at("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:at("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:at("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:at("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:at("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:at("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:at("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:at("toggleCliView",e)}]}function Va(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function yn(e){const t=Object.fromEntries(pd(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(fd)||"{}"),n={...t,...r};for(const[a,o]of pg)n[a]===o&&(n[a]=t[a]);return n}catch{return t}}function hd(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function xg({enabled:e=!0,onTrigger:t}){const r=hg(),[n,a]=i.useState(()=>yn(r)),[o,c]=i.useState(null),[l,d]=i.useState([]),m=i.useRef({parts:[],timer:null}),u=i.useCallback(p=>{const x=[];return p.metaKey&&x.push(r?"⌘":"Meta"),p.ctrlKey&&x.push("Ctrl"),p.altKey&&x.push(r?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&x.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(x.push(hd(p.key)),x.join("+"))},[r]),h=i.useCallback(p=>{a(p);try{localStorage.setItem(fd,JSON.stringify(p))}catch{}},[]);i.useEffect(()=>{const p=yn(r),x=Object.entries(n),g=Object.entries(p);x.length===g.length&&x.every(([f,N])=>p[f]===N)||h(p)},[n,r,h]);const b=i.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),k=i.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},fg))},[]);i.useEffect(()=>{if(!o)return;const p=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){c(null),d([]);return}const g=u(x);if(!g)return;const N=!(x.metaKey||x.ctrlKey||x.altKey)&&/^[A-Z0-9]$/.test(g);if(l.length===0&&N){d([g]);return}const v=[...l,g].slice(0,2).join(" "),M={...n};for(const[A,w]of Object.entries(M))w===v&&delete M[A];M[o]=v,h(M),c(null),d([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,u,h,o,l]),i.useEffect(()=>{if(!e||o)return;const p=x=>{if(x.defaultPrevented)return;const g=u(x);if(!g)return;const f=x.metaKey||x.ctrlKey||x.altKey;if(Va(x.target))return;const N=m.current.parts,S=f?[g]:[...N.slice(-1),g].slice(-2),v=S.join(" "),M=S[S.length-1],A=Object.entries(n).filter(([,T])=>!!T),w=A.find(([,T])=>T===v);if(w){x.preventDefault(),b(),t(w[0]);return}if(A.some(([,T])=>T.startsWith(`${v} `))){x.preventDefault(),m.current.parts=S,k();return}const K=A.find(([,T])=>T===M);if(K){x.preventDefault(),b(),t(K[0]);return}if(A.some(([,T])=>T.startsWith(`${M} `))){x.preventDefault(),m.current.parts=[M],k();return}b()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,k,e,u,t,b,o]),i.useEffect(()=>()=>b(),[b]);const y=i.useMemo(()=>pd(r),[r]);return{isMac:r,actionDefinitions:y,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:d,saveShortcuts:h}}function bg({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 xd(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Vi({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!xd(n):!0}function gg({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:xd(r)}const bd=1e3,yg=4;function Gi(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function qi(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function vg({detachDelayMs:e=bd,stillnessThresholdPx:t=yg,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,c=null,l=null,d=null,m=null,u=!1;const h=()=>{m!=null&&(a(m),m=null)},b=()=>{h(),l=null},k=()=>{h(),o=null,c=null,l=null,d=null,u=!1},y=()=>{!o||!l||!d||u||m!=null||(m=n(()=>{m=null,!(!o||!l||!d||u)&&Gi(d,c)&&(qi(l,d,t)||(u=!0,r({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},p=g=>{if(!(!o||u)){if(!Gi(g,c)){d={clientX:g.clientX,clientY:g.clientY},b();return}(!l||qi(l,g,t))&&(h(),l={clientX:g.clientX,clientY:g.clientY}),d={clientX:g.clientX,clientY:g.clientY},y()}},x=g=>{!o||u||(g&&(d={clientX:g.clientX,clientY:g.clientY}),b())};return{startDrag:g=>{h(),o=g.panelId,c=g.selfPanelBounds??null,l=null,d={clientX:g.clientX,clientY:g.clientY},u=!1},markSelfPanel:p,markNonSelfPanel:x,markNoDropTarget:x,markDockTarget:x,endDrag:k,isDragging:()=>o!=null,hasDetached:()=>u,dispose:k}}function wg(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Fr(e){return e.isActive}function Yi(e){return e.isVisible}const gd=i.createContext(null);function _n(){const e=i.useContext(gd);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Zr(e){return lt(e)||e.tabKey}function jg(e){return`remote:${e}`}function Pt(e){return e.startsWith("remote:")}function Xi(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function kg(e){e.preventDefault()}function da(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 ua(e,t){e.classList.remove(Ca.className,Ia.className),e.classList.add(t==="light"?Ca.className:Ia.className)}function Ji(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 Sg(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 Ng(e,t,r){var c;const n=[t];let a;for(const l of n){let d;for(const m of l){const u=e.addPanel({id:m.tabKey,component:"conversation",title:Zr(m),params:{kind:"conversation",tabKey:m.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 Qi(e,t){const r=new Set(t.map(a=>a.tabKey)),n=new Map;for(const a of t)n.set(a.tabKey,(n.get(a.tabKey)||0)+1);for(const a of[...e.panels])Pt(a.id)||r.has(a.id)||e.removePanel(a);for(const a of t){const o=e.getPanel(a.tabKey);if(o){(n.get(a.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:a.tabKey,daemonId:a.daemonId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,panelId:o.id}),o.update({params:{tabKey:a.tabKey}}),o.title!==Zr(a)&&o.api.setTitle(Zr(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:Zr(a),params:{kind:"conversation",tabKey:a.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 Zi(e,t,r){var d,m;const n=r?jg(r):null;for(const u of[...e.panels])Pt(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=Et(t,r);if(!a&&e.totalPanels===0)return;const o=e.getPanel(n),c=gl(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)??((m=e.panels.find(u=>!Pt(u.id)))==null?void 0:m.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function Cg({params:e,api:t}){var k;const r=_n(),n=i.useRef(null),[a,o]=i.useState(()=>Fr(t)),[c,l]=i.useState(()=>Yi(t)),d=r.conversationsByTabKey.get(e.tabKey),m=In({sendDaemonCommand:r.sendDaemonCommand,activeConv:d,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});i.useEffect(()=>{o(Fr(t)),l(Yi(t));const y=[t.onDidActiveChange(p=>o(p.isActive)),t.onDidActiveGroupChange(p=>{if(!Fr(t)&&!p.isActive){o(!1);return}o(Fr(t))}),t.onDidVisibilityChange(p=>l(p.isVisible))];return()=>{for(const p of y)p.dispose()}},[t]);const u=i.useMemo(()=>d?r.ides.find(y=>y.id===d.routeId):void 0,[r.ides,d]),h=i.useMemo(()=>d?r.actionLogs.filter(y=>y.routeId===d.tabKey):[],[r.actionLogs,d]);if(!d)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(Do,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const b=!et(d)&&Hs(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(Po,{activeConv:d,clearToken:r.clearedTabs[d.tabKey]||0,isCliTerminal:b,ideEntry:u,terminalRef:n,handleModalButton:m.handleModalButton,handleRelaunch:m.handleRelaunch,handleSendChat:m.handleSendChat,isSendingChat:m.isSendingChat,handleFocusAgent:m.handleFocusAgent,isFocusingAgent:m.isFocusingAgent,actionLogs:h,userName:r.userName,scrollToBottomRequestNonce:((k=r.scrollToBottomRequest)==null?void 0:k.tabKey)===d.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:c})})}function Ig({params:e}){var d;const t=_n(),r=i.useMemo(()=>Et([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=i.useMemo(()=>t.ides.find(m=>m.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}=md({doId:a,targetSessionId:r?el(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(Bc,{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 Tg(){const e=_n();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(Do,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function Mg(e){var k,y;Sg(e);const t=_n(),r=i.useCallback(p=>{"button"in p&&p.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const p=Et([...t.conversationsByTabKey.values()],e.params.routeId),x=((k=e.api.group.activePanel)==null?void 0:k.id)===e.api.id,g=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${x?" is-active":""}${g?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(p==null?void 0:p.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:p!=null&&p.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:p.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const n=t.conversationsByTabKey.get(e.params.tabKey);if(!n)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const a=((y=e.api.group.activePanel)==null?void 0:y.id)===e.api.id,o=e.api.isGroupActive,c=Sn(n,t.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,d=c.isConnecting,m=c.isGenerating,u=c.isWaiting,h=c.unread,b=t.tabShortcuts[n.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${o?" is-group-active":""}${l?" is-reconnecting":""}`,title:lt(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:p=>{var x;p.preventDefault(),r(p),t.openTabContextMenu({x:p.clientX,y:p.clientY,tabKey:n.tabKey,sourceDocument:((x=p.target)==null?void 0:x.ownerDocument)??document})},children:[h&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:m?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:lt(n)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:cs(n)}):d?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:cs(n)}):s.jsx("span",{children:cs(n)})})]}),b&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:b,children:b})]})}function Ag({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:d,userName:m,toggleHiddenTab:u,actionShortcuts:h,registerActionHandlers:b,onActiveTabChange:k,onOpenNewSession:y,onRequestScrollToBottom:p,requestedActiveTabKey:x,requestedRemoteIdeId:g,onRequestedActiveTabConsumed:f,scrollToBottomRequest:N,liveSessionInboxState:S,layoutProfile:v}){var Qe,ze,rt;const{theme:M}=Io(),{sendCommand:A}=gt(),w=i.useRef(null),j=i.useRef(null),K=i.useRef(null),P=i.useRef(!1),T=i.useRef(!1),W=i.useRef(!1),H=i.useRef(null),R=i.useRef([]),[I,C]=i.useState(null),[O,_]=i.useState(0),E=i.useRef(typeof window>"u"?{}:qx(v)),U=i.useMemo(()=>new Map(e.map(F=>[F.tabKey,F])),[e]),Q=i.useMemo(()=>{const F=w.current;return F?F.groups.some(V=>{try{const J=V.model.location.type;return J!=="floating"&&J!=="popout"?!1:V.panels.some(re=>U.has(re.id))}catch{return!1}}):!1},[U,O,e]),xe=i.useCallback(()=>{var F;(F=w.current)==null||F.focus()},[]),de=i.useCallback((F,V)=>{p==null||p(F,V)},[p]),Z=i.useCallback(F=>{const V=document,J=F.document;for(const ne of V.querySelectorAll('link[rel="stylesheet"]')){const Se=J.createElement("link");Se.rel="stylesheet",Se.href=ne.href,ne.crossOrigin&&(Se.crossOrigin=ne.crossOrigin),J.head.appendChild(Se)}for(const ne of V.querySelectorAll("style")){const Se=J.createElement("style");Se.textContent=ne.textContent,J.head.appendChild(Se)}const re=[];for(const ne of V.styleSheets)try{for(const Se of ne.cssRules)Se instanceof CSSStyleRule&&(Se.selectorText===":root"||Se.selectorText==="html")&&re.push(Se.cssText)}catch{}if(re.length>0){const ne=J.createElement("style");ne.textContent=re.join(`
54
54
  `),J.head.appendChild(ne)}const $=V.documentElement.getAttribute("data-theme");$&&J.documentElement.setAttribute("data-theme",$),J.documentElement.style.colorScheme=$==="light"?"light":"dark",J.body.className=V.body.className;const Y=V.documentElement.getAttribute("style");Y&&J.documentElement.setAttribute("style",Y);const ee=J.getElementById("dv-popout-window");ee instanceof HTMLElement&&(ee.classList.add("adhdev-dockview"),ua(ee,M))},[M]),he=i.useCallback(()=>{var V;const F=w.current;if(F)for(const J of F.groups)try{const re=(V=J.element)==null?void 0:V.ownerDocument;if(!re||re===document)continue;const $=re.getElementById("dv-popout-window");$ instanceof HTMLElement&&($.classList.add("adhdev-dockview"),ua($,M));const Y=document.documentElement.getAttribute("data-theme");Y&&re.documentElement.setAttribute("data-theme",Y),re.documentElement.style.colorScheme=Y==="light"?"light":"dark",re.body.className=document.body.className;const ee=document.documentElement.getAttribute("style");ee?re.documentElement.setAttribute("style",ee):re.documentElement.removeAttribute("style")}catch{}},[M]),we=i.useCallback(F=>{const V=w.current;if(!V)return;const J=V.getPanel(F);J&&V.addPopoutGroup(J,{popoutUrl:"/popout.html",onDidOpen:({window:re})=>{Z(re),pe();const $=U.get(F);re.document.title=$?`${lt($)} — ADHDev`:"ADHDev — Popout"}})},[U,Z]),be=i.useCallback(F=>{const V=w.current,J=V==null?void 0:V.getPanel(F);if(!V||!J)return;const re=V.groups.filter($=>{var Y;try{return((Y=$.element)==null?void 0:Y.ownerDocument)===document}catch{return!0}});re.length>0?J.api.moveTo({group:re[0],position:"center"}):J.api.moveTo({position:"center"}),J.api.setActive()},[]),X=i.useCallback(F=>{var re;const V=w.current;if(!V)return!1;const J=V.getPanel(F);if(!J)return!1;try{return((re=J.group.element)==null?void 0:re.ownerDocument)!==document}catch{return!1}},[]),ue=i.useCallback(F=>{X(F)&&be(F),u(F)},[X,be,u]),ge=i.useCallback(F=>{const V=w.current,J=V==null?void 0:V.getPanel(F);!V||!J||V.addFloatingGroup(J,{width:600,height:500})},[]),te=i.useCallback(F=>{var J;const V=(J=w.current)==null?void 0:J.getPanel(F);if(!V)return!1;try{return V.group.model.location.type==="floating"}catch{return!1}},[]),le=i.useCallback(()=>{var V,J;const F=(J=(V=w.current)==null?void 0:V.activePanel)==null?void 0:J.id;return!F||Pt(F)?null:U.has(F)?F:null},[U]),Ne=i.useCallback(F=>{const V=w.current,J=V==null?void 0:V.getPanel(F);if(!V||!J)return;const re=V.groups.filter($=>{try{return $.model.location.type==="grid"}catch{return!0}});re.length>0?J.api.moveTo({group:re[0],position:"center"}):J.api.moveTo({position:"center"}),J.api.setActive()},[]),me=i.useCallback(()=>{var Y;const F=w.current;if(!F)return;const J=F.groups.filter(ee=>{var ne;try{return((ne=ee.element)==null?void 0:ne.ownerDocument)===document&&ee.model.location.type==="grid"}catch{return!1}})[0]||null,re=[...F.panels];for(const ee of re){const ne=(Y=ee.group.element)==null?void 0:Y.ownerDocument,Se=ee.group.model.location.type;ne===document&&Se==="grid"||(J&&J.id!==ee.group.id?ee.api.moveTo({group:J,position:"center"}):ee.api.moveTo({position:"center"}))}const $=F.activePanel;$&&($.group.model.openPanel($),$.api.setActive()),da(document)},[]),pe=i.useCallback(()=>{var V,J;const F=w.current;if(F)for(const re of F.groups){const $=(V=re.element)==null?void 0:V.ownerDocument;if(!$||$===document)continue;const Y=$.getElementById("dv-popout-window");if(!(Y instanceof HTMLElement))continue;let ee=null,ne=$.title||"ADHDev",Se="Popout workspace";const De=re.activePanel;if(De)if(ee=De.id,Pt(De.id)){const Re=((J=De.params)==null?void 0:J.routeId)||De.id.slice(7),Xe=Et([...U.values()],Re);ne=gl(Xe),Se=Xe!=null&&Xe.machineName?`Remote view · ${Xe.machineName}`:"Remote view"}else{const Re=U.get(De.id);ne=Re?lt(Re):De.title||De.id,Se=Re?cs(Re):"Dockview panel"}$.title=`${ne} — ADHDev`;const Ee=Array.from($.querySelectorAll("#adhdev-popout-header"));for(const Re of Ee)Re.remove();const Ce=$.createElement("div");Ce.id="adhdev-popout-header",$.body.appendChild(Ce),Ce.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(";")),Ce.innerHTML=`
55
55
  <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
56
56
  <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
@@ -88,11 +88,11 @@ This will disconnect CDP and optionally kill the process.`))try{const E=await r(
88
88
 
89
89
  `)}function Yy(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Xy(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Jy({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:c,searchQuery:l,daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:h}){const b=Iy(n,o),k=Ay(e,l),y=Py(t,l),p=_y(b,l),x=Dy(a,l),g=Yy(k,c),f=c==="all"?y:[],N=Xy(p,c),S=c==="issues"?[]:x,v=Ey({daemonLogs:k,daemonRawLines:y,trace:p,webEvents:x}),M=Uy({daemonLogs:g,daemonRawLines:f,trace:N,webEvents:S}),A=Vy(M),w=Ky({daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:h,daemonLogKind:r,daemonLogsCount:k.length,daemonRawLineCount:y.length,traceCount:p.length,webEventCount:x.length});return{filteredDaemonLogs:k,filteredDaemonRawLines:y,filteredTraceEntries:p,filteredWebEvents:x,visibleDaemonLogs:g,visibleDaemonRawLines:f,visibleTraceEntries:N,visibleWebEvents:S,quickFilterCounts:v,diagnosticEvents:M,diagnosticsSummary:A,sourceStates:w}}function Qy(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Td(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function qa(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 xa(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 Oo(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function Zy({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${qa(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:Td(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:Oo(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 e0({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:c,onCopyVisible:l,onToggleAutoRefresh:d,onRefresh:m,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(h=>s.jsx("button",{type:"button",onClick:()=>a(h.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===h.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:h.label},h.id))}),s.jsx("input",{value:r,onChange:h=>o(h.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:m,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:u,className:"machine-btn",children:"Clear"})]})]})}function t0({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:Ny.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 s0({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:c,traceFetchError:l}){var u,h;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((h=e.latestIssue)==null?void 0:h.severity)==="warn"?"warning":"good",m=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 ${xa(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 ${xa(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:[Oo(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:Td(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 ${xa(m)}`,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: ",Qy(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(b=>s.jsxs("div",{children:[b.label,": ",b.status]},b.id))})]})]})}function r0({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()," · ",Oo(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function n0({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:c,visibleWebEvents:l,quickFilter:d,searchQuery:m}){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(Zy,{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,h)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${h}`)),e.daemonLogKind!=="text"&&a.map((u,h)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${qa(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-${h}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>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:m.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 ${qa(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:Os(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:m.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:Os(u.payload,360)||"No payload"})]},u.id))]})]})]})}function a0({machineId:e,sendDaemonCommand:t}){const r=By({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}),m=i.useRef(null),u=i.useRef(!1),h=i.useMemo(()=>Jy({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&&h.diagnosticEvents.length>0){const y=u.current?"smooth":"instant";setTimeout(()=>{var p;(p=m.current)==null||p.scrollIntoView({behavior:y}),u.current=!0},50)}},[h.diagnosticEvents.length,r.autoRefresh]);const b=i.useCallback(async()=>{var p;const y=$y({daemonLogs:h.visibleDaemonLogs,daemonRawLines:h.visibleDaemonRawLines,trace:h.visibleTraceEntries,webEvents:h.visibleWebEvents});if(!y.trim()){nt.showToast("No visible logs to copy.","info");return}try{await((p=navigator.clipboard)==null?void 0:p.writeText(y)),nt.showToast("Copied visible logs to clipboard.","success")}catch(x){nt.showToast(x instanceof Error?x.message:"Could not copy visible logs","warning")}},[h.visibleDaemonLogs,h.visibleDaemonRawLines,h.visibleTraceEntries,h.visibleWebEvents]),k=i.useCallback(async()=>{var p;const y=qy({events:h.diagnosticEvents,summary:h.diagnosticsSummary,sources:h.sourceStates});try{await((p=navigator.clipboard)==null?void 0:p.writeText(y)),nt.showToast("Copied diagnostic bundle to clipboard.","success")}catch(x){nt.showToast(x instanceof Error?x.message:"Could not copy diagnostic bundle","warning")}},[h.diagnosticEvents,h.diagnosticsSummary,h.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(e0,{quickFilter:n,quickFilterCounts:h.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:c,onCopyDiagnostics:()=>{k()},onCopyVisible:()=>{b()},onToggleAutoRefresh:()=>r.setAutoRefresh(y=>!y),onRefresh:r.refresh,onClear:r.clear}),s.jsx(t0,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(s0,{diagnosticsSummary:h.diagnosticsSummary,diagnosticEventsCount:h.diagnosticEvents.length,sourceStates:h.sourceStates,searchQuery:o,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(r0,{patterns:h.diagnosticsSummary.repeatedPatterns}),s.jsx(n0,{streams:r,sectionsOpen:l,setSectionsOpen:d,diagnosticEvents:h.diagnosticEvents,visibleDaemonLogs:h.visibleDaemonLogs,visibleDaemonRawLines:h.visibleDaemonRawLines,visibleTraceEntries:h.visibleTraceEntries,visibleWebEvents:h.visibleWebEvents,quickFilter:n,searchQuery:o}),s.jsx("div",{ref:m})]})}function o0(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 Md(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 i0(e){var a;const t=[],r=[],n=[];for(const o of e||[]){const c=String((o==null?void 0:o.lifecycle)||"").trim(),l=Md((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 c0(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function ba(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 ga(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function ya(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function dc(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 l0(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function d0(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 u0(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 m0({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=i.useState(""),[o,c]=i.useState(null),[l,d]=i.useState(!1),m=bx(e,{enabled:!!e,includeSessions:!0,limit:bi,intervalMs:fp}),u=m.diagnostics,h=m.loading,b=m.applyDiagnostics,k=i.useMemo(()=>o0({diagnostics:u,loading:h,refreshing:l,error:n}),[u,h,l,n]),y=i.useMemo(()=>new Map(t.map(P=>[P.sessionId||P.id,P])),[t]),p=i.useCallback(async()=>{if(e){d(!0);try{const P=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:bi}),T=ga(P);if(!(T!=null&&T.success))throw new Error((T==null?void 0:T.error)||"Could not load hosted runtime diagnostics");b(T.diagnostics||T.result||null),a("")}catch(P){const T=P instanceof Error?P.message:"Could not load hosted runtime diagnostics";a(T)}finally{d(!1)}}},[b,e,r]);i.useEffect(()=>{!e||u||h||l||p()},[u,h,e,p,l]);const x=i.useCallback(async(P,T)=>{const W=`${P}:${T.sessionId}`;if(!(P==="session_host_stop_session"&&!window.confirm(`Stop ${T.displayName}?
90
90
  This will terminate the hosted runtime.`))){c(W);try{const H=await r(e,P,{sessionId:T.sessionId}),R=ga(H);if(!(R!=null&&R.success))throw new Error((R==null?void 0:R.error)||"Session host action failed");const I=P==="session_host_resume_session"?"resumed":P==="session_host_restart_session"?"restarted":"stopped";nt.showToast(`Session host ${I}: ${T.displayName}`,"success"),await p()}catch(H){const R=H instanceof Error?H.message:"Session host action failed";nt.showToast(R,"warning"),a(R)}finally{c(H=>H===W?null:H)}}},[e,p,r]),g=i.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
91
- 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 T=await r(e,"session_host_prune_duplicate_sessions",{}),W=ga(T);if(!(W!=null&&W.success))throw new Error((W==null?void 0:W.error)||"Duplicate prune failed");const H=W.result||{},R=Array.isArray(H.prunedSessionIds)?H.prunedSessionIds.length:0,I=typeof H.duplicateGroupCount=="number"?H.duplicateGroupCount:0;nt.showToast(`Pruned ${R} duplicate runtime(s) across ${I} group(s)`,"success"),await p()}catch(T){const W=T instanceof Error?T.message:"Duplicate prune failed";nt.showToast(W,"warning"),a(W)}finally{c(T=>T==="session_host_prune_duplicate_sessions"?null:T)}}},[e,p,r]),f=i.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((P,T)=>(T.lastActivityAt||0)-(P.lastActivityAt||0)),[u==null?void 0:u.sessions]),N=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)||[]}:i0(f),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,f]),S=N.liveRuntimes,v=N.recoverySnapshots,M=N.inactiveRecords,A=i.useMemo(()=>u0(S),[S]),w=i.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),j=i.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(P=>P.level==="warn"||P.level==="error")||null,[u==null?void 0:u.recentLogs]),K=(P,T)=>{var U;const W=o===`session_host_resume_session:${P.sessionId}`,H=o===`session_host_restart_session:${P.sessionId}`,R=o===`session_host_stop_session:${P.sessionId}`,I=Md(P.meta),C=y.get(P.sessionId),O=P.attachedClients.length===1?"1 client":`${P.attachedClients.length} clients`,_=T==="recovery"?"Recover":"Resume",E=c0(T);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:P.displayName||(C==null?void 0:C.cliName)||P.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${d0(P.lifecycle)}`,children:P.lifecycle}),I&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:I})]}),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:P.workspaceLabel||(C==null?void 0:C.runtimeWorkspaceLabel)||P.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:P.runtimeKey}),P.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",P.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((U=P.writeOwner)==null?void 0:U.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:l0(P.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(Nc,{size:11})," ",O]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",dc(P.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",E]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[T==="recovery"&&(P.lifecycle==="interrupted"||P.lifecycle==="failed"||P.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_resume_session",P)},children:W?`${_}ing…`:_}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_restart_session",P)},children:H?"Restarting…":"Restart"}),T==="live"&&(P.lifecycle==="running"||P.lifecycle==="starting"||P.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:()=>{x("session_host_stop_session",P)},children:R?"Stopping…":"Stop"})]})]})},P.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(Jt,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:gh()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[A>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{g()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${A})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${k.toneClass}`,children:k.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:h||l,children:[s.jsx(yr,{size:13}),h||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(xr,{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:v.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:dc(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:ya(u.hostStartedAt)})]})]}),j&&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(xr,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:j.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[ya(j.timestamp),j.sessionId?` · ${j.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(ro,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ba("live")}),S.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:S.map(P=>K(P,"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(Jt,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ba("recovery")}),v.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:v.map(P=>K(P,"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:ba("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:M.map(P=>K(P,"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"}),w.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:w.map(P=>{var W;const T=f.find(H=>H.sessionId===P.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:(T==null?void 0:T.displayName)||((W=y.get(P.sessionId))==null?void 0:W.cliName)||P.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[P.action,P.lifecycle?` · ${P.lifecycle}`:"",P.detail?` · ${P.detail}`:"",P.error?` · ${P.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${P.success===!1?"text-red-300":"text-text-secondary"}`,children:ya(P.timestamp)})]},`${P.sessionId}:${P.timestamp}:${P.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 f0({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 va({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 wa({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 p0({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),m="0.9.79",u=Jl(e),h=Cs(e,m),b=ur(e,h),k=u==="preview"?"Update to preview":"Update daemon";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(va,{icon:s.jsx(zt,{size:13}),children:"Current Chats"}),s.jsx(wa,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(y=>{const p=Ua(y);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(y),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:lt(y)}),p>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:kn(p)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:gs(y)})]},y.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(va,{icon:s.jsx(Mc,{size:13}),children:"Recent Launches"}),s.jsx(wa,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(y=>{const{metaText:p,updatedLabel:x}=cd(y);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(y),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:y.label}),x&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:x})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:p})]},y.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(va,{icon:s.jsx(xr,{size:13}),children:"Daemon Update"}),s.jsx(wa,{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:b?"Daemon update required":"Version mismatch detected"}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[b?"This machine is on an incompatible daemon version. Update it before starting more sessions.":u==="preview"?"This machine can be upgraded to the current preview daemon without opening a remote shell.":"This machine is running a different daemon version than the current app. Update it before starting more sessions.",h&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",h,u?` (${u})`:""]})]}),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(yr,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:k})]})]})})]})]})}function h0(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function x0({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 m=d.target.value;if(o(m),m==="__custom__"&&a){l();return}m!=="__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?"⭐ ":"",Nn(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 b0={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 Ur(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ja({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:o,actions:c,sendDaemonCommand:l,initialWorkspaceId:d,initialWorkspacePath:m,onOpenGitDialog:u}){const h=Ws(),{handleLaunchIde:b,handleStopCli:k,handleRestartIde:y,handleStopIde:p,handleDetectIdes:x,launchingIde:g,launchingAgentType:f,addLog:N}=c,[S,v]=i.useState(null),M=i.useCallback(L=>{L&&h(Zt(L))},[h]),A=b0[e],w=e==="ide",j=e==="acp",K=i.useMemo(()=>n.filter(L=>ys(L,e)),[e,n]),P=i.useMemo(()=>new Map(K.map(L=>[L.type,L.displayName||L.type])),[K]),[T,W]=i.useState(""),[H,R]=i.useState(""),[I,C]=i.useState([]),[O,_]=i.useState(""),[E,U]=i.useState(""),[Q,xe]=i.useState([]),[de,Z]=i.useState(!1),[he,we]=i.useState(!1),[be,X]=i.useState(""),[ue,ge]=i.useState(!1),[te,le]=i.useState(()=>jt()),[Ne,me]=i.useState(null),[pe,oe]=i.useState(m?"__custom__":d||t.defaultWorkspaceId||""),[fe,ie]=i.useState(m||""),[D,z]=i.useState([]),[ce,se]=i.useState(!1),[q,ke]=i.useState(""),[ve,Le]=i.useState([]),[Ae,B]=i.useState(!1),[Ie,Pe]=i.useState(""),Fe=i.useRef(null),[He,qe]=i.useState(null),Ye=i.useRef("__home__"),[tt,mt]=i.useState("__home__"),[ht,bt]=i.useState(!1),Te=i.useRef(0),Ue=D.filter(L=>!a.some(ae=>ae.type===L&&xt(ae.status)!=="stopped")),Qe=i.useRef({});i.useEffect(()=>{t.defaultWorkspaceId&&!pe&&oe(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),i.useEffect(()=>{if(m){oe("__custom__"),ie(m);return}d&&(oe(d),ie(""))},[d,m]),i.useEffect(()=>{w||T&&(K.some(L=>L.type===T)||(W(""),U("")))},[K,w,T]);const ze=(()=>{if(pe==="__custom__")return fe.trim();if(!pe)return"";const L=(t.workspaces||[]).find(ae=>ae.id===pe);return(L==null?void 0:L.path)||""})(),rt=i.useCallback(L=>{const ae=Qe.current[L];ae&&(clearTimeout(ae),delete Qe.current[L]),z(ye=>ye.includes(L)?ye.filter(Ke=>Ke!==L):ye)},[]),F=i.useRef(new Set),V=i.useCallback(async L=>{if(l){B(!0),Pe("");try{const ae=await Rn(l,r,L);ke(ae.path),ie(ae.path),Le(ae.directories)}catch(ae){Pe(ae instanceof Error?ae.message:"Could not load folder")}finally{B(!1)}}},[r,l]),J=i.useCallback(()=>{if(!l)return;oe("__custom__"),se(!0);const L=a.map(ye=>ye.workspace),ae=Ln(t.platform,An(fe.trim(),ze,m,L,t.defaultWorkspacePath,(t.workspaces||[]).map(ye=>ye.path)));V(ae)},[fe,m,V,t.defaultWorkspacePath,t.platform,t.workspaces,a,ze,l]),re=i.useCallback(L=>{const ae=String(L.workspace||"").trim();if(!ae)return;const ye=(t.workspaces||[]).find(Ke=>Ur(Ke.path)===Ur(ae));if(ye){oe(ye.id),ie("");return}oe("__custom__"),ie(ae)},[t.workspaces]),$=i.useCallback(L=>{const ae=String(L.workspace||"").trim();if(!ae)return{workspaceId:null,workspacePath:"",useHome:!0};const ye=(t.workspaces||[]).find(Ke=>Ur(Ke.path)===Ur(ae));return ye?{workspaceId:ye.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:ae,useHome:!1}},[t.workspaces]),Y=i.useCallback(async L=>{if(!l||!L||e!=="cli"){xe([]),Z(!1),we(!1),X("");return}const ae=Te.current+1;Te.current=ae,Z(!0),X("");try{const ye=await l(r,"list_saved_sessions",{providerType:L,kind:"cli",limit:30});if(Te.current!==ae)return;const Ke=(ye==null?void 0:ye.result)??ye;xe(Array.isArray(Ke==null?void 0:Ke.sessions)?Ke.sessions:[])}catch(ye){if(Te.current!==ae)return;xe([]),X(ye instanceof Error?ye.message:"Could not load saved sessions")}finally{Te.current===ae&&(Z(!1),we(!0))}},[e,r,l]),ee=i.useMemo(()=>{if(e!=="cli"||!T)return null;const L=P.get(T)||T;return{routeId:r,daemonId:r,providerSessionId:E||void 0,transport:"pty",mode:"chat",agentName:L,agentType:T,status:"idle",title:L,messages:[],ideType:T,workspaceName:ze,workspacePath:ze,displayPrimary:L,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${T}`}},[e,r,P,ze,E,T]),ne=i.useCallback(L=>{if(e==="ide"||!L){C([]);return}C(Ga(r,L))},[e,r]),Se=i.useCallback((L,ae)=>{e==="ide"||!L||(Rg(r,L,ae),C(Ga(r,L)))},[e,r]);i.useEffect(()=>{Te.current+=1,U(""),ne(T),we(!1),xe([]),X(""),Z(!1)},[e,ne,Y,T]);const De=i.useMemo(()=>Q.find(L=>L.providerSessionId===E)||null,[Q,E]);i.useEffect(()=>{if(!E)return;const L=Q.find(ae=>ae.providerSessionId===E);L!=null&&L.canResume||U("")},[Q,E]);const Ee=i.useCallback((L,ae)=>{Fe.current=ae,Ye.current=L.selectedWorkspaceKey||"__home__",mt(L.selectedWorkspaceKey||"__home__"),qe(L)},[]),Ce=i.useCallback(()=>{Fe.current&&(bt(!0),Fe.current().finally(()=>{Fe.current=null,bt(!1),qe(null)}))},[]),$e=i.useCallback(L=>{if(!L)return;z(ye=>ye.includes(L)?ye:[...ye,L]);const ae=Qe.current[L];ae&&clearTimeout(ae),Qe.current[L]=setTimeout(()=>{z(ye=>ye.includes(L)?ye.filter(Ke=>Ke!==L):ye),delete Qe.current[L]},2e4)},[]);i.useEffect(()=>{for(const ae of a)xt(ae.status)!=="stopped"&&(D.includes(ae.type)&&!F.current.has(ae.type)&&(F.current.add(ae.type),N("info",`${P.get(ae.type)||ae.type} launched`,!0)),rt(ae.type));const L=new Set(a.filter(ae=>xt(ae.status)!=="stopped").map(ae=>ae.type));F.current.forEach(ae=>{!D.includes(ae)&&!L.has(ae)&&F.current.delete(ae)})},[N,rt,a,D,P]),i.useEffect(()=>()=>{Object.values(Qe.current).forEach(clearTimeout),Qe.current={}},[]);const[Be,Re]=i.useState({}),[Xe,Ze]=i.useState(null);i.useEffect(()=>{if(!w||!r||!l)return;(async()=>{try{const ae=await l(r,"get_ide_extensions",{}),ye=(ae==null?void 0:ae.result)||ae;ye!=null&&ye.success&&(ye!=null&&ye.ideExtensions)&&Re(ye.ideExtensions)}catch{}})()},[w,r,l]);const ct=L=>w?it(L.type):e==="cli"?L.cliName:L.acpName,ft=w?t.detectedIdes||[]:[],dt=i.useCallback(async L=>{const ae=(L==null?void 0:L.type)||T,ye=(L==null?void 0:L.workspacePath)??ze;if(w){await b(ae,ye?{workspace:ye}:void 0)&&$e(ae);return}const Ke=await c.runLaunchCliCore({cliType:ae,dir:L!=null&&L.workspaceId?void 0:ye||void 0,workspaceId:(L==null?void 0:L.workspaceId)||void 0,useHome:(L==null?void 0:L.useHome)||!(L!=null&&L.workspaceId)&&!ye,argsStr:(L==null?void 0:L.argsStr)??(H||void 0),model:(L==null?void 0:L.model)??(j&&O||void 0),resumeSessionId:(L==null?void 0:L.resumeSessionId)||!j&&e==="cli"&&ae===T&&E||void 0});if(Ke.success||Ke.pending){const _e=(L==null?void 0:L.argsStr)??H;!w&&(_e!=null&&_e.trim())&&(jd(r,ae,_e),ne(ae)),$e(ae),Ke.success&&Ke.sessionId&&M(Ke.sessionId)}},[c,b,j,w,H,O,ne,$e,r,M,ze,E,T]),wt=wl(w?"ide":j?"acp":"cli",!w&&!j&&!!E),Ve=jl(w?"ide":j?"acp":"cli",!w&&!j&&!!E),je=()=>{var _e;const L=w?it(T):P.get(T)||T,ae=!w&&!j&&!!E,{options:ye,selectedKey:Ke}=ps({machine:t,currentWorkspaceId:pe&&pe!=="__custom__"?pe:null,currentWorkspacePath:ze});Ee({title:ae?ko(L):ls("start-fresh",L),description:ae?So():ds("start-fresh"),confirmLabel:wt,busyLabel:Ve,workspaceOptions:ye,selectedWorkspaceKey:Ke,details:[{label:"Mode",value:A.label},{label:"Provider",value:L},...!w&&e==="cli"&&E?[{label:"Resume",value:((_e=Q.find(Oe=>Oe.providerSessionId===E))==null?void 0:_e.title)||E}]:[],...!w&&H.trim()?[{label:"Arguments",value:H.trim()}]:[],...j&&O.trim()?[{label:"Model",value:O.trim()}]:[]]},async()=>{const Oe=ye.find(ot=>ot.key===Ye.current);Oe!=null&&Oe.workspaceId?(oe(Oe.workspaceId),ie("")):Oe!=null&&Oe.workspacePath?(oe("__custom__"),ie(Oe.workspacePath)):(oe(""),ie("")),await dt({workspaceId:(Oe==null?void 0:Oe.workspaceId)??null,workspacePath:(Oe==null?void 0:Oe.workspacePath)??"",useHome:!(Oe!=null&&Oe.workspaceId)&&!(Oe!=null&&Oe.workspacePath)})})},G=L=>{w?p(L):k(L.type,L.workspace,L.id)},Me=i.useCallback(async(L,ae,ye=!1)=>{if(L.mode===ae){ye&&L.sessionId&&M(L.sessionId);return}if(!l||!L.sessionId){ye&&L.sessionId&&M(L.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:L.sessionId,cliType:L.type,mode:ae}),ye&&M(L.sessionId)}catch(Ke){const _e=Fl(Ke);Wl(Ke)?console.warn(_e?"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 ${A.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 ",A.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:w?ft.length>0?ft.map(L=>{const ae=a.find(ot=>(ot.type||"").toLowerCase()===(L.type||"").toLowerCase()&&xt(ot.status)!=="stopped"),ye=L.running||!!ae,Ke=!!ae&&ae.cdpConnected,_e=D.includes(L.type||L.id||""),Oe=T===(L.type||"");return s.jsxs("button",{onClick:()=>{if(Ke&&ae){const ot=ae.sessionId;ot?h(Zt(ot),{state:{openRemoteForTabKey:ot}}):h("/dashboard",{state:{openRemoteForTabKey:ae.id}});return}_e||W(ot=>ot===(L.type||"")?"":L.type||"")},disabled:!!g||_e,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":Oe?"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:g&&g!==L.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(L.type)}),ye&&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:L.name||it(L.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Ke?"text-green-400":_e?"text-orange-400":Oe?"text-accent-primary":"text-text-muted"}`,children:Ke?"Open Session":_e?"Starting...":Oe?"Configure":"Select"})]})]},L.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:x,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(Wu,{size:14})," Scan System"]})]}):K.length>0?K.map(L=>{const ae=T===L.type,ye=D.includes(L.type),_e=!!a.find(Oe=>Oe.type===L.type&&xt(Oe.status)!=="stopped");return s.jsxs("button",{onClick:()=>W(Oe=>Oe===L.type?"":L.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${ae?"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:L.icon}),_e&&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:L.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ye?"text-orange-400":ae?"text-accent-primary":"text-text-muted"}`,children:ye?"Starting...":ae?"Configure":"Select"})]})]},L.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."})]})}),T&&(w?ft.find(L=>L.type===T):K.find(L=>L.type===T))&&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:w?it(T):P.get(T)||T})]}),s.jsx(x0,{machine:t,selectedWorkspace:pe,resolvedWorkspacePath:ze,customPath:fe,canBrowse:!!l,onWorkspaceChange:oe,onCustomPathChange:ie,onOpenBrowseDialog:J}),!w&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!j&&e==="cli"&&s.jsx(Sd,{busy:!!f||!!g||D.includes(T),savedSessionsLoading:de,savedSessionsError:be,savedSessionsLoaded:he,savedSessionsCount:Q.length,selectedSession:De,onRefresh:()=>void Y(T),onOpenHistory:()=>{T&&(ge(!0),kd({hasLoadedInitialResults:he,isLoading:de})&&Y(T))},onClearSelection:()=>U("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[j&&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:O,onChange:L=>_(L.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:L=>R(L.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"}),I.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:I.map(L=>s.jsxs("div",{className:"inline-flex max-w-full items-stretch overflow-hidden rounded-md border border-[#ffffff1a] bg-bg-tertiary text-xs text-text-secondary transition-colors hover:border-accent-primary/40 hover:text-text-primary",title:L,children:[s.jsx("button",{type:"button",className:"min-w-0 max-w-[220px] truncate px-2.5 py-1.5 text-left",onClick:()=>R(L),children:L}),s.jsx("button",{type:"button",className:"flex items-center justify-center border-l border-[#ffffff1a] px-1.5 text-text-muted transition-colors hover:bg-status-error/10 hover:text-status-error focus:outline-none focus:ring-1 focus:ring-status-error/50",onClick:()=>Se(T,L),"aria-label":`Remove startup arguments: ${L}`,title:"Remove startup arguments",children:s.jsx(vt,{size:12})})]},L))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:je,disabled:!!f||!!g||D.includes(T),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:f===T||g===T?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+D.filter(L=>!a.some(ae=>ae.type===L&&xt(ae.status)!=="stopped")).length,")"]}),a.length===0&&Ue.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 ",A.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Ue.map(L=>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(L)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:w?it(L):P.get(L)||L}),s.jsx("div",{className:"text-[11px] text-text-muted",children:f===L?"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:${L}`)),a.map(L=>{const ae=w?L:null,ye=!w&&!j?L:null,Ke=xt(L.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(L.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[ct(L),(ae==null?void 0:ae.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",ae.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:L.workspace||"—"}),u&&L.git&&L.workspace?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:_e=>{_e.stopPropagation(),u(L.daemonId??r,L.workspace)},children:s.jsx($s,{git:L.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx($s,{git:L.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(ye==null?void 0:ye.mode)&&s.jsx("span",{className:ye.mode==="chat"?"text-violet-400":"text-text-secondary",children:ye.mode==="chat"?"Chat view":"Terminal view"})]}),ye&&(ye.runtimeKey||ye.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ye.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 ",ye.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 _e;(_e=navigator.clipboard)==null||_e.writeText(`adhdev attach ${ye.runtimeKey}`),v(ye.runtimeKey||null),window.setTimeout(()=>{v(Oe=>Oe===ye.runtimeKey?null:Oe)},1200)},children:S===ye.runtimeKey?"Copied":"Copy"})]}),ye.runtimeWriteOwner&&s.jsx("span",{style:{color:ye.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ye.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:h0(ye.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}),w&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const _e=L.sessionId;if(_e){h(Zt(_e),{state:{openRemoteForTabKey:_e}});return}h("/dashboard",{state:{openRemoteForTabKey:L.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 _e=L.workspace||"",{options:Oe,selectedKey:ot}=ps({machine:t,currentWorkspacePath:_e});Ee({title:ls("restart-ide",it(L.type)),description:ds("restart-ide"),confirmLabel:Bs("restart-ide"),busyLabel:Ks("restart-ide"),workspaceOptions:Oe,selectedWorkspaceKey:ot,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:it(L.type)}]},async()=>{const Nt=Oe.find(Gt=>Gt.key===Ye.current),pt=(Nt==null?void 0:Nt.workspacePath)??"";if(pt&&pt!==_e){await dt({type:L.type,workspacePath:pt});return}await y(L)})},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(yr,{size:14})})]}),j&&s.jsx("button",{onClick:()=>{const _e=L.sessionId;_e&&M(_e)},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:!L.sessionId,children:s.jsx(zt,{size:14})}),ye&&Ke!=="stopped"&&s.jsxs(s.Fragment,{children:[ye.mode&&s.jsx(vo,{mode:ye.mode,onChange:_e=>void Me(ye,_e,!1),compact:!0}),s.jsx("button",{onClick:()=>{const _e=L.sessionId;_e&&M(_e)},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:!L.sessionId,children:ye.mode==="chat"?s.jsx(zt,{size:14}):s.jsx(Tt,{size:13})})]}),Ke==="stopped"?s.jsx("button",{onClick:()=>{const _e=L.workspace||"",Oe=w?it(L.type):ct(L),{options:ot,selectedKey:Nt}=ps({machine:t,currentWorkspacePath:_e});Ee({title:ls("restart-stopped",Oe),description:ds("restart-stopped"),confirmLabel:Bs("restart-stopped"),busyLabel:Ks("restart-stopped"),workspaceOptions:ot,selectedWorkspaceKey:Nt,details:[{label:"Mode",value:A.label},{label:"Provider",value:Oe}]},async()=>{const pt=ot.find(Gt=>Gt.key===Ye.current);await dt({type:L.type,workspaceId:(pt==null?void 0:pt.workspaceId)??null,workspacePath:(pt==null?void 0:pt.workspacePath)??"",useHome:!(pt!=null&&pt.workspaceId)&&!(pt!=null&&pt.workspacePath)})})},disabled:D.includes(L.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:D.includes(L.type)?"⏳":s.jsx(no,{size:14})}):s.jsx("button",{onClick:()=>G(L),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(vt,{size:14})})]})]}),ae&&ae.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:ae.aiAgents.map(_e=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${ln(_e.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[_e.name," · ",xt(_e.status)]},_e.id))}),ae&&(Be[ae.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:(Be[ae.type]||[]).map(_e=>s.jsxs("button",{disabled:Xe===`${ae.type}.${_e.type}`,onClick:async()=>{const Oe=`${ae.type}.${_e.type}`;Ze(Oe);try{await l(r,"set_ide_extension",{ideType:ae.type,extensionType:_e.type,enabled:!_e.enabled}),Re(ot=>({...ot,[ae.type]:(ot[ae.type]||[]).map(Nt=>Nt.type===_e.type?{...Nt,enabled:!Nt.enabled}:Nt)}))}catch(ot){console.error("Extension toggle failed:",ot)}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 ${_e.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 ${_e.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),_e.name,s.jsx("span",{className:"text-[9px] font-normal",children:_e.enabled?"ON":"OFF"})]},_e.type))})]})]},L.id)})]}),ce&&l&&s.jsx(Pn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:q,directories:ve,busy:Ae,error:Ie,confirmLabel:"Use this folder",onClose:()=>se(!1),onNavigate:L=>{V(L)},onConfirm:L=>{ie(L),oe("__custom__"),se(!1)}}),He&&s.jsx(_o,{title:He.title,description:He.description,details:He.details,workspaceOptions:He.workspaceOptions,selectedWorkspaceKey:tt,onWorkspaceChange:L=>{Ye.current=L,mt(L)},confirmLabel:He.confirmLabel,busyLabel:He.busyLabel,busy:ht,onConfirm:Ce,onCancel:()=>{Fe.current=null,qe(null)}}),ue&&ee&&s.jsx(No,{activeConv:ee,ides:[],isCreatingChat:!1,isRefreshingHistory:de,savedSessions:Q,isSavedSessionsLoading:de,isResumingSavedSessionId:Ne,savedHistoryFilters:te,missingWorkspaceResumePath:ze||null,onSavedHistoryFiltersChange:le,onClose:()=>ge(!1),onNewChat:()=>{U(""),ge(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Y(T)},onResumeSavedSession:L=>{if(!L.canResume||Ne)return;const ae=$(L);U(L.providerSessionId),re(L),me(L.providerSessionId),ge(!1),dt({type:L.providerType,workspaceId:ae.workspaceId,workspacePath:ae.workspacePath,useHome:ae.useHome,resumeSessionId:L.providerSessionId}).finally(()=>{me(ye=>ye===L.providerSessionId?null:ye)})}})]})}const uc=[{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 g0({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:o,actions:c,getIcon:l,initialCategory:d="ide",initialWorkspaceId:m,initialWorkspacePath:u,sendDaemonCommand:h,onOpenGitDialog:b}){var x;const[k,y]=i.useState(d);i.useEffect(()=>{y(d)},[d]);const p=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:uc.map(g=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${k===g.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>y(g.id),children:[s.jsx("span",{children:g.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${k===g.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:p[g.id]})]},g.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(x=uc.find(g=>g.id===k))==null?void 0:x.helper})]}),k==="ide"&&s.jsx(ja,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:b}),k==="cli"&&s.jsx(ja,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:b}),k==="acp"&&s.jsx(ja,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:o,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:b})]})}function y0({onNicknameSynced:e}={}){var ie,D,z,ce,se,q,ke,ve,Le,Ae;const{id:t}=uu(),r=Ws(),n=Qa(),{sendCommand:a}=gt(),o=jr(),c=El(),l=fl(),d=l.ides||[],m=l.initialLoaded??!0,u=d.find(B=>B.id===t&&B.type==="adhdev-daemon"),h=d.some(B=>B.type==="adhdev-daemon"),b=t?(ie=l.connectionRetryStatuses)==null?void 0:ie[t]:void 0,k=!!(b!=null&&b.blocked),[y,p]=i.useState("workspace"),[x,g]=i.useState(null),f=i.useCallback((B,Ie)=>{g({daemonId:B,workspace:Ie})},[]),[N,S]=i.useState("ide"),v=i.useRef(null),[M,A]=i.useState(null),w=i.useRef("__home__"),[j,K]=i.useState("__home__"),[P,T]=i.useState(!1),W=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||y!=="overview")return;const B=u.machine;(typeof(B==null?void 0:B.cpus)!="number"||typeof(B==null?void 0:B.totalMem)!="number"||typeof(B==null?void 0:B.arch)!="string"||typeof(B==null?void 0:B.release)!="string")&&c(t,{minFreshMs:3e4}).catch(()=>{})},[y,c,u,t]),xx(t&&y==="overview"?[t]:[],{enabled:y==="overview",intervalMs:lp});const H=()=>{if(h){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},R=py({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:W});i.useEffect(()=>nt.onToast(Ie=>{l.setToasts(Fe=>{if(Fe.some(Ye=>Ye.message===Ie.message&&Ie.timestamp-Ye.timestamp<3e3))return Fe;const qe={id:Ie.id,message:Ie.message,type:Ie.type,timestamp:Ie.timestamp,targetKey:Ie.targetKey,actions:Ie.actions};return[...Fe.slice(-4),qe]});const Pe=Ie.duration||5e3;setTimeout(()=>l.setToasts(Fe=>Fe.filter(He=>He.id!==Ie.id)),Pe)}),[l]);const I=(u==null?void 0:u.availableProviders)||[],C={};for(const B of I)C[B.type]=B.icon;const O=B=>C[B]||"",_=u?{id:u.id,hostname:Wc(u,{fallbackId:u.id}),platform:((D=u.machine)==null?void 0:D.platform)||"unknown",arch:((z=u.machine)==null?void 0:z.arch)||"",cpus:((ce=u.machine)==null?void 0:ce.cpus)||0,totalMem:((se=u.machine)==null?void 0:se.totalMem)||0,freeMem:(q=u.machine)==null?void 0:q.freeMem,availableMem:(ke=u.machine)==null?void 0:ke.availableMem,loadavg:(ve=u.machine)==null?void 0:ve.loadavg,uptime:(Le=u.machine)==null?void 0:Le.uptime,release:((Ae=u.machine)==null?void 0:Ae.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,E=d.filter(B=>B.daemonId===t&&B.type!=="adhdev-daemon").filter(B=>!br(B)&&!Ms(B)).map(B=>({id:B.id,sessionId:B.sessionId,type:B.type,version:B.version||"",instanceId:B.instanceId||"",status:B.status,workspace:B.workspace||null,terminals:B.terminals||0,aiAgents:ef(B.aiAgents||(B.agents||[]).map(Ie=>({id:Ie.name,name:Ie.name,status:Ie.status,version:Ie.version}))),activeChat:B.activeChat||null,chats:B.chats||[],childSessions:B.childSessions||[],cdpConnected:B.cdpConnected||!1,daemonId:t,lastMessageAt:B.lastMessageAt})),U=d.filter(B=>B.daemonId===t&&br(B)).map(B=>({id:B.id,sessionId:B.sessionId,type:B.type,cliName:B.cliName||B.type,status:B.status,workspace:B.workspace||"",activeChat:B.activeChat||null,providerSessionId:B.providerSessionId,mode:B.mode,runtimeKey:B.runtimeKey,runtimeDisplayName:B.runtimeDisplayName,runtimeWorkspaceLabel:B.runtimeWorkspaceLabel,runtimeWriteOwner:B.runtimeWriteOwner||null,runtimeAttachedClients:B.runtimeAttachedClients||[],daemonId:t,lastMessageAt:B.lastMessageAt})),Q=d.filter(B=>B.daemonId===t&&Ms(B)).map(B=>({id:B.id,sessionId:B.sessionId,type:B.type,acpName:B.cliName||B.type,status:B.status,workspace:B.workspace||"",activeChat:B.activeChat||null,providerSessionId:B.providerSessionId,daemonId:t,lastMessageAt:B.lastMessageAt})),xe=u?It(u,{fallbackId:t}):"",de="workspace",Z=n.state,he=Z==null?void 0:Z.initialMachineTab,we=Z==null?void 0:Z.initialWorkspaceCategory,be=Z==null?void 0:Z.initialWorkspaceId,X=Z==null?void 0:Z.initialWorkspacePath,ue=he==="ides"||he==="clis"||he==="acps"?"workspace":he||de,ge=he==="ides"?"ide":he==="clis"?"cli":he==="acps"?"acp":we,te=[...E.map(B=>{var Ie;return{id:`ide:${B.type}:${B.workspace||""}`,label:((Ie=B.activeChat)==null?void 0:Ie.title)||B.type,kind:"ide",providerType:B.type,subtitle:B.workspace||void 0,workspace:B.workspace||void 0,lastLaunchedAt:B.lastMessageAt||0}}),...U.map(B=>{var Ie;return{id:`cli:${B.type}:${B.workspace||""}`,label:((Ie=B.activeChat)==null?void 0:Ie.title)||B.cliName,kind:"cli",providerType:B.type,providerSessionId:B.providerSessionId,subtitle:B.workspace||void 0,workspace:B.workspace||void 0,lastLaunchedAt:B.lastMessageAt||0}}),...Q.map(B=>{var Ie;return{id:`acp:${B.type}:${B.workspace||""}`,label:((Ie=B.activeChat)==null?void 0:Ie.title)||B.acpName,kind:"acp",providerType:B.type,providerSessionId:B.providerSessionId,subtitle:bs(B.summaryMetadata)||B.workspace||void 0,workspace:B.workspace||void 0,lastLaunchedAt:B.lastMessageAt||0}})].sort((B,Ie)=>(Ie.lastLaunchedAt||0)-(B.lastLaunchedAt||0)),le=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(B=>({id:B.id,label:B.title||B.providerName||B.providerType,kind:B.kind,providerType:B.providerType,providerSessionId:B.providerSessionId,subtitle:bs(B.summaryMetadata)||B.workspace||void 0,workspace:B.workspace,summaryMetadata:B.summaryMetadata,lastLaunchedAt:B.lastLaunchedAt})):te,Ne=i.useMemo(()=>{var Ie;const B=((Ie=l.connectionStates)==null?void 0:Ie[t||""])||void 0;return d.filter(Pe=>Pe.daemonId===t&&Pe.type!=="adhdev-daemon").flatMap(Pe=>Co(Pe,{connectionStates:t&&B?{[t]:B}:void 0,defaultConnectionState:B})).filter(Pe=>!(Pe.transport==="pty"&&Pe.mode==="terminal")).sort((Pe,Fe)=>Ua(Fe)-Ua(Pe))},[d,l.connectionStates,t]),me=i.useCallback(B=>{const Ie=td(B);Ie&&r(Zt(Ie))},[r]),pe=i.useCallback(()=>{v.current&&(T(!0),v.current().finally(()=>{v.current=null,T(!1),A(null)}))},[]),oe=i.useCallback(B=>{if(!_)return;const{options:Ie,selectedKey:Pe}=ps({machine:_,currentWorkspacePath:B.workspace}),Fe=async()=>{S(B.kind),p("workspace")};v.current=async()=>{const He=Ie.find(tt=>tt.key===w.current),qe=(He==null?void 0:He.workspacePath)??null,Ye=(He==null?void 0:He.workspaceId)??null;if(B.kind==="ide"&&B.providerType){await R.handleLaunchIde(B.providerType,qe?{workspace:qe}:void 0);return}if((B.kind==="cli"||B.kind==="acp")&&B.providerType){await R.runLaunchCliCore({cliType:B.providerType,dir:Ye?void 0:qe||"",workspaceId:Ye||void 0,model:B.kind==="acp"&&Hc(B.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:B.providerSessionId});return}await Fe()},w.current=Pe,K(Pe),A({title:B.kind==="ide"?ls("restart-ide",B.label):B.providerSessionId?ko(B.label):ls("start-fresh",B.label),description:B.kind==="ide"?ds("restart-ide"):B.providerSessionId?So():ds("start-fresh"),confirmLabel:B.kind==="ide"?Bs("restart-ide"):B.providerSessionId?pn(!0):Bs("start-fresh"),busyLabel:B.kind==="ide"?Ks("restart-ide"):B.providerSessionId?wo(!0):Ks("start-fresh"),workspaceOptions:Ie,details:[{label:"Mode",value:B.kind.toUpperCase()},...B.providerType?[{label:"Provider",value:B.providerType}]:[]]})},[R,_]);if(i.useEffect(()=>{p(ue)},[de,ue,t]),i.useEffect(()=>{ge&&S(ge)},[ge,t]),!_)return m?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 fe=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Tt,{size:14})," Workspace"]}),count:E.length+U.length+Q.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Jt,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(wn,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Hu,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ku,{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:[R.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:R.nicknameInput,onChange:B=>R.setNicknameInput(B.target.value),onKeyDown:B=>{B.key==="Enter"&&R.handleSaveNickname(),B.key==="Escape"&&R.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:R.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:()=>R.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:()=>{R.setEditingNickname(!0),R.setNicknameInput(_.machineNickname||"")},title:"Click to set nickname",children:xe}),k?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:[_.platform," · ",_.arch]}),s.jsxs("span",{children:[_.cpus," cores"]}),(u==null?void 0:u.version)&&s.jsxs("span",{children:["v",u.version]}),_.p2p.available&&s.jsxs("span",{children:["P2P ",_.p2p.state==="connected"?"connected":_.p2p.state]}),_.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:_.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:fe.map(B=>s.jsxs("button",{onClick:()=>p(B.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${y===B.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[B.label,B.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${y===B.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:B.count})]},B.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:[y==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(p0,{machineEntry:u,providers:I,recentLaunches:le,currentConversations:Ne,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",Ql(u))}catch{}},onOpenRecent:oe,onOpenConversation:me}),s.jsx(g0,{machine:_,machineId:t,providers:I,ideSessions:E,cliSessions:U,acpSessions:Q,actions:R,getIcon:O,initialCategory:N,initialWorkspaceId:be,initialWorkspacePath:X,sendDaemonCommand:a,onOpenGitDialog:f})]}),y==="providers"&&s.jsx(Sy,{machineId:t,providers:I,sendDaemonCommand:a}),y==="overview"&&s.jsx(hy,{machineId:t,machine:_,ideSessions:E,cliSessions:U,acpSessions:Q,actions:R,sendDaemonCommand:a}),y==="session-host"&&s.jsx(m0,{machineId:t,cliSessions:U,sendDaemonCommand:a}),y==="logs"&&s.jsx(a0,{machineId:t,sendDaemonCommand:a})]})})}),R.launchPick&&_&&s.jsx(f0,{machine:_,launchPick:R.launchPick,actions:R}),M&&s.jsx(_o,{title:M.title,description:M.description,details:M.details,workspaceOptions:M.workspaceOptions,selectedWorkspaceKey:j,onWorkspaceChange:B=>{w.current=B,K(B)},confirmLabel:M.confirmLabel,busyLabel:M.busyLabel,busy:P,onConfirm:pe,onCancel:()=>{v.current=null,A(null)}}),x&&s.jsx(Id,{daemonId:x.daemonId,workspace:x.workspace,onClose:()=>g(null)}),s.jsx(kl,{toasts:l.toasts||[],onDismiss:B=>l.setToasts(Ie=>Ie.filter(Pe=>Pe.id!==B)),onClickToast:B=>{B.targetKey&&r(Zt(B.targetKey))}}),s.jsx("style",{children:`
91
+ 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 T=await r(e,"session_host_prune_duplicate_sessions",{}),W=ga(T);if(!(W!=null&&W.success))throw new Error((W==null?void 0:W.error)||"Duplicate prune failed");const H=W.result||{},R=Array.isArray(H.prunedSessionIds)?H.prunedSessionIds.length:0,I=typeof H.duplicateGroupCount=="number"?H.duplicateGroupCount:0;nt.showToast(`Pruned ${R} duplicate runtime(s) across ${I} group(s)`,"success"),await p()}catch(T){const W=T instanceof Error?T.message:"Duplicate prune failed";nt.showToast(W,"warning"),a(W)}finally{c(T=>T==="session_host_prune_duplicate_sessions"?null:T)}}},[e,p,r]),f=i.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((P,T)=>(T.lastActivityAt||0)-(P.lastActivityAt||0)),[u==null?void 0:u.sessions]),N=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)||[]}:i0(f),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,f]),S=N.liveRuntimes,v=N.recoverySnapshots,M=N.inactiveRecords,A=i.useMemo(()=>u0(S),[S]),w=i.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),j=i.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(P=>P.level==="warn"||P.level==="error")||null,[u==null?void 0:u.recentLogs]),K=(P,T)=>{var U;const W=o===`session_host_resume_session:${P.sessionId}`,H=o===`session_host_restart_session:${P.sessionId}`,R=o===`session_host_stop_session:${P.sessionId}`,I=Md(P.meta),C=y.get(P.sessionId),O=P.attachedClients.length===1?"1 client":`${P.attachedClients.length} clients`,_=T==="recovery"?"Recover":"Resume",E=c0(T);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:P.displayName||(C==null?void 0:C.cliName)||P.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${d0(P.lifecycle)}`,children:P.lifecycle}),I&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:I})]}),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:P.workspaceLabel||(C==null?void 0:C.runtimeWorkspaceLabel)||P.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:P.runtimeKey}),P.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",P.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((U=P.writeOwner)==null?void 0:U.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:l0(P.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(Nc,{size:11})," ",O]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",dc(P.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",E]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[T==="recovery"&&(P.lifecycle==="interrupted"||P.lifecycle==="failed"||P.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_resume_session",P)},children:W?`${_}ing…`:_}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_restart_session",P)},children:H?"Restarting…":"Restart"}),T==="live"&&(P.lifecycle==="running"||P.lifecycle==="starting"||P.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:()=>{x("session_host_stop_session",P)},children:R?"Stopping…":"Stop"})]})]})},P.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(Jt,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:gh()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[A>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{g()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${A})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${k.toneClass}`,children:k.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:h||l,children:[s.jsx(yr,{size:13}),h||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(xr,{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:v.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:dc(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:ya(u.hostStartedAt)})]})]}),j&&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(xr,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:j.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[ya(j.timestamp),j.sessionId?` · ${j.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(ro,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ba("live")}),S.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:S.map(P=>K(P,"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(Jt,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ba("recovery")}),v.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:v.map(P=>K(P,"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:ba("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:M.map(P=>K(P,"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"}),w.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:w.map(P=>{var W;const T=f.find(H=>H.sessionId===P.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:(T==null?void 0:T.displayName)||((W=y.get(P.sessionId))==null?void 0:W.cliName)||P.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[P.action,P.lifecycle?` · ${P.lifecycle}`:"",P.detail?` · ${P.detail}`:"",P.error?` · ${P.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${P.success===!1?"text-red-300":"text-text-secondary"}`,children:ya(P.timestamp)})]},`${P.sessionId}:${P.timestamp}:${P.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 f0({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 va({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 wa({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 p0({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),m="0.9.80",u=Jl(e),h=Cs(e,m),b=ur(e,h),k=u==="preview"?"Update to preview":"Update daemon";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(va,{icon:s.jsx(zt,{size:13}),children:"Current Chats"}),s.jsx(wa,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(y=>{const p=Ua(y);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(y),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:lt(y)}),p>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:kn(p)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:gs(y)})]},y.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(va,{icon:s.jsx(Mc,{size:13}),children:"Recent Launches"}),s.jsx(wa,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(y=>{const{metaText:p,updatedLabel:x}=cd(y);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(y),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:y.label}),x&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:x})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:p})]},y.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(va,{icon:s.jsx(xr,{size:13}),children:"Daemon Update"}),s.jsx(wa,{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:b?"Daemon update required":"Version mismatch detected"}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[b?"This machine is on an incompatible daemon version. Update it before starting more sessions.":u==="preview"?"This machine can be upgraded to the current preview daemon without opening a remote shell.":"This machine is running a different daemon version than the current app. Update it before starting more sessions.",h&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",h,u?` (${u})`:""]})]}),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(yr,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:k})]})]})})]})]})}function h0(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function x0({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 m=d.target.value;if(o(m),m==="__custom__"&&a){l();return}m!=="__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?"⭐ ":"",Nn(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 b0={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 Ur(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ja({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:o,actions:c,sendDaemonCommand:l,initialWorkspaceId:d,initialWorkspacePath:m,onOpenGitDialog:u}){const h=Ws(),{handleLaunchIde:b,handleStopCli:k,handleRestartIde:y,handleStopIde:p,handleDetectIdes:x,launchingIde:g,launchingAgentType:f,addLog:N}=c,[S,v]=i.useState(null),M=i.useCallback(L=>{L&&h(Zt(L))},[h]),A=b0[e],w=e==="ide",j=e==="acp",K=i.useMemo(()=>n.filter(L=>ys(L,e)),[e,n]),P=i.useMemo(()=>new Map(K.map(L=>[L.type,L.displayName||L.type])),[K]),[T,W]=i.useState(""),[H,R]=i.useState(""),[I,C]=i.useState([]),[O,_]=i.useState(""),[E,U]=i.useState(""),[Q,xe]=i.useState([]),[de,Z]=i.useState(!1),[he,we]=i.useState(!1),[be,X]=i.useState(""),[ue,ge]=i.useState(!1),[te,le]=i.useState(()=>jt()),[Ne,me]=i.useState(null),[pe,oe]=i.useState(m?"__custom__":d||t.defaultWorkspaceId||""),[fe,ie]=i.useState(m||""),[D,z]=i.useState([]),[ce,se]=i.useState(!1),[q,ke]=i.useState(""),[ve,Le]=i.useState([]),[Ae,B]=i.useState(!1),[Ie,Pe]=i.useState(""),Fe=i.useRef(null),[He,qe]=i.useState(null),Ye=i.useRef("__home__"),[tt,mt]=i.useState("__home__"),[ht,bt]=i.useState(!1),Te=i.useRef(0),Ue=D.filter(L=>!a.some(ae=>ae.type===L&&xt(ae.status)!=="stopped")),Qe=i.useRef({});i.useEffect(()=>{t.defaultWorkspaceId&&!pe&&oe(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),i.useEffect(()=>{if(m){oe("__custom__"),ie(m);return}d&&(oe(d),ie(""))},[d,m]),i.useEffect(()=>{w||T&&(K.some(L=>L.type===T)||(W(""),U("")))},[K,w,T]);const ze=(()=>{if(pe==="__custom__")return fe.trim();if(!pe)return"";const L=(t.workspaces||[]).find(ae=>ae.id===pe);return(L==null?void 0:L.path)||""})(),rt=i.useCallback(L=>{const ae=Qe.current[L];ae&&(clearTimeout(ae),delete Qe.current[L]),z(ye=>ye.includes(L)?ye.filter(Ke=>Ke!==L):ye)},[]),F=i.useRef(new Set),V=i.useCallback(async L=>{if(l){B(!0),Pe("");try{const ae=await Rn(l,r,L);ke(ae.path),ie(ae.path),Le(ae.directories)}catch(ae){Pe(ae instanceof Error?ae.message:"Could not load folder")}finally{B(!1)}}},[r,l]),J=i.useCallback(()=>{if(!l)return;oe("__custom__"),se(!0);const L=a.map(ye=>ye.workspace),ae=Ln(t.platform,An(fe.trim(),ze,m,L,t.defaultWorkspacePath,(t.workspaces||[]).map(ye=>ye.path)));V(ae)},[fe,m,V,t.defaultWorkspacePath,t.platform,t.workspaces,a,ze,l]),re=i.useCallback(L=>{const ae=String(L.workspace||"").trim();if(!ae)return;const ye=(t.workspaces||[]).find(Ke=>Ur(Ke.path)===Ur(ae));if(ye){oe(ye.id),ie("");return}oe("__custom__"),ie(ae)},[t.workspaces]),$=i.useCallback(L=>{const ae=String(L.workspace||"").trim();if(!ae)return{workspaceId:null,workspacePath:"",useHome:!0};const ye=(t.workspaces||[]).find(Ke=>Ur(Ke.path)===Ur(ae));return ye?{workspaceId:ye.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:ae,useHome:!1}},[t.workspaces]),Y=i.useCallback(async L=>{if(!l||!L||e!=="cli"){xe([]),Z(!1),we(!1),X("");return}const ae=Te.current+1;Te.current=ae,Z(!0),X("");try{const ye=await l(r,"list_saved_sessions",{providerType:L,kind:"cli",limit:30});if(Te.current!==ae)return;const Ke=(ye==null?void 0:ye.result)??ye;xe(Array.isArray(Ke==null?void 0:Ke.sessions)?Ke.sessions:[])}catch(ye){if(Te.current!==ae)return;xe([]),X(ye instanceof Error?ye.message:"Could not load saved sessions")}finally{Te.current===ae&&(Z(!1),we(!0))}},[e,r,l]),ee=i.useMemo(()=>{if(e!=="cli"||!T)return null;const L=P.get(T)||T;return{routeId:r,daemonId:r,providerSessionId:E||void 0,transport:"pty",mode:"chat",agentName:L,agentType:T,status:"idle",title:L,messages:[],ideType:T,workspaceName:ze,workspacePath:ze,displayPrimary:L,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${T}`}},[e,r,P,ze,E,T]),ne=i.useCallback(L=>{if(e==="ide"||!L){C([]);return}C(Ga(r,L))},[e,r]),Se=i.useCallback((L,ae)=>{e==="ide"||!L||(Rg(r,L,ae),C(Ga(r,L)))},[e,r]);i.useEffect(()=>{Te.current+=1,U(""),ne(T),we(!1),xe([]),X(""),Z(!1)},[e,ne,Y,T]);const De=i.useMemo(()=>Q.find(L=>L.providerSessionId===E)||null,[Q,E]);i.useEffect(()=>{if(!E)return;const L=Q.find(ae=>ae.providerSessionId===E);L!=null&&L.canResume||U("")},[Q,E]);const Ee=i.useCallback((L,ae)=>{Fe.current=ae,Ye.current=L.selectedWorkspaceKey||"__home__",mt(L.selectedWorkspaceKey||"__home__"),qe(L)},[]),Ce=i.useCallback(()=>{Fe.current&&(bt(!0),Fe.current().finally(()=>{Fe.current=null,bt(!1),qe(null)}))},[]),$e=i.useCallback(L=>{if(!L)return;z(ye=>ye.includes(L)?ye:[...ye,L]);const ae=Qe.current[L];ae&&clearTimeout(ae),Qe.current[L]=setTimeout(()=>{z(ye=>ye.includes(L)?ye.filter(Ke=>Ke!==L):ye),delete Qe.current[L]},2e4)},[]);i.useEffect(()=>{for(const ae of a)xt(ae.status)!=="stopped"&&(D.includes(ae.type)&&!F.current.has(ae.type)&&(F.current.add(ae.type),N("info",`${P.get(ae.type)||ae.type} launched`,!0)),rt(ae.type));const L=new Set(a.filter(ae=>xt(ae.status)!=="stopped").map(ae=>ae.type));F.current.forEach(ae=>{!D.includes(ae)&&!L.has(ae)&&F.current.delete(ae)})},[N,rt,a,D,P]),i.useEffect(()=>()=>{Object.values(Qe.current).forEach(clearTimeout),Qe.current={}},[]);const[Be,Re]=i.useState({}),[Xe,Ze]=i.useState(null);i.useEffect(()=>{if(!w||!r||!l)return;(async()=>{try{const ae=await l(r,"get_ide_extensions",{}),ye=(ae==null?void 0:ae.result)||ae;ye!=null&&ye.success&&(ye!=null&&ye.ideExtensions)&&Re(ye.ideExtensions)}catch{}})()},[w,r,l]);const ct=L=>w?it(L.type):e==="cli"?L.cliName:L.acpName,ft=w?t.detectedIdes||[]:[],dt=i.useCallback(async L=>{const ae=(L==null?void 0:L.type)||T,ye=(L==null?void 0:L.workspacePath)??ze;if(w){await b(ae,ye?{workspace:ye}:void 0)&&$e(ae);return}const Ke=await c.runLaunchCliCore({cliType:ae,dir:L!=null&&L.workspaceId?void 0:ye||void 0,workspaceId:(L==null?void 0:L.workspaceId)||void 0,useHome:(L==null?void 0:L.useHome)||!(L!=null&&L.workspaceId)&&!ye,argsStr:(L==null?void 0:L.argsStr)??(H||void 0),model:(L==null?void 0:L.model)??(j&&O||void 0),resumeSessionId:(L==null?void 0:L.resumeSessionId)||!j&&e==="cli"&&ae===T&&E||void 0});if(Ke.success||Ke.pending){const _e=(L==null?void 0:L.argsStr)??H;!w&&(_e!=null&&_e.trim())&&(jd(r,ae,_e),ne(ae)),$e(ae),Ke.success&&Ke.sessionId&&M(Ke.sessionId)}},[c,b,j,w,H,O,ne,$e,r,M,ze,E,T]),wt=wl(w?"ide":j?"acp":"cli",!w&&!j&&!!E),Ve=jl(w?"ide":j?"acp":"cli",!w&&!j&&!!E),je=()=>{var _e;const L=w?it(T):P.get(T)||T,ae=!w&&!j&&!!E,{options:ye,selectedKey:Ke}=ps({machine:t,currentWorkspaceId:pe&&pe!=="__custom__"?pe:null,currentWorkspacePath:ze});Ee({title:ae?ko(L):ls("start-fresh",L),description:ae?So():ds("start-fresh"),confirmLabel:wt,busyLabel:Ve,workspaceOptions:ye,selectedWorkspaceKey:Ke,details:[{label:"Mode",value:A.label},{label:"Provider",value:L},...!w&&e==="cli"&&E?[{label:"Resume",value:((_e=Q.find(Oe=>Oe.providerSessionId===E))==null?void 0:_e.title)||E}]:[],...!w&&H.trim()?[{label:"Arguments",value:H.trim()}]:[],...j&&O.trim()?[{label:"Model",value:O.trim()}]:[]]},async()=>{const Oe=ye.find(ot=>ot.key===Ye.current);Oe!=null&&Oe.workspaceId?(oe(Oe.workspaceId),ie("")):Oe!=null&&Oe.workspacePath?(oe("__custom__"),ie(Oe.workspacePath)):(oe(""),ie("")),await dt({workspaceId:(Oe==null?void 0:Oe.workspaceId)??null,workspacePath:(Oe==null?void 0:Oe.workspacePath)??"",useHome:!(Oe!=null&&Oe.workspaceId)&&!(Oe!=null&&Oe.workspacePath)})})},G=L=>{w?p(L):k(L.type,L.workspace,L.id)},Me=i.useCallback(async(L,ae,ye=!1)=>{if(L.mode===ae){ye&&L.sessionId&&M(L.sessionId);return}if(!l||!L.sessionId){ye&&L.sessionId&&M(L.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:L.sessionId,cliType:L.type,mode:ae}),ye&&M(L.sessionId)}catch(Ke){const _e=Fl(Ke);Wl(Ke)?console.warn(_e?"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 ${A.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 ",A.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:w?ft.length>0?ft.map(L=>{const ae=a.find(ot=>(ot.type||"").toLowerCase()===(L.type||"").toLowerCase()&&xt(ot.status)!=="stopped"),ye=L.running||!!ae,Ke=!!ae&&ae.cdpConnected,_e=D.includes(L.type||L.id||""),Oe=T===(L.type||"");return s.jsxs("button",{onClick:()=>{if(Ke&&ae){const ot=ae.sessionId;ot?h(Zt(ot),{state:{openRemoteForTabKey:ot}}):h("/dashboard",{state:{openRemoteForTabKey:ae.id}});return}_e||W(ot=>ot===(L.type||"")?"":L.type||"")},disabled:!!g||_e,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":Oe?"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:g&&g!==L.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(L.type)}),ye&&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:L.name||it(L.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Ke?"text-green-400":_e?"text-orange-400":Oe?"text-accent-primary":"text-text-muted"}`,children:Ke?"Open Session":_e?"Starting...":Oe?"Configure":"Select"})]})]},L.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:x,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(Wu,{size:14})," Scan System"]})]}):K.length>0?K.map(L=>{const ae=T===L.type,ye=D.includes(L.type),_e=!!a.find(Oe=>Oe.type===L.type&&xt(Oe.status)!=="stopped");return s.jsxs("button",{onClick:()=>W(Oe=>Oe===L.type?"":L.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${ae?"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:L.icon}),_e&&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:L.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ye?"text-orange-400":ae?"text-accent-primary":"text-text-muted"}`,children:ye?"Starting...":ae?"Configure":"Select"})]})]},L.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."})]})}),T&&(w?ft.find(L=>L.type===T):K.find(L=>L.type===T))&&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:w?it(T):P.get(T)||T})]}),s.jsx(x0,{machine:t,selectedWorkspace:pe,resolvedWorkspacePath:ze,customPath:fe,canBrowse:!!l,onWorkspaceChange:oe,onCustomPathChange:ie,onOpenBrowseDialog:J}),!w&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!j&&e==="cli"&&s.jsx(Sd,{busy:!!f||!!g||D.includes(T),savedSessionsLoading:de,savedSessionsError:be,savedSessionsLoaded:he,savedSessionsCount:Q.length,selectedSession:De,onRefresh:()=>void Y(T),onOpenHistory:()=>{T&&(ge(!0),kd({hasLoadedInitialResults:he,isLoading:de})&&Y(T))},onClearSelection:()=>U("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[j&&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:O,onChange:L=>_(L.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:L=>R(L.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"}),I.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:I.map(L=>s.jsxs("div",{className:"inline-flex max-w-full items-stretch overflow-hidden rounded-md border border-[#ffffff1a] bg-bg-tertiary text-xs text-text-secondary transition-colors hover:border-accent-primary/40 hover:text-text-primary",title:L,children:[s.jsx("button",{type:"button",className:"min-w-0 max-w-[220px] truncate px-2.5 py-1.5 text-left",onClick:()=>R(L),children:L}),s.jsx("button",{type:"button",className:"flex items-center justify-center border-l border-[#ffffff1a] px-1.5 text-text-muted transition-colors hover:bg-status-error/10 hover:text-status-error focus:outline-none focus:ring-1 focus:ring-status-error/50",onClick:()=>Se(T,L),"aria-label":`Remove startup arguments: ${L}`,title:"Remove startup arguments",children:s.jsx(vt,{size:12})})]},L))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:je,disabled:!!f||!!g||D.includes(T),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:f===T||g===T?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+D.filter(L=>!a.some(ae=>ae.type===L&&xt(ae.status)!=="stopped")).length,")"]}),a.length===0&&Ue.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 ",A.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Ue.map(L=>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(L)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:w?it(L):P.get(L)||L}),s.jsx("div",{className:"text-[11px] text-text-muted",children:f===L?"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:${L}`)),a.map(L=>{const ae=w?L:null,ye=!w&&!j?L:null,Ke=xt(L.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(L.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[ct(L),(ae==null?void 0:ae.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",ae.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:L.workspace||"—"}),u&&L.git&&L.workspace?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:_e=>{_e.stopPropagation(),u(L.daemonId??r,L.workspace)},children:s.jsx($s,{git:L.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx($s,{git:L.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(ye==null?void 0:ye.mode)&&s.jsx("span",{className:ye.mode==="chat"?"text-violet-400":"text-text-secondary",children:ye.mode==="chat"?"Chat view":"Terminal view"})]}),ye&&(ye.runtimeKey||ye.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ye.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 ",ye.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 _e;(_e=navigator.clipboard)==null||_e.writeText(`adhdev attach ${ye.runtimeKey}`),v(ye.runtimeKey||null),window.setTimeout(()=>{v(Oe=>Oe===ye.runtimeKey?null:Oe)},1200)},children:S===ye.runtimeKey?"Copied":"Copy"})]}),ye.runtimeWriteOwner&&s.jsx("span",{style:{color:ye.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ye.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:h0(ye.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}),w&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const _e=L.sessionId;if(_e){h(Zt(_e),{state:{openRemoteForTabKey:_e}});return}h("/dashboard",{state:{openRemoteForTabKey:L.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 _e=L.workspace||"",{options:Oe,selectedKey:ot}=ps({machine:t,currentWorkspacePath:_e});Ee({title:ls("restart-ide",it(L.type)),description:ds("restart-ide"),confirmLabel:Bs("restart-ide"),busyLabel:Ks("restart-ide"),workspaceOptions:Oe,selectedWorkspaceKey:ot,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:it(L.type)}]},async()=>{const Nt=Oe.find(Gt=>Gt.key===Ye.current),pt=(Nt==null?void 0:Nt.workspacePath)??"";if(pt&&pt!==_e){await dt({type:L.type,workspacePath:pt});return}await y(L)})},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(yr,{size:14})})]}),j&&s.jsx("button",{onClick:()=>{const _e=L.sessionId;_e&&M(_e)},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:!L.sessionId,children:s.jsx(zt,{size:14})}),ye&&Ke!=="stopped"&&s.jsxs(s.Fragment,{children:[ye.mode&&s.jsx(vo,{mode:ye.mode,onChange:_e=>void Me(ye,_e,!1),compact:!0}),s.jsx("button",{onClick:()=>{const _e=L.sessionId;_e&&M(_e)},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:!L.sessionId,children:ye.mode==="chat"?s.jsx(zt,{size:14}):s.jsx(Tt,{size:13})})]}),Ke==="stopped"?s.jsx("button",{onClick:()=>{const _e=L.workspace||"",Oe=w?it(L.type):ct(L),{options:ot,selectedKey:Nt}=ps({machine:t,currentWorkspacePath:_e});Ee({title:ls("restart-stopped",Oe),description:ds("restart-stopped"),confirmLabel:Bs("restart-stopped"),busyLabel:Ks("restart-stopped"),workspaceOptions:ot,selectedWorkspaceKey:Nt,details:[{label:"Mode",value:A.label},{label:"Provider",value:Oe}]},async()=>{const pt=ot.find(Gt=>Gt.key===Ye.current);await dt({type:L.type,workspaceId:(pt==null?void 0:pt.workspaceId)??null,workspacePath:(pt==null?void 0:pt.workspacePath)??"",useHome:!(pt!=null&&pt.workspaceId)&&!(pt!=null&&pt.workspacePath)})})},disabled:D.includes(L.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:D.includes(L.type)?"⏳":s.jsx(no,{size:14})}):s.jsx("button",{onClick:()=>G(L),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(vt,{size:14})})]})]}),ae&&ae.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:ae.aiAgents.map(_e=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${ln(_e.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[_e.name," · ",xt(_e.status)]},_e.id))}),ae&&(Be[ae.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:(Be[ae.type]||[]).map(_e=>s.jsxs("button",{disabled:Xe===`${ae.type}.${_e.type}`,onClick:async()=>{const Oe=`${ae.type}.${_e.type}`;Ze(Oe);try{await l(r,"set_ide_extension",{ideType:ae.type,extensionType:_e.type,enabled:!_e.enabled}),Re(ot=>({...ot,[ae.type]:(ot[ae.type]||[]).map(Nt=>Nt.type===_e.type?{...Nt,enabled:!Nt.enabled}:Nt)}))}catch(ot){console.error("Extension toggle failed:",ot)}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 ${_e.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 ${_e.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),_e.name,s.jsx("span",{className:"text-[9px] font-normal",children:_e.enabled?"ON":"OFF"})]},_e.type))})]})]},L.id)})]}),ce&&l&&s.jsx(Pn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:q,directories:ve,busy:Ae,error:Ie,confirmLabel:"Use this folder",onClose:()=>se(!1),onNavigate:L=>{V(L)},onConfirm:L=>{ie(L),oe("__custom__"),se(!1)}}),He&&s.jsx(_o,{title:He.title,description:He.description,details:He.details,workspaceOptions:He.workspaceOptions,selectedWorkspaceKey:tt,onWorkspaceChange:L=>{Ye.current=L,mt(L)},confirmLabel:He.confirmLabel,busyLabel:He.busyLabel,busy:ht,onConfirm:Ce,onCancel:()=>{Fe.current=null,qe(null)}}),ue&&ee&&s.jsx(No,{activeConv:ee,ides:[],isCreatingChat:!1,isRefreshingHistory:de,savedSessions:Q,isSavedSessionsLoading:de,isResumingSavedSessionId:Ne,savedHistoryFilters:te,missingWorkspaceResumePath:ze||null,onSavedHistoryFiltersChange:le,onClose:()=>ge(!1),onNewChat:()=>{U(""),ge(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Y(T)},onResumeSavedSession:L=>{if(!L.canResume||Ne)return;const ae=$(L);U(L.providerSessionId),re(L),me(L.providerSessionId),ge(!1),dt({type:L.providerType,workspaceId:ae.workspaceId,workspacePath:ae.workspacePath,useHome:ae.useHome,resumeSessionId:L.providerSessionId}).finally(()=>{me(ye=>ye===L.providerSessionId?null:ye)})}})]})}const uc=[{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 g0({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:o,actions:c,getIcon:l,initialCategory:d="ide",initialWorkspaceId:m,initialWorkspacePath:u,sendDaemonCommand:h,onOpenGitDialog:b}){var x;const[k,y]=i.useState(d);i.useEffect(()=>{y(d)},[d]);const p=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:uc.map(g=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${k===g.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>y(g.id),children:[s.jsx("span",{children:g.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${k===g.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:p[g.id]})]},g.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(x=uc.find(g=>g.id===k))==null?void 0:x.helper})]}),k==="ide"&&s.jsx(ja,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:b}),k==="cli"&&s.jsx(ja,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:b}),k==="acp"&&s.jsx(ja,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:o,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:b})]})}function y0({onNicknameSynced:e}={}){var ie,D,z,ce,se,q,ke,ve,Le,Ae;const{id:t}=uu(),r=Ws(),n=Qa(),{sendCommand:a}=gt(),o=jr(),c=El(),l=fl(),d=l.ides||[],m=l.initialLoaded??!0,u=d.find(B=>B.id===t&&B.type==="adhdev-daemon"),h=d.some(B=>B.type==="adhdev-daemon"),b=t?(ie=l.connectionRetryStatuses)==null?void 0:ie[t]:void 0,k=!!(b!=null&&b.blocked),[y,p]=i.useState("workspace"),[x,g]=i.useState(null),f=i.useCallback((B,Ie)=>{g({daemonId:B,workspace:Ie})},[]),[N,S]=i.useState("ide"),v=i.useRef(null),[M,A]=i.useState(null),w=i.useRef("__home__"),[j,K]=i.useState("__home__"),[P,T]=i.useState(!1),W=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||y!=="overview")return;const B=u.machine;(typeof(B==null?void 0:B.cpus)!="number"||typeof(B==null?void 0:B.totalMem)!="number"||typeof(B==null?void 0:B.arch)!="string"||typeof(B==null?void 0:B.release)!="string")&&c(t,{minFreshMs:3e4}).catch(()=>{})},[y,c,u,t]),xx(t&&y==="overview"?[t]:[],{enabled:y==="overview",intervalMs:lp});const H=()=>{if(h){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},R=py({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:W});i.useEffect(()=>nt.onToast(Ie=>{l.setToasts(Fe=>{if(Fe.some(Ye=>Ye.message===Ie.message&&Ie.timestamp-Ye.timestamp<3e3))return Fe;const qe={id:Ie.id,message:Ie.message,type:Ie.type,timestamp:Ie.timestamp,targetKey:Ie.targetKey,actions:Ie.actions};return[...Fe.slice(-4),qe]});const Pe=Ie.duration||5e3;setTimeout(()=>l.setToasts(Fe=>Fe.filter(He=>He.id!==Ie.id)),Pe)}),[l]);const I=(u==null?void 0:u.availableProviders)||[],C={};for(const B of I)C[B.type]=B.icon;const O=B=>C[B]||"",_=u?{id:u.id,hostname:Wc(u,{fallbackId:u.id}),platform:((D=u.machine)==null?void 0:D.platform)||"unknown",arch:((z=u.machine)==null?void 0:z.arch)||"",cpus:((ce=u.machine)==null?void 0:ce.cpus)||0,totalMem:((se=u.machine)==null?void 0:se.totalMem)||0,freeMem:(q=u.machine)==null?void 0:q.freeMem,availableMem:(ke=u.machine)==null?void 0:ke.availableMem,loadavg:(ve=u.machine)==null?void 0:ve.loadavg,uptime:(Le=u.machine)==null?void 0:Le.uptime,release:((Ae=u.machine)==null?void 0:Ae.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,E=d.filter(B=>B.daemonId===t&&B.type!=="adhdev-daemon").filter(B=>!br(B)&&!Ms(B)).map(B=>({id:B.id,sessionId:B.sessionId,type:B.type,version:B.version||"",instanceId:B.instanceId||"",status:B.status,workspace:B.workspace||null,terminals:B.terminals||0,aiAgents:ef(B.aiAgents||(B.agents||[]).map(Ie=>({id:Ie.name,name:Ie.name,status:Ie.status,version:Ie.version}))),activeChat:B.activeChat||null,chats:B.chats||[],childSessions:B.childSessions||[],cdpConnected:B.cdpConnected||!1,daemonId:t,lastMessageAt:B.lastMessageAt})),U=d.filter(B=>B.daemonId===t&&br(B)).map(B=>({id:B.id,sessionId:B.sessionId,type:B.type,cliName:B.cliName||B.type,status:B.status,workspace:B.workspace||"",activeChat:B.activeChat||null,providerSessionId:B.providerSessionId,mode:B.mode,runtimeKey:B.runtimeKey,runtimeDisplayName:B.runtimeDisplayName,runtimeWorkspaceLabel:B.runtimeWorkspaceLabel,runtimeWriteOwner:B.runtimeWriteOwner||null,runtimeAttachedClients:B.runtimeAttachedClients||[],daemonId:t,lastMessageAt:B.lastMessageAt})),Q=d.filter(B=>B.daemonId===t&&Ms(B)).map(B=>({id:B.id,sessionId:B.sessionId,type:B.type,acpName:B.cliName||B.type,status:B.status,workspace:B.workspace||"",activeChat:B.activeChat||null,providerSessionId:B.providerSessionId,daemonId:t,lastMessageAt:B.lastMessageAt})),xe=u?It(u,{fallbackId:t}):"",de="workspace",Z=n.state,he=Z==null?void 0:Z.initialMachineTab,we=Z==null?void 0:Z.initialWorkspaceCategory,be=Z==null?void 0:Z.initialWorkspaceId,X=Z==null?void 0:Z.initialWorkspacePath,ue=he==="ides"||he==="clis"||he==="acps"?"workspace":he||de,ge=he==="ides"?"ide":he==="clis"?"cli":he==="acps"?"acp":we,te=[...E.map(B=>{var Ie;return{id:`ide:${B.type}:${B.workspace||""}`,label:((Ie=B.activeChat)==null?void 0:Ie.title)||B.type,kind:"ide",providerType:B.type,subtitle:B.workspace||void 0,workspace:B.workspace||void 0,lastLaunchedAt:B.lastMessageAt||0}}),...U.map(B=>{var Ie;return{id:`cli:${B.type}:${B.workspace||""}`,label:((Ie=B.activeChat)==null?void 0:Ie.title)||B.cliName,kind:"cli",providerType:B.type,providerSessionId:B.providerSessionId,subtitle:B.workspace||void 0,workspace:B.workspace||void 0,lastLaunchedAt:B.lastMessageAt||0}}),...Q.map(B=>{var Ie;return{id:`acp:${B.type}:${B.workspace||""}`,label:((Ie=B.activeChat)==null?void 0:Ie.title)||B.acpName,kind:"acp",providerType:B.type,providerSessionId:B.providerSessionId,subtitle:bs(B.summaryMetadata)||B.workspace||void 0,workspace:B.workspace||void 0,lastLaunchedAt:B.lastMessageAt||0}})].sort((B,Ie)=>(Ie.lastLaunchedAt||0)-(B.lastLaunchedAt||0)),le=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(B=>({id:B.id,label:B.title||B.providerName||B.providerType,kind:B.kind,providerType:B.providerType,providerSessionId:B.providerSessionId,subtitle:bs(B.summaryMetadata)||B.workspace||void 0,workspace:B.workspace,summaryMetadata:B.summaryMetadata,lastLaunchedAt:B.lastLaunchedAt})):te,Ne=i.useMemo(()=>{var Ie;const B=((Ie=l.connectionStates)==null?void 0:Ie[t||""])||void 0;return d.filter(Pe=>Pe.daemonId===t&&Pe.type!=="adhdev-daemon").flatMap(Pe=>Co(Pe,{connectionStates:t&&B?{[t]:B}:void 0,defaultConnectionState:B})).filter(Pe=>!(Pe.transport==="pty"&&Pe.mode==="terminal")).sort((Pe,Fe)=>Ua(Fe)-Ua(Pe))},[d,l.connectionStates,t]),me=i.useCallback(B=>{const Ie=td(B);Ie&&r(Zt(Ie))},[r]),pe=i.useCallback(()=>{v.current&&(T(!0),v.current().finally(()=>{v.current=null,T(!1),A(null)}))},[]),oe=i.useCallback(B=>{if(!_)return;const{options:Ie,selectedKey:Pe}=ps({machine:_,currentWorkspacePath:B.workspace}),Fe=async()=>{S(B.kind),p("workspace")};v.current=async()=>{const He=Ie.find(tt=>tt.key===w.current),qe=(He==null?void 0:He.workspacePath)??null,Ye=(He==null?void 0:He.workspaceId)??null;if(B.kind==="ide"&&B.providerType){await R.handleLaunchIde(B.providerType,qe?{workspace:qe}:void 0);return}if((B.kind==="cli"||B.kind==="acp")&&B.providerType){await R.runLaunchCliCore({cliType:B.providerType,dir:Ye?void 0:qe||"",workspaceId:Ye||void 0,model:B.kind==="acp"&&Hc(B.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:B.providerSessionId});return}await Fe()},w.current=Pe,K(Pe),A({title:B.kind==="ide"?ls("restart-ide",B.label):B.providerSessionId?ko(B.label):ls("start-fresh",B.label),description:B.kind==="ide"?ds("restart-ide"):B.providerSessionId?So():ds("start-fresh"),confirmLabel:B.kind==="ide"?Bs("restart-ide"):B.providerSessionId?pn(!0):Bs("start-fresh"),busyLabel:B.kind==="ide"?Ks("restart-ide"):B.providerSessionId?wo(!0):Ks("start-fresh"),workspaceOptions:Ie,details:[{label:"Mode",value:B.kind.toUpperCase()},...B.providerType?[{label:"Provider",value:B.providerType}]:[]]})},[R,_]);if(i.useEffect(()=>{p(ue)},[de,ue,t]),i.useEffect(()=>{ge&&S(ge)},[ge,t]),!_)return m?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 fe=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Tt,{size:14})," Workspace"]}),count:E.length+U.length+Q.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Jt,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(wn,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Hu,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ku,{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:[R.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:R.nicknameInput,onChange:B=>R.setNicknameInput(B.target.value),onKeyDown:B=>{B.key==="Enter"&&R.handleSaveNickname(),B.key==="Escape"&&R.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:R.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:()=>R.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:()=>{R.setEditingNickname(!0),R.setNicknameInput(_.machineNickname||"")},title:"Click to set nickname",children:xe}),k?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:[_.platform," · ",_.arch]}),s.jsxs("span",{children:[_.cpus," cores"]}),(u==null?void 0:u.version)&&s.jsxs("span",{children:["v",u.version]}),_.p2p.available&&s.jsxs("span",{children:["P2P ",_.p2p.state==="connected"?"connected":_.p2p.state]}),_.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:_.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:fe.map(B=>s.jsxs("button",{onClick:()=>p(B.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${y===B.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[B.label,B.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${y===B.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:B.count})]},B.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:[y==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(p0,{machineEntry:u,providers:I,recentLaunches:le,currentConversations:Ne,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",Ql(u))}catch{}},onOpenRecent:oe,onOpenConversation:me}),s.jsx(g0,{machine:_,machineId:t,providers:I,ideSessions:E,cliSessions:U,acpSessions:Q,actions:R,getIcon:O,initialCategory:N,initialWorkspaceId:be,initialWorkspacePath:X,sendDaemonCommand:a,onOpenGitDialog:f})]}),y==="providers"&&s.jsx(Sy,{machineId:t,providers:I,sendDaemonCommand:a}),y==="overview"&&s.jsx(hy,{machineId:t,machine:_,ideSessions:E,cliSessions:U,acpSessions:Q,actions:R,sendDaemonCommand:a}),y==="session-host"&&s.jsx(m0,{machineId:t,cliSessions:U,sendDaemonCommand:a}),y==="logs"&&s.jsx(a0,{machineId:t,sendDaemonCommand:a})]})})}),R.launchPick&&_&&s.jsx(f0,{machine:_,launchPick:R.launchPick,actions:R}),M&&s.jsx(_o,{title:M.title,description:M.description,details:M.details,workspaceOptions:M.workspaceOptions,selectedWorkspaceKey:j,onWorkspaceChange:B=>{w.current=B,K(B)},confirmLabel:M.confirmLabel,busyLabel:M.busyLabel,busy:P,onConfirm:pe,onCancel:()=>{v.current=null,A(null)}}),x&&s.jsx(Id,{daemonId:x.daemonId,workspace:x.workspace,onClose:()=>g(null)}),s.jsx(kl,{toasts:l.toasts||[],onDismiss:B=>l.setToasts(Ie=>Ie.filter(Pe=>Pe.id!==B)),onClickToast:B=>{B.targetKey&&r(Zt(B.targetKey))}}),s.jsx("style",{children:`
92
92
  @keyframes toast-in {
93
93
  from { opacity: 0; transform: translateX(40px); }
94
94
  to { opacity: 1; transform: translateX(0); }
95
95
  }
96
96
  `})]})}function v0(e){switch(e){case"online":return"#22c55e";case"dirty":return"#f59e0b";case"degraded":return"#ef4444";case"wrong_branch":return"#a855f7";case"offline":return"#6b7280";default:return"#9ca3af"}}function w0(e){switch(e){case"parentBranch":return"rgba(148,163,184,0.6)";case"worktreeLink":return"rgba(59,130,246,0.4)";case"sessionLink":return"rgba(168,85,247,0.4)";default:return"rgba(148,163,184,0.3)"}}function j0(e,t,r,n,a=120){const o=r/2,c=n/2;for(let l=0;l<a;l++){for(let d=0;d<e.length;d++)for(let m=d+1;m<e.length;m++){const u=e[m].x-e[d].x,h=e[m].y-e[d].y;let b=Math.sqrt(u*u+h*h)||1;const k=8e3/(b*b),y=u/b*k,p=h/b*k;e[d].vx-=y,e[d].vy-=p,e[m].vx+=y,e[m].vy+=p}for(const d of t){const m=e.find(f=>f.id===d.source),u=e.find(f=>f.id===d.target);if(!m||!u)continue;const h=u.x-m.x,b=u.y-m.y,k=Math.sqrt(h*h+b*b)||1,y=d.type==="parentBranch"?140:90,p=(k-y)/k*.08,x=h*p,g=b*p;m.vx+=x,m.vy+=g,u.vx-=x,u.vy-=g}for(const d of e)d.vx+=(o-d.x)*.003,d.vy+=(c-d.y)*.003;for(const d of e){d.vx*=.85,d.vy*=.85,d.x+=d.vx,d.y+=d.vy;const m=d.radius+10;d.x=Math.max(m,Math.min(r-m,d.x)),d.y=Math.max(m,Math.min(n-m,d.y))}}}function k0({data:e,width:t=800,height:r=500,onNodeClick:n,selectedNodeId:a}){const o=i.useRef(null),[c,l]=i.useState(1),[d,m]=i.useState({x:0,y:0}),[u,h]=i.useState(!1),b=i.useRef(null),k=i.useMemo(()=>{const f=e.nodes.map((N,S)=>({...N,x:t/2+Math.cos(S/Math.max(e.nodes.length,1)*Math.PI*2)*120,y:r/2+Math.sin(S/Math.max(e.nodes.length,1)*Math.PI*2)*120,vx:0,vy:0,radius:N.type==="defaultBranchNode"?28:20}));return j0(f,e.edges,t,r,120),f},[e,t,r]),y=i.useCallback(f=>{f.preventDefault();const N=f.deltaY>0?.9:1.1;l(S=>Math.max(.3,Math.min(3,S*N)))},[]),p=i.useCallback(f=>{b.current={startX:f.clientX,startY:f.clientY,panX:d.x,panY:d.y},h(!0)},[d]),x=i.useCallback(f=>{if(!b.current)return;const N=b.current;m({x:N.panX+(f.clientX-N.startX),y:N.panY+(f.clientY-N.startY)})},[]),g=i.useCallback(()=>{b.current=null,h(!1)},[]);return s.jsxs("div",{className:"relative rounded-xl border border-border-subtle bg-bg-panel overflow-hidden",style:{width:t,height:r},children:[s.jsxs("div",{className:"absolute top-2 left-2 z-10 flex flex-wrap gap-2",children:[s.jsxs("span",{className:"px-2 py-0.5 rounded bg-bg-glass text-[10px] text-text-muted border border-border-subtle",children:["Nodes: ",e.stats.totalNodes]}),s.jsxs("span",{className:"px-2 py-0.5 rounded bg-green-500/10 text-[10px] text-green-400 border border-green-500/20",children:["Online: ",e.stats.onlineNodes]}),e.stats.dirtyNodes>0&&s.jsxs("span",{className:"px-2 py-0.5 rounded bg-yellow-500/10 text-[10px] text-yellow-400 border border-yellow-500/20",children:["Dirty: ",e.stats.dirtyNodes]}),e.stats.orphanNodes>0&&s.jsxs("span",{className:"px-2 py-0.5 rounded bg-red-500/10 text-[10px] text-red-400 border border-red-500/20",children:["Orphan: ",e.stats.orphanNodes]}),e.stats.totalActiveSessions>0&&s.jsxs("span",{className:"px-2 py-0.5 rounded bg-blue-500/10 text-[10px] text-blue-400 border border-blue-500/20",children:["Sessions: ",e.stats.totalActiveSessions]})]}),s.jsxs("div",{className:"absolute bottom-2 right-2 z-10 flex flex-col gap-1",children:[s.jsx("button",{className:"w-7 h-7 rounded bg-bg-glass border border-border-subtle text-text-muted hover:text-text-primary flex items-center justify-center text-xs",onClick:()=>l(f=>Math.min(3,f*1.2)),children:"+"}),s.jsx("button",{className:"w-7 h-7 rounded bg-bg-glass border border-border-subtle text-text-muted hover:text-text-primary flex items-center justify-center text-xs",onClick:()=>l(f=>Math.max(.3,f/1.2)),children:"-"}),s.jsx("button",{className:"w-7 h-7 rounded bg-bg-glass border border-border-subtle text-text-muted hover:text-text-primary flex items-center justify-center text-[9px]",onClick:()=>{l(1),m({x:0,y:0})},children:"⟲"})]}),e.warnings.length>0&&s.jsx("div",{className:"absolute top-2 right-2 z-10 flex flex-col gap-1 max-w-[200px]",children:e.warnings.map((f,N)=>s.jsxs("div",{className:"px-2 py-0.5 rounded bg-red-500/10 text-[10px] text-red-400 border border-red-500/20",children:["⚠ ",f]},N))}),s.jsx("svg",{ref:o,width:t,height:r,onWheel:y,onMouseDown:p,onMouseMove:x,onMouseUp:g,onMouseLeave:g,style:{cursor:u?"grabbing":"grab"},children:s.jsxs("g",{transform:`translate(${d.x}, ${d.y}) scale(${c})`,children:[e.edges.map(f=>{const N=k.find(v=>v.id===f.source),S=k.find(v=>v.id===f.target);return!N||!S?null:s.jsxs("g",{children:[s.jsx("line",{x1:N.x,y1:N.y,x2:S.x,y2:S.y,stroke:w0(f.type),strokeWidth:f.type==="parentBranch"?2:1,strokeDasharray:f.type==="worktreeLink"?"4 3":void 0}),f.label&&s.jsx("text",{x:(N.x+S.x)/2,y:(N.y+S.y)/2-4,fill:"#94a3b8",fontSize:9,textAnchor:"middle",children:f.label})]},f.id)}),k.map(f=>s.jsxs("g",{transform:`translate(${f.x}, ${f.y})`,onClick:()=>n==null?void 0:n(f),style:{cursor:"pointer"},children:[f.hasConflicts&&s.jsxs("circle",{r:f.radius+6,fill:"none",stroke:"#ef4444",strokeWidth:1.5,opacity:.5,children:[s.jsx("animate",{attributeName:"r",values:`${f.radius+4};${f.radius+8};${f.radius+4}`,dur:"2s",repeatCount:"indefinite"}),s.jsx("animate",{attributeName:"opacity",values:"0.6;0.2;0.6",dur:"2s",repeatCount:"indefinite"})]}),s.jsx("circle",{r:f.radius,fill:v0(f.health),opacity:f.health==="offline"?.4:.9,stroke:a===f.id?"#38bdf8":"#0f172a",strokeWidth:a===f.id?3:2}),f.dirty&&s.jsx("circle",{r:f.radius-4,fill:"none",stroke:"#f59e0b",strokeWidth:a===f.id?3:2,strokeDasharray:"3 2"}),s.jsx("text",{y:f.radius+14,fill:"#e2e8f0",fontSize:10,textAnchor:"middle",fontWeight:600,children:f.label}),f.branch&&s.jsx("text",{y:f.radius+26,fill:"#94a3b8",fontSize:9,textAnchor:"middle",children:f.branch}),(f.ahead>0||f.behind>0)&&s.jsxs("g",{transform:`translate(${f.radius-6}, -${f.radius-6})`,children:[s.jsx("circle",{r:10,fill:"#0f172a",stroke:"#334155",strokeWidth:1}),s.jsx("text",{y:3,fill:"#e2e8f0",fontSize:8,textAnchor:"middle",children:f.ahead>0?`+${f.ahead}`:`-${f.behind}`})]}),f.activeSessionCount>0&&s.jsxs("g",{transform:`translate(-${f.radius-6}, -${f.radius-6})`,children:[s.jsx("circle",{r:10,fill:"#0f172a",stroke:"#3b82f6",strokeWidth:1}),s.jsx("text",{y:3,fill:"#60a5fa",fontSize:8,textAnchor:"middle",children:f.activeSessionCount})]})]},f.id))]})})]})}function rs({label:e,value:t}){return t==null||t===""?null:s.jsxs("div",{className:"flex justify-between text-[11px] py-0.5 border-b border-border-subtle/50",children:[s.jsx("span",{className:"text-text-muted",children:e}),s.jsx("span",{className:"text-text-secondary font-medium",children:String(t)})]})}function S0({health:e}){const t={online:"bg-green-500/10 text-green-400 border-green-500/20",dirty:"bg-yellow-500/10 text-yellow-400 border-yellow-500/20",degraded:"bg-red-500/10 text-red-400 border-red-500/20",wrong_branch:"bg-purple-500/10 text-purple-400 border-purple-500/20",offline:"bg-gray-500/10 text-gray-400 border-gray-500/20",unknown:"bg-gray-500/10 text-gray-400 border-gray-500/20"};return s.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] border ${t[e]||t.unknown}`,children:e})}function N0({node:e,onClose:t}){return e?s.jsxs("div",{className:"w-64 rounded-xl border border-border-subtle bg-bg-panel p-4 flex flex-col gap-2 shadow-lg",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary truncate",children:e.label}),t&&s.jsx("button",{onClick:t,className:"text-text-muted hover:text-text-primary text-xs",children:"✕"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(S0,{health:e.health}),e.dirty&&s.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] bg-yellow-500/10 text-yellow-400 border border-yellow-500/20",children:"Dirty"}),e.hasConflicts&&s.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] bg-red-500/10 text-red-400 border border-red-500/20",children:"Conflict"}),e.isOrphan&&s.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] bg-red-500/10 text-red-400 border border-red-500/20",children:"Orphan"})]}),s.jsxs("div",{className:"flex flex-col gap-0.5 mt-1",children:[s.jsx(rs,{label:"Workspace",value:e.workspace}),s.jsx(rs,{label:"Branch",value:e.branch}),s.jsx(rs,{label:"Ahead",value:e.ahead>0?`+${e.ahead}`:null}),s.jsx(rs,{label:"Behind",value:e.behind>0?`-${e.behind}`:null}),s.jsx(rs,{label:"Dirty files",value:e.dirtyFiles>0?e.dirtyFiles:null}),s.jsx(rs,{label:"Active sessions",value:e.activeSessionCount>0?e.activeSessionCount:null}),s.jsx(rs,{label:"Providers",value:e.providers.join(", ")||null})]}),e.orphanReasons.length>0&&s.jsxs("div",{className:"mt-1",children:[s.jsx("div",{className:"text-[10px] font-semibold text-red-400 mb-1",children:"Orphan reasons"}),s.jsx("ul",{className:"list-disc list-inside text-[10px] text-red-300 space-y-0.5",children:e.orphanReasons.map((r,n)=>s.jsx("li",{children:r},n))})]}),e.nextStepHint&&s.jsxs("div",{className:"mt-1 px-2 py-1.5 rounded bg-blue-500/10 border border-blue-500/20 text-[10px] text-blue-300",children:["💡 ",e.nextStepHint]})]}):s.jsx("div",{className:"w-64 rounded-xl border border-border-subtle bg-bg-panel p-4 text-text-muted text-xs",children:"Select a node to view details."})}const zr=[{value:"preserve",label:"Preserve history and runtimes",description:"Keep completed chat history and leave live runtimes alone."},{value:"stop",label:"Stop live runtimes only",description:"Release running session processes, but keep chat records/transcripts."},{value:"delete_stopped",label:"Delete stopped sessions only",description:"Clean completed/stopped chat clutter without killing live runtimes."},{value:"stop_and_delete",label:"Stop and delete sessions",description:"Stop matching runtimes, then remove their session records/transcripts."}],C0={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,sessionCleanupOnNodeRemove:"preserve"};function tn(e){var n;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((n=e.policy)==null?void 0:n.providerPriority)?e.policy.providerPriority:[],r=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>r.has(a)?!1:(r.add(a),!0))}function I0(e){const t=tn(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"launch not ready unless an explicit provider is selected"}}function T0(e,t){return t.filter(r=>r.status!=="assigned"?!1:(r.assignedNodeId||r.nodeId)===e.id)}function M0(e){const t=e.assignedSessionId||e.sessionId||"unassigned session",r=e.message.length>80?`${e.message.slice(0,77)}…`:e.message;return`${t}: ${r}`}function A0(e,t){return[...Array.isArray(t==null?void 0:t.cliSessions)?t.cliSessions:[],...Array.isArray(t==null?void 0:t.acpSessions)?t.acpSessions:[],...Array.isArray(t==null?void 0:t.sessions)?t.sessions:[]].filter(n=>{var a;return((a=n==null?void 0:n.settings)==null?void 0:a.meshNodeId)===e.id||(n==null?void 0:n.workspace)===e.workspace}).map(n=>{var a;return{id:n.sessionId||n.id||n.instanceId||"unknown",provider:n.providerType||n.cliType||n.acpType||n.type||"unknown",status:n.status||((a=n.activeChat)==null?void 0:a.status)||"unknown"}})}function ka(e){return{...C0,...(e==null?void 0:e.policy)||{}}}function L0({meshId:e,availableCliAgents:t}){const r=t.find(a=>{const o=a.id.toLowerCase(),c=a.name.toLowerCase();return o==="hermes-cli"||o.includes("hermes")||c.includes("hermes")}),n=ed(r==null?void 0:r.meshCoordinator,{meshId:e});return n?s.jsx(yt,{title:"Hermes MCP Config",description:"Hermes does not auto-import repo-local .mcp.json. Add this YAML under mcp_servers in Hermes config, then start a fresh Hermes session.",children:s.jsx(Nd,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}function R0(){var ie;const{sendCommand:e}=gt(),{ides:t}=es(),r=t.find(D=>D.daemonMode||D.type==="adhdev-daemon"),n=(r==null?void 0:r.id)||"",a=[];let o=[];if(r){const D=r.availableProviders||[];o=Ah(D);for(const z of D)z.category==="cli"&&a.push({id:z.type||z.id,name:z.displayName||z.name||z.type,meshCoordinator:z.meshCoordinator})}const[c,l]=i.useState([]),[d,m]=i.useState(null),[u,h]=i.useState(!0),[b,k]=i.useState(null),[y,p]=i.useState(!1),[x,g]=i.useState(null),[f,N]=i.useState({}),[S,v]=i.useState([]),[M,A]=i.useState(null),[w,j]=i.useState(null),[K,P]=i.useState(!1),[T,W]=i.useState(null),[H,R]=i.useState(null),[I,C]=i.useState(!1),[O,_]=i.useState(""),[E,U]=i.useState(""),[Q,xe]=i.useState(!1),[de,Z]=i.useState(""),[he,we]=i.useState([]),be=c.find(D=>D.id===d)||null;i.useEffect(()=>{N(Object.fromEntries(((be==null?void 0:be.nodes)||[]).map(D=>[D.id,tn(D)])))},[be]),i.useEffect(()=>{const D=Lh(o);Q&&he.length===0&&D.length>0&&we(D)},[Q,o,he.length]),i.useEffect(()=>{const D=new Set(((be==null?void 0:be.nodes)||[]).map(z=>z.id));M&&!D.has(M)&&A(null)},[be,M]);const X=i.useCallback(async()=>{if(n){h(!0);try{const D=await e(n,"list_meshes");D!=null&&D.success?(l(D.meshes||[]),k(null)):k((D==null?void 0:D.error)||"Failed to load meshes")}catch(D){k((D==null?void 0:D.message)||"Failed to load meshes")}finally{h(!1)}}},[n,e]),ue=i.useCallback(async D=>{if(!n||!D){v([]);return}try{const z=await e(n,"get_mesh_queue",{meshId:D});z!=null&&z.success?v(Array.isArray(z.queue)?z.queue:[]):v([])}catch{v([])}},[n,e]);i.useEffect(()=>{X()},[X]),i.useEffect(()=>{ue(d)},[ue,d]);async function ge(){if(!(!n||!d))try{P(!0),W(null);const D=await e(n,"mesh_status",{meshId:d});if(D!=null&&D.success){const z=D.status||D.result||D;if(z&&typeof z=="object"){const ce=$0(z);j(ce)}else W("Invalid mesh_status response format")}else W((D==null?void 0:D.error)||"mesh_status failed")}catch(D){W((D==null?void 0:D.message)||"Failed to load mesh graph")}finally{P(!1)}}i.useEffect(()=>{d&&(j(null),W(null),R(null),ge())},[d]);async function te(){var D;if(!(!n||!O.trim()))try{const z=await e(n,"create_mesh",{name:O.trim(),repoIdentity:E.trim()||void 0});z!=null&&z.success?(C(!1),_(""),U(""),await X(),m(((D=z.mesh)==null?void 0:D.id)||null)):k((z==null?void 0:z.error)||"Create failed")}catch(z){k((z==null?void 0:z.message)||"Create failed")}}async function le(D){if(!(!n||!confirm("Delete this mesh?")))try{await e(n,"delete_mesh",{meshId:D}),m(null),await X()}catch(z){k((z==null?void 0:z.message)||"Delete failed")}}async function Ne(){if(!(!n||!d||!de.trim()))try{const D=await e(n,"add_mesh_node",{meshId:d,workspace:de.trim(),providerPriority:Ka(he,o)});D!=null&&D.success?(xe(!1),Z(""),we([]),await X(),await ue(d)):k((D==null?void 0:D.error)||"Add node failed")}catch(D){k((D==null?void 0:D.message)||"Add node failed")}}async function me(D){var se;if(!n||!d)return;const z=ka(be),ce=((se=zr.find(q=>q.value===z.sessionCleanupOnNodeRemove))==null?void 0:se.label)||"Preserve history and runtimes";if(confirm(`Remove this node?
97
97
 
98
- Node removal cleanup policy: ${ce}`))try{await e(n,"remove_mesh_node",{meshId:d,nodeId:D}),M===D&&A(null),await X(),await ue(d)}catch(q){k((q==null?void 0:q.message)||"Remove node failed")}}async function pe(D){if(!n||!d)return;const z={...ka(be),...D};try{p(!0),k(null);const ce=await e(n,"update_mesh",{meshId:d,policy:z});if((ce==null?void 0:ce.success)===!1){k(ce.error||"Policy update failed");return}await X()}catch(ce){k((ce==null?void 0:ce.message)||"Policy update failed")}finally{p(!1)}}async function oe(D){if(!n||!d)return;const z=Ka(f[D.id]||tn(D),o),ce={...D.policy||{}};delete ce.provider_priority,z.length?ce.providerPriority=z:delete ce.providerPriority;try{g(D.id),k(null);const se=await e(n,"update_mesh_node",{meshId:d,nodeId:D.id,policy:ce});if((se==null?void 0:se.success)===!1){k(se.error||"Node policy update failed");return}await X()}catch(se){k((se==null?void 0:se.message)||"Node policy update failed")}finally{g(null)}}if(!n)return s.jsx(dr,{icon:s.jsx(Ar,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})});if(!be)return s.jsxs(dr,{icon:s.jsx(Ar,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>C(!0),children:"+ Create Mesh"}),children:[b&&s.jsx(Ts,{variant:"error",className:"mb-4",children:b}),I&&s.jsx(yt,{title:"New Mesh",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Mt,{label:"Name",children:s.jsx(Jn,{value:O,onChange:D=>_(D.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(Mt,{label:"Repo Identity (optional)",children:s.jsx(Jn,{value:E,onChange:D=>U(D.target.value),placeholder:"github.com/user/repo"})}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:te,disabled:!O.trim(),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>C(!1),children:"Cancel"})]})]})}),u?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):c.length===0?s.jsx(hn,{icon:s.jsx(Ar,{}),title:"No meshes",description:"Create a mesh to get started."}):s.jsx("div",{className:"flex flex-col gap-2",children:c.map(D=>s.jsxs("button",{className:"text-left w-full p-4 rounded-xl border border-border-subtle bg-bg-panel hover:border-accent-primary/40 transition-colors",onClick:()=>m(D.id),children:[s.jsx("div",{className:"font-semibold text-sm",children:D.name}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5 font-mono",children:D.repoIdentity||"No repo identity"}),s.jsxs("div",{className:"text-[10px] text-text-muted mt-1",children:[D.nodes.length," node(s)"]})]},D.id))})]});const fe=ka(be);return s.jsxs(dr,{icon:s.jsx(Ar,{}),title:be.name,subtitle:be.repoIdentity||"Repo Mesh",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>m(null),children:"← Back"}),s.jsx("button",{className:"btn btn-sm",style:{color:"var(--color-red-400)"},onClick:()=>le(be.id),children:"Delete"})]}),children:[b&&s.jsx(Ts,{variant:"error",className:"mb-4",children:b}),s.jsxs(yt,{title:"Policy",description:"Coordinator safety defaults and node-removal session cleanup behavior for this local mesh.",children:[s.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[s.jsx(Mt,{label:"Checkpoint before task",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:fe.requirePreTaskCheckpoint?"yes":"no",onChange:D=>pe({requirePreTaskCheckpoint:D.target.value==="yes"}),disabled:y,children:[s.jsx("option",{value:"no",children:"No"}),s.jsx("option",{value:"yes",children:"Yes"})]})}),s.jsx(Mt,{label:"Checkpoint after task",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:fe.requirePostTaskCheckpoint?"yes":"no",onChange:D=>pe({requirePostTaskCheckpoint:D.target.value==="yes"}),disabled:y,children:[s.jsx("option",{value:"yes",children:"Yes"}),s.jsx("option",{value:"no",children:"No"})]})}),s.jsx(Mt,{label:"Push approval",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:fe.requireApprovalForPush?"required":"not_required",onChange:D=>pe({requireApprovalForPush:D.target.value==="required"}),disabled:y,children:[s.jsx("option",{value:"required",children:"Require approval before push"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(Mt,{label:"Destructive git approval",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:fe.requireApprovalForDestructiveGit?"required":"not_required",onChange:D=>pe({requireApprovalForDestructiveGit:D.target.value==="required"}),disabled:y,children:[s.jsx("option",{value:"required",children:"Require approval"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(Mt,{label:"Dirty workspace behavior",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:fe.dirtyWorkspaceBehavior||"warn",onChange:D=>pe({dirtyWorkspaceBehavior:D.target.value}),disabled:y,children:[s.jsx("option",{value:"warn",children:"Warn and continue"}),s.jsx("option",{value:"block",children:"Block task"}),s.jsx("option",{value:"checkpoint_then_continue",children:"Checkpoint then continue"})]})}),s.jsx(Mt,{label:"Max parallel tasks",children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:String(fe.maxParallelTasks??2),onChange:D=>pe({maxParallelTasks:Number(D.target.value)}),disabled:y,children:[1,2,3,4,5,6,7,8].map(D=>s.jsx("option",{value:D,children:D},D))})})]}),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(Mt,{label:"Node removal session cleanup",hint:"Separate transcript cleanup from runtime/process cleanup. Preserve is safest when completed work may need review.",children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:fe.sessionCleanupOnNodeRemove||"preserve",onChange:D=>pe({sessionCleanupOnNodeRemove:D.target.value}),disabled:y,children:zr.map(D=>s.jsx("option",{value:D.value,children:D.label},D.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((ie=zr.find(D=>D.value===fe.sessionCleanupOnNodeRemove))==null?void 0:ie.description)||zr[0].description})]}),y&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving policy..."})]}),s.jsxs(yt,{title:"Visualization",description:"Live mesh topology: branches, worktrees, sessions, and orphan detection.",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500"}),"healthy"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-amber-500"}),"dirty"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-red-500"}),"error"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-gray-500"}),"offline"]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:ge,disabled:K,children:K?"Loading...":"Refresh Graph"})]}),T&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:T}),w?s.jsxs("div",{className:"flex gap-4",style:{minHeight:420},children:[s.jsx("div",{className:"flex-1 rounded-xl border border-border-subtle bg-bg-secondary overflow-hidden",style:{minHeight:420},children:s.jsx(k0,{data:w,onNodeClick:D=>R(z=>(z==null?void 0:z.id)===D.id?null:D),selectedNodeId:(H==null?void 0:H.id)||null})}),H&&s.jsx("div",{className:"w-80 shrink-0",children:s.jsx(N0,{node:H,onClose:()=>R(null)})})]}):s.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:K?"Loading graph...":"Refresh the graph to view mesh topology."})]}),s.jsxs(yt,{title:"Nodes",description:"Workspaces participating in this mesh.",children:[s.jsx("div",{className:"flex justify-end mb-3",children:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>xe(!0),children:"+ Add Node"})}),Q&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:"Add Node"}),s.jsx("button",{onClick:()=>xe(!1),className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(vt,{size:16})})]}),s.jsx(Mt,{label:"Workspace Path",children:s.jsx(Jn,{value:de,onChange:D=>Z(D.target.value),placeholder:"/Users/dev/projects/myapp",autoFocus:!0})}),s.jsx(Mt,{label:"Provider Priority",hint:"Order used when launching without an explicit provider. Empty means fail closed unless a provider is selected explicitly.",children:s.jsx(Ti,{value:he,availableProviders:o,onChange:we})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:Ne,disabled:!de.trim(),className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>xe(!1),className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),be.nodes.length===0?s.jsx(hn,{icon:s.jsx(xs,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:be.nodes.map(D=>{const z=tn(D),ce=I0(D),se=T0(D,S),q=A0(D,r),ke=M===D.id;return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary cursor-pointer transition-colors ${ke?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`,role:"button",tabIndex:0,onClick:()=>A(ke?null:D.id),onKeyDown:ve=>{(ve.key==="Enter"||ve.key===" ")&&(ve.preventDefault(),A(ke?null:D.id))},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"text-sm font-medium",children:D.workspace.split("/").pop()}),se.length>0&&s.jsxs("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-orange-500/15 text-orange-300 border border-orange-500/25",children:[se.length," active task",se.length===1?"":"s"]})]}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:D.workspace}),s.jsx("div",{className:"mt-3 max-w-2xl",onClick:ve=>ve.stopPropagation(),children:s.jsxs(Mt,{label:"Provider priority",hint:"Used when launches omit an explicit provider. Empty keeps fail-closed behavior until a provider is selected manually.",children:[s.jsx(Ti,{value:f[D.id]??z,availableProviders:o,onChange:ve=>N(Le=>({...Le,[D.id]:ve})),disabled:x===D.id,saveButton:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:ve=>{ve.stopPropagation(),oe(D)},disabled:x===D.id,children:x===D.id?"Saving...":"Save policy"})}),s.jsxs("div",{className:"mt-2 text-[12px]",children:[s.jsx("span",{className:"text-text-muted",children:"Effective provider priority: "}),s.jsx("span",{className:ce.configured?"text-text-primary font-mono":"text-amber-400",children:ce.label}),ce.launchBlockedMessage&&s.jsxs("span",{className:"ml-2 text-amber-400",children:["(",ce.launchBlockedMessage,")"]})]})]})})]}),s.jsx("button",{className:"text-text-muted hover:text-red-400 transition-colors bg-transparent border-none cursor-pointer",onClick:ve=>{ve.stopPropagation(),me(D.id)},children:s.jsx(vt,{size:14})})]}),ke&&s.jsxs("div",{className:"mt-3 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-[12px] text-text-muted",children:[s.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Node ID:"})," ",s.jsx("span",{className:"font-mono",children:D.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Launch ready:"})," ",s.jsx("span",{className:ce.configured?"text-green-400":"text-amber-400",children:ce.configured?"yes":"provider priority not configured"})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Repo root:"})," ",s.jsx("span",{className:"font-mono",children:D.repoRoot||D.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Active sessions:"})," ",q.length]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Branch / git:"})," not loaded in standalone list view"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Health:"})," ",se.length>0||q.length>0?"active":"idle/unknown"]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active queue assignments"}),se.length===0?s.jsx("div",{children:"No active assigned queue task for this node."}):s.jsx("ul",{className:"m-0 pl-4",children:se.map(ve=>s.jsx("li",{className:"font-mono",children:M0(ve)},ve.id))})]}),q.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active sessions"}),s.jsx("ul",{className:"m-0 pl-4",children:q.map(ve=>s.jsxs("li",{className:"font-mono",children:[ve.provider," / ",ve.status," / ",ve.id]},ve.id))})]})]})]},D.id)})})]}),s.jsx(L0,{meshId:be.id,availableCliAgents:a})]})}function P0(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function _0(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function D0(e,t){const r=[],n=e.git;return n?n.isGitRepo?(n.branch===null&&n.headCommit&&r.push("Detached HEAD"),n.branch&&n.upstream,n.branch&&n.upstream,e.error&&r.push(`Error: ${e.error}`),r):(r.push("Not a git repository"),r):(r.push("No git status available"),r)}function mc(e){switch(e){case"online":return 0;case"dirty":return 1;case"degraded":return 2;case"wrong_branch":return 3;case"offline":return 4;case"unknown":return 5;default:return 5}}function E0(e){return e.length===0?"unknown":e.reduce((t,r)=>mc(r)>mc(t)?r:t)}function $0(e){var k,y,p;const t=[],r=[],n=[],a=new Map;for(const x of e.nodes){const g=x.git,f=(g==null?void 0:g.branch)||null,N=D0(x,null),S=P0(g),v=_0(g);let M="worktreeNode";N.length>0&&(M="orphanNode");const A={id:x.nodeId,type:M,label:x.machineLabel||x.nodeId.slice(0,8),workspace:x.workspace,branch:f,health:x.health,ahead:(g==null?void 0:g.ahead)??0,behind:(g==null?void 0:g.behind)??0,dirty:S,dirtyFiles:v,hasConflicts:(g==null?void 0:g.hasConflicts)??!1,activeSessionCount:((k=x.activeSessions)==null?void 0:k.length)??0,activeSessions:x.activeSessions??[],providers:x.providers??[],isOrphan:N.length>0,orphanReasons:N,source:x};if(t.push(A),f){const w=a.get(f)??[];w.push(A.id),a.set(f,w)}}const o=new Map;for(const x of e.nodes){const g=(y=x.git)==null?void 0:y.branch,f=(p=x.git)==null?void 0:p.upstream;g&&f&&o.set(g,(o.get(g)??0)+1)}let c=null,l=0;for(const[x,g]of o)g>l&&(l=g,c=x);const d=c?`__branch_${c}`:null;if(d&&c){const x=a.get(c)??[],g=x.map(S=>t.find(v=>v.id===S).health),f={id:d,type:"defaultBranchNode",label:c,workspace:"",branch:c,health:E0(g),ahead:0,behind:0,dirty:!1,dirtyFiles:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],providers:[],isOrphan:!1,orphanReasons:[],nextStepHint:x.length>0?`${x.length} node(s) on default branch`:void 0,source:{nodeId:d,machineLabel:c,workspace:"",health:"online",providers:[],activeSessions:[]}};t.push(f);const N=new Set;for(const S of t)if(S.type!=="defaultBranchNode"&&S.branch){if(S.branch===c){r.push({id:`${d}--${S.id}`,source:d,target:S.id,type:"parentBranch",label:"default"});continue}N.has(S.branch)||(N.add(S.branch),r.push({id:`${d}--branch_${S.branch}`,source:d,target:S.branch,type:"parentBranch",label:S.branch}))}}for(const[x,g]of a)if(!(g.length<2))for(let f=1;f<g.length;f++)r.push({id:`wt_${g[0]}--${g[f]}`,source:g[0],target:g[f],type:"worktreeLink",label:x});const m=t.filter(x=>x.isOrphan).length;m>0&&n.push(`${m} orphan node(s) detected`);const u=t.filter(x=>x.hasConflicts).length;u>0&&n.push(`${u} node(s) with merge conflicts`);const h=t.filter(x=>x.health==="offline").length;h>0&&n.push(`${h} node(s) offline`);const b={totalNodes:e.nodes.length,onlineNodes:e.nodes.filter(x=>x.health==="online").length,dirtyNodes:t.filter(x=>x.dirty).length,orphanNodes:m,errorNodes:e.nodes.filter(x=>!!x.error).length,offlineNodes:h,totalActiveSessions:e.nodes.reduce((x,g)=>{var f;return x+(((f=g.activeSessions)==null?void 0:f.length)??0)},0)};return{meshId:e.meshId,meshName:e.meshName,repoIdentity:e.repoIdentity,refreshedAt:e.refreshedAt,nodes:t,edges:r,stats:b,warnings:n}}function Wo(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function B0(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=Wo();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 $t(e,t){return await fetch(B0(e),{credentials:"same-origin",...t})}function Ad(){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 K0{constructor(){Je(this,"adapters",new Map);Je(this,"states",new Map);Je(this,"runtimeListeners",new Map);Je(this,"screenshotCallbacks",new Map);Je(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 $t(`${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 Wt=new K0;function O0(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=Wo();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Vr=O0(),fc=3e3,W0=3e4;let _t=null,F0=0;const vn=new Map;let ns=null,fr=null;function pc(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function sr(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function H0(e){return e==="connected"?"connected":e}async function sn(e,t,r){const n=Il(e,r||{}),a=_t;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++F0}_${Date.now()}`;return new Promise((c,l)=>{const d=setTimeout(()=>{vn.delete(o),l(new Error(`WS command timeout: ${t}`))},3e4);vn.set(o,{resolve:m=>{clearTimeout(d),c(m)},reject:m=>{clearTimeout(d),l(m)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Ya(e,t){const r=_t;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 U0(e,t,r){const n=_t;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=Il(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 z0{constructor(t){Je(this,"daemonId");Je(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(_t==null?void 0:_t.readyState)===WebSocket.OPEN}get connectionState(){return(_t==null?void 0:_t.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return sn(this.daemonId,t,r)}async sendInput(t,r){return sn(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,ns&&(clearInterval(ns),ns=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await sn(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());Wt.emitScreenshot(this.daemonId,a)}}catch{}};r(),ns=setInterval(r,2e3)}stopScreenshots(t){ns&&(clearInterval(ns),ns=null)}}let Lt=null;function V0(e){return(!Lt||Lt.daemonId!==e)&&(Lt=new z0(e)),Lt}function G0({children:e}){const t=i.useRef(hr()),r=hr();t.current=r;const{setUserName:n}=es(),a=i.useRef(n);a.current=n;const o=i.useRef(null),c=i.useRef(null),[,l]=i.useState("disconnected"),d=i.useCallback((p,x)=>{l(p),fr==null||fr(p,x)},[]),m=i.useRef(null),u=i.useRef(),h=i.useRef(fc),b=i.useRef(!0),k=i.useRef(!1),y=i.useRef("initial_connect");return i.useEffect(()=>{b.current=!0,k.current=!1;function p(){var f,N;if(!b.current||((f=m.current)==null?void 0:f.readyState)===WebSocket.OPEN||((N=m.current)==null?void 0:N.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Vr}...`),sr("connect_attempt",{url:Vr,reason:y.current,delayMs:h.current});let g;try{g=new WebSocket(Vr)}catch(S){console.error("[Standalone WS] Failed to create WebSocket:",S),x();return}m.current=g,g.onopen=()=>{if(!b.current){g.close();return}d("connected"),h.current=fc,sr("open",{url:Vr,reason:y.current}),Ut.resubscribeAll({sendData:Ya}),console.log("[Standalone WS] Connected")},_t=g,g.onmessage=S=>{var v,M;try{const A=JSON.parse(S.data);if((A.type==="command_result"||A.type==="error")&&A.requestId){const w=vn.get(A.requestId);w&&(vn.delete(A.requestId),A.type==="error"?w.reject(new Error(((v=A.data)==null?void 0:v.message)||"Command failed")):w.resolve(A.data));return}if(A.type==="session_output"){const w=A.sessionId||A.cliId||A.cliType;w&&Wt.emitSessionOutput(w,typeof A.data=="string"?A.data:"",typeof A.seq=="number"?A.seq:void 0);return}if(A.type==="runtime_snapshot"){Wt.emitRuntimeSnapshot(A.sessionId,typeof A.text=="string"?A.text:"",typeof A.seq=="number"?A.seq:0,!!A.truncated,typeof A.cols=="number"?A.cols:void 0,typeof A.rows=="number"?A.rows:void 0);return}if(A.type==="topic_update"){const w=A.update;w&&Ut.publish(w);return}if(A.type==="status"||A.type==="initial_state"){const w=A.data;if(!w)return;const{injectEntries:j,markLoaded:K,getIdes:P}=t.current,T=w.instanceId||"standalone",W=P().find(I=>I.id===T),H=V0(T);Wt.register(T,H),Wt.setState(T,"connected"),d("connected",T),Wt.emitStatus(T,w);const R=fn(w,{daemonId:T,existingDaemon:W,existingEntries:P()});pc("ws_status",{type:A.type,daemonId:T,sessions:(w.sessions||[]).map(I=>({id:I.id,parentId:I.parentId,providerType:I.providerType,kind:I.kind,transport:I.transport,unread:I.unread,inboxBucket:I.inboxBucket,lastSeenAt:I.lastSeenAt,lastUpdated:I.lastUpdated,title:I.title})),recentLaunches:(w.recentLaunches||[]).map(I=>({id:I.id,providerType:I.providerType,kind:I.kind,workspace:I.workspace,lastLaunchedAt:I.lastLaunchedAt}))}),pc("entries",{daemonId:T,entries:R.filter(I=>I.type!=="adhdev-daemon").map(I=>({id:I.id,type:I.type,unread:I.unread,inboxBucket:I.inboxBucket,lastSeenAt:I.lastSeenAt,lastUpdated:I.lastUpdated,sessionId:I.sessionId}))}),R.length>0&&j(R,{authoritativeDaemonIds:[T]}),K(),c.current!==T&&((M=o.current)==null||M.call(o),c.current=T,o.current=Ut.subscribe({sendData:Ya},T,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${T}`,params:{includeSessions:!0}},I=>{if(I.topic!=="daemon.metadata")return;const C=t.current.getIdes(),O=C.find(E=>E.id===T),_=fn(I.status,{daemonId:T,existingDaemon:O,existingEntries:C,timestamp:I.timestamp});_.length>0&&t.current.injectEntries(_,{authoritativeDaemonIds:[T]}),I.userName&&a.current&&a.current(I.userName)}))}}catch(A){console.error("[Standalone WS] Parse error:",A)}},g.onclose=S=>{b.current&&(Lt==null||Lt.stopScreenshots(),Lt&&Wt.setState(Lt.daemonId,"disconnected"),d("disconnected"),m.current=null,y.current=`close:${S.code}${S.wasClean?":clean":":unclean"}`,sr("close",{code:S.code,reason:S.reason||"",wasClean:S.wasClean}),x())},g.onerror=S=>{k.current||!b.current||(y.current="error",sr("error",{message:S instanceof Event?"event":String(S),readyState:g.readyState}),console.warn("[Standalone WS] Error, will reconnect:",S))}}function x(){if(!b.current)return;clearTimeout(u.current);const g=h.current;console.log(`[Standalone WS] Reconnecting in ${g}ms...`),sr("schedule_reconnect",{reason:y.current,delayMs:g}),u.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,W0),p()},g)}return p(),()=>{var g;b.current=!1,k.current=!0,(g=o.current)==null||g.call(o),o.current=null,c.current=null,clearTimeout(u.current),m.current&&(m.current.onerror=null,m.current.onclose=null,m.current.close(),m.current=null,_t=null),Lt&&(Lt.stopScreenshots(),Wt.unregister(Lt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function q0({children:e}){const[t,r]=i.useState("disconnected"),[n,a]=i.useState(null);i.useEffect(()=>(fr=(c,l)=>{r(c),l&&a(l)},()=>{fr=null}),[]);const o=i.useMemo(()=>{const c=t==="connected",l=H0(t),d={};return n&&(d[n]=l),d.standalone=l,{wsStatus:t,isConnected:c,connectionStates:d}},[t,n]);return s.jsx(Tu,{connectionOverrides:o,children:s.jsx(G0,{children:e})})}const Ld="adhdev_standalone_font_preferences",hs={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},En=[{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"}],gr=[{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"}],Y0=new Set(En.map(e=>e.id)),X0=new Set(gr.map(e=>e.id));function Kt(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:rn("chat",t.chat),code:rn("code",t.code),terminal:rn("terminal",t.terminal)}}function rn(e,t){const r=hs[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"?Y0:X0).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function nn(e,t){var a;const r=rn(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?En:gr;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function J0(e){const t=Kt(e),r=nn("chat",t.chat),n=nn("code",t.code),a=nn("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function os(e,t=document.documentElement){const r=Kt(e),n=J0(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function Xa(e){const t=Kt(e);try{localStorage.setItem(Ld,JSON.stringify(t))}catch{}return t}function Q0(){try{const e=localStorage.getItem(Ld);if(e)return Kt(JSON.parse(e))}catch{}return hs}function Z0(){return os(Q0())}function rr(e,t){var n;const r=e==="chat"?En:gr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const ev=[{id:"dashboard",path:"/dashboard",icon:s.jsx(Sc,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(Jt,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(_s,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx(wn,{}),label:"Settings"}];function tv({children:e}){const t=Ws(),r=Qa(),n=i.useMemo(()=>ev.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(Cc,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Ic,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(Fh,{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.79"]}),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 sv=[{icon:s.jsx(Jt,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(zt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Tc,{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(_s,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Cc,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],rv=[{icon:s.jsx(zu,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Sc,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(jn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Bu,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Nc,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Ou,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],nv=[{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 av(){return s.jsxs(dr,{icon:s.jsx(Ic,{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.79"]}),children:[s.jsx(yt,{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(yt,{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:sv.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(yt,{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:Tl.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Al.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Ml.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(yt,{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:rv.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(yt,{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:nv.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(hn,{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(tm,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Sa(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:nn(e,n)})]})]})]})}function ov({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:o,onSave:c,onResetToSaved:l,onResetToDefaults:d}){const m=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:En,onChange:u=>o(Sa(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:gr,onChange:u=>o(Sa(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:gr,onChange:u=>o(Sa(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: ",rr("chat",e.chat.preset)," · Code: ",rr("code",e.code.preset)," · Terminal: ",rr("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",rr("chat",hs.chat.preset)," / ",rr("code",hs.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||!m,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||!m,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 iv(){const{ides:e}=es(),t=e.find(X=>X.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=gt(),{userName:a}=es(),[o,c]=i.useState(a||""),[l,d]=i.useState(null),[m,u]=i.useState(null),[h,b]=i.useState(hs),[k,y]=i.useState(!1),[p,x]=i.useState(""),[g,f]=i.useState(""),[N,S]=i.useState("127.0.0.1"),[v,M]=i.useState(""),[A,w]=i.useState(""),[j,K]=i.useState(""),[P,T]=i.useState(""),[W,H]=i.useState(""),[R,I]=i.useState(!1),C=async()=>{const ue=await(await $t("/auth/session")).json();d(ue)},O=async()=>{const ue=await(await $t("/api/v1/standalone/preferences")).json();u(ue),S(ue.standaloneBindHost);const ge=Kt(ue.standaloneFontPreferences);b(ge),os(ge),Xa(ge)};i.useEffect(()=>{a!==void 0&&c(a)},[a]),i.useEffect(()=>{Promise.all([C(),O()]).catch(X=>{T(X instanceof Error?X.message:String(X))})},[]),i.useEffect(()=>{os(h)},[h]);const _=X=>{const ue=X.target.value.trim();t!=null&&t.id&&ue!==a&&n(t.id,"set_user_name",{userName:ue}).catch(console.error)},[E,U]=i.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),Q=X=>{U(X);try{localStorage.setItem("adhdev_sound",X?"1":"0")}catch{}},xe=async()=>{x(""),f(""),y(!0);try{const X=Kt(h),ue=await $t("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:X})}),ge=await ue.json();if(!ue.ok)throw new Error((ge==null?void 0:ge.error)||"Failed to save standalone font preferences");const te=Kt(ge.standaloneFontPreferences);u(ge),b(te),os(te),Xa(te),f("Standalone chat fonts saved for this self-hosted dashboard.")}catch(X){x(X instanceof Error?X.message:String(X))}finally{y(!1)}},de=()=>{const X=Kt(m==null?void 0:m.standaloneFontPreferences);x(""),f(""),b(X),os(X)},Z=()=>{x(""),f(""),b(hs),os(hs)},he=async()=>{T(""),H(""),I(!0);try{const X=await $t("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:N})}),ue=await X.json();if(!X.ok)throw new Error((ue==null?void 0:ue.error)||"Failed to save standalone network preference");u(ue),S(ue.standaloneBindHost),H(ue.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){T(X instanceof Error?X.message:String(X))}finally{I(!1)}},we=async()=>{if(T(""),H(""),A.trim().length<4){T("Password must be at least 4 characters.");return}if(A!==j){T("New password and confirmation do not match.");return}I(!0);try{const X=await $t("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,newPassword:A})}),ue=await X.json();if(!X.ok)throw new Error((ue==null?void 0:ue.error)||"Failed to save password");d(ue),await O(),M(""),w(""),K(""),H(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Ad()}catch(X){T(X instanceof Error?X.message:String(X))}finally{I(!1)}},be=async()=>{T(""),H(""),I(!0);try{const X=await $t("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,clear:!0})}),ue=await X.json();if(!X.ok)throw new Error((ue==null?void 0:ue.error)||"Failed to clear password");d(ue),await O(),M(""),w(""),K(""),H("Standalone password disabled.")}catch(X){T(X instanceof Error?X.message:String(X))}finally{I(!1)}};return s.jsxs(dr,{icon:s.jsx(wn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(Ts,{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(Ts,{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(yt,{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.79"]}),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:(m==null?void 0:m.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:(m==null?void 0:m.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(yt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:N==="127.0.0.1",onChange:()=>S("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 127.0.0.1. Best when only this machine should open the dashboard."})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:N==="0.0.0.0",onChange:()=>S("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:()=>{he()},disabled:R,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 default network mode"}),s.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(m==null?void 0:m.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),s.jsx(yt,{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."}),P&&s.jsx(Ts,{variant:"error",children:P}),W&&s.jsx(Ts,{variant:"success",children:W}),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:v,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:A,onChange:X=>w(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:j,onChange:X=>K(X.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{we()},disabled:R,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…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{be()},disabled:R,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(yt,{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(yt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(Jh,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(yt,{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(tx,{})]}),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(lx,{})]}),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(ov,{value:h,savedValue:Kt(m==null?void 0:m.standaloneFontPreferences),saving:k,error:p,notice:g,onChange:b,onSave:()=>{xe()},onResetToSaved:de,onResetToDefaults:Z})]}),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(mx,{})]})]})}),s.jsx(yt,{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(qh,{}),s.jsx(as,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(em,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:E,onChange:Q})]})}),s.jsx(yt,{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($u,{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:_,onKeyDown:X=>{X.key==="Enter"&&X.currentTarget.blur()}})]})})})]})}Oh();ix();Z0();const cv=jc({baseUrl:"",getToken:Wo});function lv({children:e}){const[t,r]=i.useState(null),[n,a]=i.useState(!0),[o,c]=i.useState(""),[l,d]=i.useState(""),[m,u]=i.useState(!1),h=async()=>{a(!0),d("");try{const y=await(await $t("/auth/session")).json();r(y)}catch(k){d(k instanceof Error?k.message:String(k))}finally{a(!1)}};i.useEffect(()=>{h()},[]),i.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let k=!1;return(async()=>{try{const y=await $t("/api/v1/standalone/preferences");if(!y.ok)return;const p=await y.json();if(k)return;const x=Kt(p.standaloneFontPreferences);os(x),Xa(x)}catch{}})(),()=>{k=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const b=async k=>{k.preventDefault(),u(!0),d("");try{const y=await $t("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),p=await y.json();if(!y.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),c(""),Ad()}catch(y){d(y instanceof Error?y.message:String(y))}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:b,children:[s.jsx("input",{type:"password",value:o,onChange:k=>c(k.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),s.jsx("button",{type:"submit",disabled:m||!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:m?"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 hc(){const{ides:e,initialLoaded:t}=es();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(Ta,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Ta,{to:"/dashboard",replace:!0})}function dv(){const e=i.useMemo(()=>({sendCommand:sn,sendData:Ya,sendPtyInput:U0}),[]);return s.jsx(mu,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Lu,{client:cv,children:s.jsx(lv,{children:s.jsx(q0,{children:s.jsx(Pu,{value:e,children:s.jsx(tv,{children:s.jsxs(fu,{children:[s.jsx(qt,{path:"/dashboard",element:s.jsx(fy,{})}),s.jsx(qt,{path:"/machine",element:s.jsx(hc,{})}),s.jsx(qt,{path:"/machines/:id",element:s.jsx(y0,{})}),s.jsx(qt,{path:"/machines",element:s.jsx(hc,{})}),s.jsx(qt,{path:"/about",element:s.jsx(av,{})}),s.jsx(qt,{path:"/settings",element:s.jsx(iv,{})}),s.jsx(qt,{path:"/mesh",element:s.jsx(R0,{})}),s.jsx(qt,{path:"*",element:s.jsx(Ta,{to:"/dashboard",replace:!0})})]})})})})})})})}Xp({connectionManager:Wt});pu(document.getElementById("root")).render(s.jsx(dv,{}));
98
+ Node removal cleanup policy: ${ce}`))try{await e(n,"remove_mesh_node",{meshId:d,nodeId:D}),M===D&&A(null),await X(),await ue(d)}catch(q){k((q==null?void 0:q.message)||"Remove node failed")}}async function pe(D){if(!n||!d)return;const z={...ka(be),...D};try{p(!0),k(null);const ce=await e(n,"update_mesh",{meshId:d,policy:z});if((ce==null?void 0:ce.success)===!1){k(ce.error||"Policy update failed");return}await X()}catch(ce){k((ce==null?void 0:ce.message)||"Policy update failed")}finally{p(!1)}}async function oe(D){if(!n||!d)return;const z=Ka(f[D.id]||tn(D),o),ce={...D.policy||{}};delete ce.provider_priority,z.length?ce.providerPriority=z:delete ce.providerPriority;try{g(D.id),k(null);const se=await e(n,"update_mesh_node",{meshId:d,nodeId:D.id,policy:ce});if((se==null?void 0:se.success)===!1){k(se.error||"Node policy update failed");return}await X()}catch(se){k((se==null?void 0:se.message)||"Node policy update failed")}finally{g(null)}}if(!n)return s.jsx(dr,{icon:s.jsx(Ar,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})});if(!be)return s.jsxs(dr,{icon:s.jsx(Ar,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>C(!0),children:"+ Create Mesh"}),children:[b&&s.jsx(Ts,{variant:"error",className:"mb-4",children:b}),I&&s.jsx(yt,{title:"New Mesh",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Mt,{label:"Name",children:s.jsx(Jn,{value:O,onChange:D=>_(D.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(Mt,{label:"Repo Identity (optional)",children:s.jsx(Jn,{value:E,onChange:D=>U(D.target.value),placeholder:"github.com/user/repo"})}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:te,disabled:!O.trim(),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>C(!1),children:"Cancel"})]})]})}),u?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):c.length===0?s.jsx(hn,{icon:s.jsx(Ar,{}),title:"No meshes",description:"Create a mesh to get started."}):s.jsx("div",{className:"flex flex-col gap-2",children:c.map(D=>s.jsxs("button",{className:"text-left w-full p-4 rounded-xl border border-border-subtle bg-bg-panel hover:border-accent-primary/40 transition-colors",onClick:()=>m(D.id),children:[s.jsx("div",{className:"font-semibold text-sm",children:D.name}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5 font-mono",children:D.repoIdentity||"No repo identity"}),s.jsxs("div",{className:"text-[10px] text-text-muted mt-1",children:[D.nodes.length," node(s)"]})]},D.id))})]});const fe=ka(be);return s.jsxs(dr,{icon:s.jsx(Ar,{}),title:be.name,subtitle:be.repoIdentity||"Repo Mesh",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>m(null),children:"← Back"}),s.jsx("button",{className:"btn btn-sm",style:{color:"var(--color-red-400)"},onClick:()=>le(be.id),children:"Delete"})]}),children:[b&&s.jsx(Ts,{variant:"error",className:"mb-4",children:b}),s.jsxs(yt,{title:"Policy",description:"Coordinator safety defaults and node-removal session cleanup behavior for this local mesh.",children:[s.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[s.jsx(Mt,{label:"Checkpoint before task",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:fe.requirePreTaskCheckpoint?"yes":"no",onChange:D=>pe({requirePreTaskCheckpoint:D.target.value==="yes"}),disabled:y,children:[s.jsx("option",{value:"no",children:"No"}),s.jsx("option",{value:"yes",children:"Yes"})]})}),s.jsx(Mt,{label:"Checkpoint after task",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:fe.requirePostTaskCheckpoint?"yes":"no",onChange:D=>pe({requirePostTaskCheckpoint:D.target.value==="yes"}),disabled:y,children:[s.jsx("option",{value:"yes",children:"Yes"}),s.jsx("option",{value:"no",children:"No"})]})}),s.jsx(Mt,{label:"Push approval",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:fe.requireApprovalForPush?"required":"not_required",onChange:D=>pe({requireApprovalForPush:D.target.value==="required"}),disabled:y,children:[s.jsx("option",{value:"required",children:"Require approval before push"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(Mt,{label:"Destructive git approval",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:fe.requireApprovalForDestructiveGit?"required":"not_required",onChange:D=>pe({requireApprovalForDestructiveGit:D.target.value==="required"}),disabled:y,children:[s.jsx("option",{value:"required",children:"Require approval"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(Mt,{label:"Dirty workspace behavior",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:fe.dirtyWorkspaceBehavior||"warn",onChange:D=>pe({dirtyWorkspaceBehavior:D.target.value}),disabled:y,children:[s.jsx("option",{value:"warn",children:"Warn and continue"}),s.jsx("option",{value:"block",children:"Block task"}),s.jsx("option",{value:"checkpoint_then_continue",children:"Checkpoint then continue"})]})}),s.jsx(Mt,{label:"Max parallel tasks",children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:String(fe.maxParallelTasks??2),onChange:D=>pe({maxParallelTasks:Number(D.target.value)}),disabled:y,children:[1,2,3,4,5,6,7,8].map(D=>s.jsx("option",{value:D,children:D},D))})})]}),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(Mt,{label:"Node removal session cleanup",hint:"Separate transcript cleanup from runtime/process cleanup. Preserve is safest when completed work may need review.",children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:fe.sessionCleanupOnNodeRemove||"preserve",onChange:D=>pe({sessionCleanupOnNodeRemove:D.target.value}),disabled:y,children:zr.map(D=>s.jsx("option",{value:D.value,children:D.label},D.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((ie=zr.find(D=>D.value===fe.sessionCleanupOnNodeRemove))==null?void 0:ie.description)||zr[0].description})]}),y&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving policy..."})]}),s.jsxs(yt,{title:"Visualization",description:"Live mesh topology: branches, worktrees, sessions, and orphan detection.",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500"}),"healthy"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-amber-500"}),"dirty"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-red-500"}),"error"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-gray-500"}),"offline"]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:ge,disabled:K,children:K?"Loading...":"Refresh Graph"})]}),T&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:T}),w?s.jsxs("div",{className:"flex gap-4",style:{minHeight:420},children:[s.jsx("div",{className:"flex-1 rounded-xl border border-border-subtle bg-bg-secondary overflow-hidden",style:{minHeight:420},children:s.jsx(k0,{data:w,onNodeClick:D=>R(z=>(z==null?void 0:z.id)===D.id?null:D),selectedNodeId:(H==null?void 0:H.id)||null})}),H&&s.jsx("div",{className:"w-80 shrink-0",children:s.jsx(N0,{node:H,onClose:()=>R(null)})})]}):s.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:K?"Loading graph...":"Refresh the graph to view mesh topology."})]}),s.jsxs(yt,{title:"Nodes",description:"Workspaces participating in this mesh.",children:[s.jsx("div",{className:"flex justify-end mb-3",children:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>xe(!0),children:"+ Add Node"})}),Q&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:"Add Node"}),s.jsx("button",{onClick:()=>xe(!1),className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(vt,{size:16})})]}),s.jsx(Mt,{label:"Workspace Path",children:s.jsx(Jn,{value:de,onChange:D=>Z(D.target.value),placeholder:"/Users/dev/projects/myapp",autoFocus:!0})}),s.jsx(Mt,{label:"Provider Priority",hint:"Order used when launching without an explicit provider. Empty means fail closed unless a provider is selected explicitly.",children:s.jsx(Ti,{value:he,availableProviders:o,onChange:we})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:Ne,disabled:!de.trim(),className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>xe(!1),className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),be.nodes.length===0?s.jsx(hn,{icon:s.jsx(xs,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:be.nodes.map(D=>{const z=tn(D),ce=I0(D),se=T0(D,S),q=A0(D,r),ke=M===D.id;return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary cursor-pointer transition-colors ${ke?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`,role:"button",tabIndex:0,onClick:()=>A(ke?null:D.id),onKeyDown:ve=>{(ve.key==="Enter"||ve.key===" ")&&(ve.preventDefault(),A(ke?null:D.id))},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"text-sm font-medium",children:D.workspace.split("/").pop()}),se.length>0&&s.jsxs("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-orange-500/15 text-orange-300 border border-orange-500/25",children:[se.length," active task",se.length===1?"":"s"]})]}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:D.workspace}),s.jsx("div",{className:"mt-3 max-w-2xl",onClick:ve=>ve.stopPropagation(),children:s.jsxs(Mt,{label:"Provider priority",hint:"Used when launches omit an explicit provider. Empty keeps fail-closed behavior until a provider is selected manually.",children:[s.jsx(Ti,{value:f[D.id]??z,availableProviders:o,onChange:ve=>N(Le=>({...Le,[D.id]:ve})),disabled:x===D.id,saveButton:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:ve=>{ve.stopPropagation(),oe(D)},disabled:x===D.id,children:x===D.id?"Saving...":"Save policy"})}),s.jsxs("div",{className:"mt-2 text-[12px]",children:[s.jsx("span",{className:"text-text-muted",children:"Effective provider priority: "}),s.jsx("span",{className:ce.configured?"text-text-primary font-mono":"text-amber-400",children:ce.label}),ce.launchBlockedMessage&&s.jsxs("span",{className:"ml-2 text-amber-400",children:["(",ce.launchBlockedMessage,")"]})]})]})})]}),s.jsx("button",{className:"text-text-muted hover:text-red-400 transition-colors bg-transparent border-none cursor-pointer",onClick:ve=>{ve.stopPropagation(),me(D.id)},children:s.jsx(vt,{size:14})})]}),ke&&s.jsxs("div",{className:"mt-3 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-[12px] text-text-muted",children:[s.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Node ID:"})," ",s.jsx("span",{className:"font-mono",children:D.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Launch ready:"})," ",s.jsx("span",{className:ce.configured?"text-green-400":"text-amber-400",children:ce.configured?"yes":"provider priority not configured"})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Repo root:"})," ",s.jsx("span",{className:"font-mono",children:D.repoRoot||D.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Active sessions:"})," ",q.length]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Branch / git:"})," not loaded in standalone list view"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Health:"})," ",se.length>0||q.length>0?"active":"idle/unknown"]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active queue assignments"}),se.length===0?s.jsx("div",{children:"No active assigned queue task for this node."}):s.jsx("ul",{className:"m-0 pl-4",children:se.map(ve=>s.jsx("li",{className:"font-mono",children:M0(ve)},ve.id))})]}),q.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active sessions"}),s.jsx("ul",{className:"m-0 pl-4",children:q.map(ve=>s.jsxs("li",{className:"font-mono",children:[ve.provider," / ",ve.status," / ",ve.id]},ve.id))})]})]})]},D.id)})})]}),s.jsx(L0,{meshId:be.id,availableCliAgents:a})]})}function P0(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function _0(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function D0(e,t){const r=[],n=e.git;return n?n.isGitRepo?(n.branch===null&&n.headCommit&&r.push("Detached HEAD"),n.branch&&n.upstream,n.branch&&n.upstream,e.error&&r.push(`Error: ${e.error}`),r):(r.push("Not a git repository"),r):(r.push("No git status available"),r)}function mc(e){switch(e){case"online":return 0;case"dirty":return 1;case"degraded":return 2;case"wrong_branch":return 3;case"offline":return 4;case"unknown":return 5;default:return 5}}function E0(e){return e.length===0?"unknown":e.reduce((t,r)=>mc(r)>mc(t)?r:t)}function $0(e){var k,y,p;const t=[],r=[],n=[],a=new Map;for(const x of e.nodes){const g=x.git,f=(g==null?void 0:g.branch)||null,N=D0(x,null),S=P0(g),v=_0(g);let M="worktreeNode";N.length>0&&(M="orphanNode");const A={id:x.nodeId,type:M,label:x.machineLabel||x.nodeId.slice(0,8),workspace:x.workspace,branch:f,health:x.health,ahead:(g==null?void 0:g.ahead)??0,behind:(g==null?void 0:g.behind)??0,dirty:S,dirtyFiles:v,hasConflicts:(g==null?void 0:g.hasConflicts)??!1,activeSessionCount:((k=x.activeSessions)==null?void 0:k.length)??0,activeSessions:x.activeSessions??[],providers:x.providers??[],isOrphan:N.length>0,orphanReasons:N,source:x};if(t.push(A),f){const w=a.get(f)??[];w.push(A.id),a.set(f,w)}}const o=new Map;for(const x of e.nodes){const g=(y=x.git)==null?void 0:y.branch,f=(p=x.git)==null?void 0:p.upstream;g&&f&&o.set(g,(o.get(g)??0)+1)}let c=null,l=0;for(const[x,g]of o)g>l&&(l=g,c=x);const d=c?`__branch_${c}`:null;if(d&&c){const x=a.get(c)??[],g=x.map(S=>t.find(v=>v.id===S).health),f={id:d,type:"defaultBranchNode",label:c,workspace:"",branch:c,health:E0(g),ahead:0,behind:0,dirty:!1,dirtyFiles:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],providers:[],isOrphan:!1,orphanReasons:[],nextStepHint:x.length>0?`${x.length} node(s) on default branch`:void 0,source:{nodeId:d,machineLabel:c,workspace:"",health:"online",providers:[],activeSessions:[]}};t.push(f);const N=new Set;for(const S of t)if(S.type!=="defaultBranchNode"&&S.branch){if(S.branch===c){r.push({id:`${d}--${S.id}`,source:d,target:S.id,type:"parentBranch",label:"default"});continue}N.has(S.branch)||(N.add(S.branch),r.push({id:`${d}--branch_${S.branch}`,source:d,target:S.branch,type:"parentBranch",label:S.branch}))}}for(const[x,g]of a)if(!(g.length<2))for(let f=1;f<g.length;f++)r.push({id:`wt_${g[0]}--${g[f]}`,source:g[0],target:g[f],type:"worktreeLink",label:x});const m=t.filter(x=>x.isOrphan).length;m>0&&n.push(`${m} orphan node(s) detected`);const u=t.filter(x=>x.hasConflicts).length;u>0&&n.push(`${u} node(s) with merge conflicts`);const h=t.filter(x=>x.health==="offline").length;h>0&&n.push(`${h} node(s) offline`);const b={totalNodes:e.nodes.length,onlineNodes:e.nodes.filter(x=>x.health==="online").length,dirtyNodes:t.filter(x=>x.dirty).length,orphanNodes:m,errorNodes:e.nodes.filter(x=>!!x.error).length,offlineNodes:h,totalActiveSessions:e.nodes.reduce((x,g)=>{var f;return x+(((f=g.activeSessions)==null?void 0:f.length)??0)},0)};return{meshId:e.meshId,meshName:e.meshName,repoIdentity:e.repoIdentity,refreshedAt:e.refreshedAt,nodes:t,edges:r,stats:b,warnings:n}}function Wo(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function B0(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=Wo();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 $t(e,t){return await fetch(B0(e),{credentials:"same-origin",...t})}function Ad(){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 K0{constructor(){Je(this,"adapters",new Map);Je(this,"states",new Map);Je(this,"runtimeListeners",new Map);Je(this,"screenshotCallbacks",new Map);Je(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 $t(`${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 Wt=new K0;function O0(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=Wo();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Vr=O0(),fc=3e3,W0=3e4;let _t=null,F0=0;const vn=new Map;let ns=null,fr=null;function pc(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function sr(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function H0(e){return e==="connected"?"connected":e}async function sn(e,t,r){const n=Il(e,r||{}),a=_t;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++F0}_${Date.now()}`;return new Promise((c,l)=>{const d=setTimeout(()=>{vn.delete(o),l(new Error(`WS command timeout: ${t}`))},3e4);vn.set(o,{resolve:m=>{clearTimeout(d),c(m)},reject:m=>{clearTimeout(d),l(m)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Ya(e,t){const r=_t;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 U0(e,t,r){const n=_t;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=Il(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 z0{constructor(t){Je(this,"daemonId");Je(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(_t==null?void 0:_t.readyState)===WebSocket.OPEN}get connectionState(){return(_t==null?void 0:_t.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return sn(this.daemonId,t,r)}async sendInput(t,r){return sn(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,ns&&(clearInterval(ns),ns=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await sn(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());Wt.emitScreenshot(this.daemonId,a)}}catch{}};r(),ns=setInterval(r,2e3)}stopScreenshots(t){ns&&(clearInterval(ns),ns=null)}}let Lt=null;function V0(e){return(!Lt||Lt.daemonId!==e)&&(Lt=new z0(e)),Lt}function G0({children:e}){const t=i.useRef(hr()),r=hr();t.current=r;const{setUserName:n}=es(),a=i.useRef(n);a.current=n;const o=i.useRef(null),c=i.useRef(null),[,l]=i.useState("disconnected"),d=i.useCallback((p,x)=>{l(p),fr==null||fr(p,x)},[]),m=i.useRef(null),u=i.useRef(),h=i.useRef(fc),b=i.useRef(!0),k=i.useRef(!1),y=i.useRef("initial_connect");return i.useEffect(()=>{b.current=!0,k.current=!1;function p(){var f,N;if(!b.current||((f=m.current)==null?void 0:f.readyState)===WebSocket.OPEN||((N=m.current)==null?void 0:N.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Vr}...`),sr("connect_attempt",{url:Vr,reason:y.current,delayMs:h.current});let g;try{g=new WebSocket(Vr)}catch(S){console.error("[Standalone WS] Failed to create WebSocket:",S),x();return}m.current=g,g.onopen=()=>{if(!b.current){g.close();return}d("connected"),h.current=fc,sr("open",{url:Vr,reason:y.current}),Ut.resubscribeAll({sendData:Ya}),console.log("[Standalone WS] Connected")},_t=g,g.onmessage=S=>{var v,M;try{const A=JSON.parse(S.data);if((A.type==="command_result"||A.type==="error")&&A.requestId){const w=vn.get(A.requestId);w&&(vn.delete(A.requestId),A.type==="error"?w.reject(new Error(((v=A.data)==null?void 0:v.message)||"Command failed")):w.resolve(A.data));return}if(A.type==="session_output"){const w=A.sessionId||A.cliId||A.cliType;w&&Wt.emitSessionOutput(w,typeof A.data=="string"?A.data:"",typeof A.seq=="number"?A.seq:void 0);return}if(A.type==="runtime_snapshot"){Wt.emitRuntimeSnapshot(A.sessionId,typeof A.text=="string"?A.text:"",typeof A.seq=="number"?A.seq:0,!!A.truncated,typeof A.cols=="number"?A.cols:void 0,typeof A.rows=="number"?A.rows:void 0);return}if(A.type==="topic_update"){const w=A.update;w&&Ut.publish(w);return}if(A.type==="status"||A.type==="initial_state"){const w=A.data;if(!w)return;const{injectEntries:j,markLoaded:K,getIdes:P}=t.current,T=w.instanceId||"standalone",W=P().find(I=>I.id===T),H=V0(T);Wt.register(T,H),Wt.setState(T,"connected"),d("connected",T),Wt.emitStatus(T,w);const R=fn(w,{daemonId:T,existingDaemon:W,existingEntries:P()});pc("ws_status",{type:A.type,daemonId:T,sessions:(w.sessions||[]).map(I=>({id:I.id,parentId:I.parentId,providerType:I.providerType,kind:I.kind,transport:I.transport,unread:I.unread,inboxBucket:I.inboxBucket,lastSeenAt:I.lastSeenAt,lastUpdated:I.lastUpdated,title:I.title})),recentLaunches:(w.recentLaunches||[]).map(I=>({id:I.id,providerType:I.providerType,kind:I.kind,workspace:I.workspace,lastLaunchedAt:I.lastLaunchedAt}))}),pc("entries",{daemonId:T,entries:R.filter(I=>I.type!=="adhdev-daemon").map(I=>({id:I.id,type:I.type,unread:I.unread,inboxBucket:I.inboxBucket,lastSeenAt:I.lastSeenAt,lastUpdated:I.lastUpdated,sessionId:I.sessionId}))}),R.length>0&&j(R,{authoritativeDaemonIds:[T]}),K(),c.current!==T&&((M=o.current)==null||M.call(o),c.current=T,o.current=Ut.subscribe({sendData:Ya},T,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${T}`,params:{includeSessions:!0}},I=>{if(I.topic!=="daemon.metadata")return;const C=t.current.getIdes(),O=C.find(E=>E.id===T),_=fn(I.status,{daemonId:T,existingDaemon:O,existingEntries:C,timestamp:I.timestamp});_.length>0&&t.current.injectEntries(_,{authoritativeDaemonIds:[T]}),I.userName&&a.current&&a.current(I.userName)}))}}catch(A){console.error("[Standalone WS] Parse error:",A)}},g.onclose=S=>{b.current&&(Lt==null||Lt.stopScreenshots(),Lt&&Wt.setState(Lt.daemonId,"disconnected"),d("disconnected"),m.current=null,y.current=`close:${S.code}${S.wasClean?":clean":":unclean"}`,sr("close",{code:S.code,reason:S.reason||"",wasClean:S.wasClean}),x())},g.onerror=S=>{k.current||!b.current||(y.current="error",sr("error",{message:S instanceof Event?"event":String(S),readyState:g.readyState}),console.warn("[Standalone WS] Error, will reconnect:",S))}}function x(){if(!b.current)return;clearTimeout(u.current);const g=h.current;console.log(`[Standalone WS] Reconnecting in ${g}ms...`),sr("schedule_reconnect",{reason:y.current,delayMs:g}),u.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,W0),p()},g)}return p(),()=>{var g;b.current=!1,k.current=!0,(g=o.current)==null||g.call(o),o.current=null,c.current=null,clearTimeout(u.current),m.current&&(m.current.onerror=null,m.current.onclose=null,m.current.close(),m.current=null,_t=null),Lt&&(Lt.stopScreenshots(),Wt.unregister(Lt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function q0({children:e}){const[t,r]=i.useState("disconnected"),[n,a]=i.useState(null);i.useEffect(()=>(fr=(c,l)=>{r(c),l&&a(l)},()=>{fr=null}),[]);const o=i.useMemo(()=>{const c=t==="connected",l=H0(t),d={};return n&&(d[n]=l),d.standalone=l,{wsStatus:t,isConnected:c,connectionStates:d}},[t,n]);return s.jsx(Tu,{connectionOverrides:o,children:s.jsx(G0,{children:e})})}const Ld="adhdev_standalone_font_preferences",hs={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},En=[{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"}],gr=[{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"}],Y0=new Set(En.map(e=>e.id)),X0=new Set(gr.map(e=>e.id));function Kt(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:rn("chat",t.chat),code:rn("code",t.code),terminal:rn("terminal",t.terminal)}}function rn(e,t){const r=hs[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"?Y0:X0).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function nn(e,t){var a;const r=rn(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?En:gr;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function J0(e){const t=Kt(e),r=nn("chat",t.chat),n=nn("code",t.code),a=nn("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function os(e,t=document.documentElement){const r=Kt(e),n=J0(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function Xa(e){const t=Kt(e);try{localStorage.setItem(Ld,JSON.stringify(t))}catch{}return t}function Q0(){try{const e=localStorage.getItem(Ld);if(e)return Kt(JSON.parse(e))}catch{}return hs}function Z0(){return os(Q0())}function rr(e,t){var n;const r=e==="chat"?En:gr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const ev=[{id:"dashboard",path:"/dashboard",icon:s.jsx(Sc,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(Jt,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(_s,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx(wn,{}),label:"Settings"}];function tv({children:e}){const t=Ws(),r=Qa(),n=i.useMemo(()=>ev.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(Cc,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Ic,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(Fh,{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.80"]}),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 sv=[{icon:s.jsx(Jt,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(zt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Tc,{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(_s,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Cc,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],rv=[{icon:s.jsx(zu,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Sc,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(jn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Bu,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Nc,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Ou,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],nv=[{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 av(){return s.jsxs(dr,{icon:s.jsx(Ic,{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.80"]}),children:[s.jsx(yt,{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(yt,{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:sv.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(yt,{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:Tl.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Al.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Ml.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(yt,{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:rv.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(yt,{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:nv.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(hn,{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(tm,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Sa(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:nn(e,n)})]})]})]})}function ov({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:o,onSave:c,onResetToSaved:l,onResetToDefaults:d}){const m=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:En,onChange:u=>o(Sa(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:gr,onChange:u=>o(Sa(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:gr,onChange:u=>o(Sa(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: ",rr("chat",e.chat.preset)," · Code: ",rr("code",e.code.preset)," · Terminal: ",rr("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",rr("chat",hs.chat.preset)," / ",rr("code",hs.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||!m,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||!m,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 iv(){const{ides:e}=es(),t=e.find(X=>X.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=gt(),{userName:a}=es(),[o,c]=i.useState(a||""),[l,d]=i.useState(null),[m,u]=i.useState(null),[h,b]=i.useState(hs),[k,y]=i.useState(!1),[p,x]=i.useState(""),[g,f]=i.useState(""),[N,S]=i.useState("127.0.0.1"),[v,M]=i.useState(""),[A,w]=i.useState(""),[j,K]=i.useState(""),[P,T]=i.useState(""),[W,H]=i.useState(""),[R,I]=i.useState(!1),C=async()=>{const ue=await(await $t("/auth/session")).json();d(ue)},O=async()=>{const ue=await(await $t("/api/v1/standalone/preferences")).json();u(ue),S(ue.standaloneBindHost);const ge=Kt(ue.standaloneFontPreferences);b(ge),os(ge),Xa(ge)};i.useEffect(()=>{a!==void 0&&c(a)},[a]),i.useEffect(()=>{Promise.all([C(),O()]).catch(X=>{T(X instanceof Error?X.message:String(X))})},[]),i.useEffect(()=>{os(h)},[h]);const _=X=>{const ue=X.target.value.trim();t!=null&&t.id&&ue!==a&&n(t.id,"set_user_name",{userName:ue}).catch(console.error)},[E,U]=i.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),Q=X=>{U(X);try{localStorage.setItem("adhdev_sound",X?"1":"0")}catch{}},xe=async()=>{x(""),f(""),y(!0);try{const X=Kt(h),ue=await $t("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:X})}),ge=await ue.json();if(!ue.ok)throw new Error((ge==null?void 0:ge.error)||"Failed to save standalone font preferences");const te=Kt(ge.standaloneFontPreferences);u(ge),b(te),os(te),Xa(te),f("Standalone chat fonts saved for this self-hosted dashboard.")}catch(X){x(X instanceof Error?X.message:String(X))}finally{y(!1)}},de=()=>{const X=Kt(m==null?void 0:m.standaloneFontPreferences);x(""),f(""),b(X),os(X)},Z=()=>{x(""),f(""),b(hs),os(hs)},he=async()=>{T(""),H(""),I(!0);try{const X=await $t("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:N})}),ue=await X.json();if(!X.ok)throw new Error((ue==null?void 0:ue.error)||"Failed to save standalone network preference");u(ue),S(ue.standaloneBindHost),H(ue.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){T(X instanceof Error?X.message:String(X))}finally{I(!1)}},we=async()=>{if(T(""),H(""),A.trim().length<4){T("Password must be at least 4 characters.");return}if(A!==j){T("New password and confirmation do not match.");return}I(!0);try{const X=await $t("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,newPassword:A})}),ue=await X.json();if(!X.ok)throw new Error((ue==null?void 0:ue.error)||"Failed to save password");d(ue),await O(),M(""),w(""),K(""),H(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Ad()}catch(X){T(X instanceof Error?X.message:String(X))}finally{I(!1)}},be=async()=>{T(""),H(""),I(!0);try{const X=await $t("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,clear:!0})}),ue=await X.json();if(!X.ok)throw new Error((ue==null?void 0:ue.error)||"Failed to clear password");d(ue),await O(),M(""),w(""),K(""),H("Standalone password disabled.")}catch(X){T(X instanceof Error?X.message:String(X))}finally{I(!1)}};return s.jsxs(dr,{icon:s.jsx(wn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(Ts,{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(Ts,{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(yt,{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.80"]}),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:(m==null?void 0:m.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:(m==null?void 0:m.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(yt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:N==="127.0.0.1",onChange:()=>S("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 127.0.0.1. Best when only this machine should open the dashboard."})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:N==="0.0.0.0",onChange:()=>S("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:()=>{he()},disabled:R,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 default network mode"}),s.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(m==null?void 0:m.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),s.jsx(yt,{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."}),P&&s.jsx(Ts,{variant:"error",children:P}),W&&s.jsx(Ts,{variant:"success",children:W}),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:v,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:A,onChange:X=>w(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:j,onChange:X=>K(X.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{we()},disabled:R,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…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{be()},disabled:R,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(yt,{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(yt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(Jh,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(yt,{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(tx,{})]}),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(lx,{})]}),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(ov,{value:h,savedValue:Kt(m==null?void 0:m.standaloneFontPreferences),saving:k,error:p,notice:g,onChange:b,onSave:()=>{xe()},onResetToSaved:de,onResetToDefaults:Z})]}),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(mx,{})]})]})}),s.jsx(yt,{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(qh,{}),s.jsx(as,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(em,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:E,onChange:Q})]})}),s.jsx(yt,{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($u,{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:_,onKeyDown:X=>{X.key==="Enter"&&X.currentTarget.blur()}})]})})})]})}Oh();ix();Z0();const cv=jc({baseUrl:"",getToken:Wo});function lv({children:e}){const[t,r]=i.useState(null),[n,a]=i.useState(!0),[o,c]=i.useState(""),[l,d]=i.useState(""),[m,u]=i.useState(!1),h=async()=>{a(!0),d("");try{const y=await(await $t("/auth/session")).json();r(y)}catch(k){d(k instanceof Error?k.message:String(k))}finally{a(!1)}};i.useEffect(()=>{h()},[]),i.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let k=!1;return(async()=>{try{const y=await $t("/api/v1/standalone/preferences");if(!y.ok)return;const p=await y.json();if(k)return;const x=Kt(p.standaloneFontPreferences);os(x),Xa(x)}catch{}})(),()=>{k=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const b=async k=>{k.preventDefault(),u(!0),d("");try{const y=await $t("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),p=await y.json();if(!y.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),c(""),Ad()}catch(y){d(y instanceof Error?y.message:String(y))}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:b,children:[s.jsx("input",{type:"password",value:o,onChange:k=>c(k.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),s.jsx("button",{type:"submit",disabled:m||!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:m?"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 hc(){const{ides:e,initialLoaded:t}=es();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(Ta,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Ta,{to:"/dashboard",replace:!0})}function dv(){const e=i.useMemo(()=>({sendCommand:sn,sendData:Ya,sendPtyInput:U0}),[]);return s.jsx(mu,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Lu,{client:cv,children:s.jsx(lv,{children:s.jsx(q0,{children:s.jsx(Pu,{value:e,children:s.jsx(tv,{children:s.jsxs(fu,{children:[s.jsx(qt,{path:"/dashboard",element:s.jsx(fy,{})}),s.jsx(qt,{path:"/machine",element:s.jsx(hc,{})}),s.jsx(qt,{path:"/machines/:id",element:s.jsx(y0,{})}),s.jsx(qt,{path:"/machines",element:s.jsx(hc,{})}),s.jsx(qt,{path:"/about",element:s.jsx(av,{})}),s.jsx(qt,{path:"/settings",element:s.jsx(iv,{})}),s.jsx(qt,{path:"/mesh",element:s.jsx(R0,{})}),s.jsx(qt,{path:"*",element:s.jsx(Ta,{to:"/dashboard",replace:!0})})]})})})})})})})}Xp({connectionManager:Wt});pu(document.getElementById("root")).render(s.jsx(dv,{}));