@adhdev/daemon-standalone 0.8.54 → 0.8.56

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.
@@ -28,7 +28,7 @@ var sc=Object.defineProperty;var rc=(e,s,r)=>s in e?sc(e,s,{enumerable:!0,config
28
28
  `})]})}function Rn(e,s={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:o=60}=s,i=Date.now()-e,c=Math.floor(i/1e3);if(c<o)return n;const d=Math.floor(c/60);if(d<60)return`${d}m${r}`;const m=Math.floor(d/60);if(m<24)return`${m}h${r}`;const f=Math.floor(m/24);return f<7?`${f}d${r}`:new Date(e).toLocaleDateString()}const Co=e=>Rn(e);function al(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden}}function ks(e){const s=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating",o=e.status==="waiting_approval";return{isReconnecting:s,isConnecting:r,isGenerating:n,isWaiting:o}}function Fs(e){const s=new Map,r=(n,o)=>{n&&s.set(n,{sessionId:n,...al(o)})};for(const n of e)if(n.type!=="adhdev-daemon"){r(n.sessionId,n);for(const o of n.childSessions||[])r(o.id,o)}return s}function Ws(e,s){if(e.sessionId){const r=s.get(e.sessionId);if(r)return r}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1}}function Os(e,s,r){const n=Ws(e,s),o=ks(e),i=o.isReconnecting,c=o.isConnecting,d=o.isGenerating,m=o.isWaiting,f=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||m,p=n.inboxBucket==="working"||d,x=n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation));return{unread:x,requiresAction:f,isWorking:p,isReconnecting:i,isConnecting:c,isGenerating:d,isWaiting:m,inboxBucket:f?"needs_attention":p?"working":x?"task_complete":"idle"}}function ol(e,s,r){return Os(e,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function il(e,s,r){return Ws(e,r||new Map).surfaceHidden}function Io({activeConv:e,onModalButton:s}){const[r,n]=a.useState(null);if(a.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!ks(e).isWaiting||!e.modalButtons)return null;const i=d=>{r||(n(d),s(d))},c=d=>d.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return t.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&t.jsx("div",{className:"text-[11px] opacity-85 mb-1.5 whitespace-nowrap overflow-hidden text-ellipsis max-w-full",children:e.modalMessage.replace(/[\n\r]+/g," ").slice(0,120)}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[t.jsx(ns,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),t.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((d,m)=>{const f=c(d).toLowerCase(),p=/^(run|approve|accept|yes|allow|always)/.test(f),x=/^(reject|deny|delete|remove|abort)/.test(f),b=r===d,S=r!==null;return t.jsx("button",{onClick:()=>i(d),disabled:S,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${p?"font-extrabold":x?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${S&&!b?"opacity-40":"opacity-100"} ${S?"cursor-not-allowed":"cursor-pointer"}`,style:p?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:x?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:b?"⏳ ...":c(d)},m)})})]})]})}var cl=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function ll(e){var s;return(((s=e==null?void 0:e.buttons)==null?void 0:s.length)??0)>0}function bt(e,s){if(ll(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":cl.has(r)?"generating":r==="error"?"error":r==="stopped"?"stopped":r==="starting"?"starting":r==="panel_hidden"?"panel_hidden":r==="not_monitored"?"not_monitored":r==="disconnected"?"disconnected":"idle"}function To(e){return bt(e)==="generating"}function et(e){return e?e.charAt(0).toUpperCase()+e.slice(1).toLowerCase():"IDE"}function dl(e){if(e<60)return`${Math.round(e)}s`;const s=Math.floor(e/60);if(s<60)return`${s}m`;const r=Math.floor(s/60),n=s%60;if(r<24)return n>0?`${r}h ${n}m`:`${r}h`;const o=Math.floor(r/24),i=r%24;return`${o}d ${i}h`}function Fr(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Pr(e,s){const r=typeof s=="string"?s.trim():"";if(r)return r;const n=typeof e=="string"?e.trim():"";if(!n)return"";const o=n.replace(/[\\/]+$/,""),i=o.split(/[\\/]/).filter(Boolean);return i[i.length-1]||o}function ul(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const s=e.split("_"),r=s[s.length-1];return r.length>12?`Machine-${r.substring(0,8)}`:r}return e}function ml(e){const s=e.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function pl(e){return ul(e.trim().replace(/\.local$/i,""))}function fl(e){const s=e.machineNickname??e.nickname;return typeof s!="string"?null:s.trim()||null}function Ao(e,s={}){var o,i;const r=[e.hostname,(o=e.machine)==null?void 0:o.hostname,(i=e.system)==null?void 0:i.hostname].find(c=>typeof c=="string"&&c.trim().length>0&&!ml(c));if(r&&r!=="Unknown")return pl(r);const n=s.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function jt(e,s={}){return fl(e)||Ao(e,s)}function Hs(e){return e.transport==="pty"}function xs(e){return e.transport==="acp"}function ba(e,s){return et(e)}function ga(e,s,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const o=(s||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=et(r||"").trim().toLowerCase();return n===o||n===i||n===c}function xl(e){return bt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function hl(e){if(!Array.isArray(e)||e.length<=1)return e;const s=new Map,r=["generating","waiting_approval","connected","idle","panel_hidden"];for(const n of e){const o=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),i=s.get(o),c=bt(n.status);if(!i){s.set(o,{...n,status:c});continue}const d=r.indexOf(i.status||"idle"),m=r.indexOf(c||"idle");m>=0&&(d<0||m<d)&&s.set(o,{...n,status:c})}return Array.from(s.values())}function bl(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Date.parse(e);if(Number.isFinite(s))return s}return 0}function gl(e){var r,n;const s=(n=(r=e==null?void 0:e.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return s&&bl(s.receivedAt)||0}function yl(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function xn(e){return Math.max(yl(e),gl(e.activeChat))}function vl(e,s,r,n,o,i){const c=s-e;if(c!==0)return c;const d=r.localeCompare(n);return d!==0?d:o.localeCompare(i)}function Ln(e,s){return vl(xn(e),xn(s),jt(e,{fallbackId:e.id}),jt(s,{fallbackId:s.id}),e.id,s.id)}const Mo="adhdev_notification_prefs",ya={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function wl(){try{const e=localStorage.getItem(Mo);if(e){const s=JSON.parse(e);return{...ya,...s}}}catch{}return{...ya}}function jl(e){try{localStorage.setItem(Mo,JSON.stringify(e))}catch{}}let Et=wl(),pr=[];function kl(){pr.forEach(e=>e())}function Nl(e){Et={...Et,...e},jl(Et),kl()}function Sl(){const[,e]=a.useState(0);a.useEffect(()=>{const r=()=>e(n=>n+1);return pr.push(r),()=>{pr=pr.filter(n=>n!==r)}},[]);const s=a.useCallback(r=>{Nl(r)},[]);return[{...Et},s]}function Ps(e){if(!Et.globalEnabled)return!1;switch(e){case"disconnect":return Et.disconnectAlert;case"completion":return Et.completionAlert;case"approval":return Et.approvalAlert;case"browser":return Et.browserNotifications;default:return!0}}const Cl={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Il(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function _o(){return"Notification"in window&&Notification.permission==="granted"}let Ft=null;async function Tl(){if(Ft!==null)return Ft;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Ft=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(Ft=!!await e.pushManager.getSubscription(),Ft):(Ft=!1,!1)}catch{return Ft=!1,!1}}function hn(e,s,r){if(_o())try{const n=new Notification(e,{body:s,icon:"/otter-logo.png",tag:r||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>n.close(),8e3),n.onclick=()=>{window.focus(),n.close()}}catch{}}function Al(e,s={}){const r={...Cl,...s},n=a.useRef(new Map),o=a.useRef(0),i=a.useRef(null);a.useEffect(()=>{Tl().then(d=>{i.current=d})},[]);const c=a.useCallback((d,m,f)=>{const p=Date.now();p-o.current<r.throttleMs||(o.current=p,hn(d,m,f))},[r.throttleMs]);a.useEffect(()=>{var d;if(!(!r.enabled||!_o())&&Ps("browser")&&i.current!==!0){if(document.hasFocus()){for(const m of e)n.current.set(m.id,bt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const f=n.current.get(m.id),p=bt(m.status,{activeModal:m.activeModal}),x=m.name||m.id;if(r.onApproval&&Ps("approval")&&p==="waiting_approval"&&f!=="waiting_approval"){const b=((d=m.activeModal)==null?void 0:d.message)||"Action requires your approval";c(`🔔 ${x} — Approval needed`,b.slice(0,120),`approval-${m.id}`)}r.onComplete&&Ps("completion")&&To(f)&&p==="idle"&&c(`✅ ${x} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&p==="error"&&f!=="error"&&c(`⚠️ ${x} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,p)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,c])}const Ml=/^(run|approve|accept|yes|allow|always)/,_l=/^(run|approve|accept|yes|allow|always|proceed|save)/,Pl=/^(reject|deny|delete|remove|abort|cancel|no)/;function Dn(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Rl(e){const s=Dn(e).toLowerCase();return Ml.test(s)?"primary":Pl.test(s)?"danger":"default"}function Ll(e){return _l.test(Dn(e).toLowerCase())?"approve":"reject"}function Dl(e){return e.map((s,r)=>({label:Dn(s),variant:Rl(s),action:Ll(s),button:s,buttonIndex:r}))}function El(e,s){const r=e||"Approval requested",n=s!=null&&s.length?s.map(o=>`[${o}]`).join(" "):"[Approve] [Reject]";return`⚡ Approval requested: ${r}
29
29
  ${n}`}function $l(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Bl(e,s,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(e,s,"approve").catch(o=>n==null?void 0:n("approve",o))}},{label:"Decline",variant:"danger",onClick:()=>{r(e,s,"reject").catch(o=>n==null?void 0:n("reject",o))}}]}class Kl{constructor(){lt(this,"dedupMap",new Map);lt(this,"DEDUP_WINDOW_MS",5e3);lt(this,"DEDUP_MAX_SIZE",50);lt(this,"DEDUP_CLEANUP_AGE_MS",1e4);lt(this,"toastCallbacks",[]);lt(this,"systemMessageCallbacks",[]);lt(this,"clearSystemMessageCallbacks",[]);lt(this,"resolveActionFn",null);lt(this,"viewRequestRespondFn",null);lt(this,"ides",[])}onToast(s){return this.toastCallbacks.push(s),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==s)}}onSystemMessage(s){return this.systemMessageCallbacks.push(s),()=>{this.systemMessageCallbacks=this.systemMessageCallbacks.filter(r=>r!==s)}}onClearSystemMessage(s){return this.clearSystemMessageCallbacks.push(s),()=>{this.clearSystemMessageCallbacks=this.clearSystemMessageCallbacks.filter(r=>r!==s)}}setResolveAction(s){this.resolveActionFn=s}setIdes(s){this.ides=s}setViewRequestRespond(s){this.viewRequestRespondFn=s}emitToast(s){for(const r of this.toastCallbacks)r(s)}showToast(s,r="info",n){const o=(n==null?void 0:n.id)||Date.now();this.emitToast({id:o,message:s,type:r,timestamp:o,duration:5e3,...n})}emitSystemMessage(s,r){for(const n of this.systemMessageCallbacks)n(s,r)}isDuplicate(s){const r=Date.now(),n=this.dedupMap.get(s)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(s,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[o,i]of this.dedupMap)r-i>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(o);return!1}resolveOwningDaemon(s){if(s.daemonId){const o=this.ides.find(i=>i.id===s.daemonId&&i.type==="adhdev-daemon");if(o)return o}const r=s.targetSessionId&&this.findOwningSession(s.targetSessionId)||void 0;if(r){const o=r.daemonId;if(o){const i=this.ides.find(c=>c.id===o&&c.type==="adhdev-daemon");if(i)return i}}const n=this.ides.filter(o=>o.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(s){for(const r of this.ides)if(r.id===s||r.sessionId===s||(Array.isArray(r.childSessions)?r.childSessions:[]).some(o=>(o==null?void 0:o.id)===s))return r;return null}resolveActionRouteTarget(s){if(s.targetSessionId){const r=this.findOwningSession(s.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return s.daemonId||null}resolveConversationKey(s){return s.targetSessionId?s.targetSessionId:s.daemonId?s.daemonId:null}handleRawEvent(s,r){var A,u;const n=this.resolveConversationKey(s),o=Number.isFinite(s.timestamp)?Number(s.timestamp):Date.now(),i=n||s.daemonId||"",c=s.requestId||s.targetName||s.requesterName||s.modalMessage||String(o),d=`${i}:${s.event}:${c}`;if(this.isDuplicate(d))return;const m=s.targetSessionId?this.findOwningSession(s.targetSessionId):null,f=(m==null?void 0:m.type)||"";let p=et(f);const x=this.resolveOwningDaemon(s);if(x){const h=jt(x,{fallbackId:x.id});h&&(p=!f||f==="adhdev-daemon"?h:`${h}/${p}`)}let b="",S="info";if(s.event==="agent:generating_completed"){const h=s.duration?` (${s.duration}s)`:"";b=`✅ ${p} agent task completed${h}`,S="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(s.event!=="agent:generating_started")if(s.event==="agent:waiting_approval"){if(b=`⚡ ${p} approval needed`,S="warning",n&&!((A=s.modalButtons)!=null&&A.length)&&this.emitSystemMessage(n,{role:"system",timestamp:o,content:El(s.modalMessage,s.modalButtons),_localId:`sys_approval_${o}`}),(u=s.modalButtons)!=null&&u.length&&this.resolveActionFn){const h=this.resolveActionRouteTarget(s);if(!h)return;const y=this.resolveActionFn,l=Dl(s.modalButtons).map(k=>({label:k.label,variant:k.variant,onClick:()=>{y(h,"resolve_action",{action:k.action,button:k.button,buttonIndex:k.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),j=$l(p,s.modalMessage,b),P=Date.now();this.emitToast({id:P,message:j,type:S,timestamp:P,targetKey:n||h,actions:l,duration:15e3}),b=""}}else if(s.event==="monitor:long_generating"){const h=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";b=`⚠️ ${p} agent is taking a long time${h}`,S="warning",Ps("browser")&&!document.hasFocus()&&hn(`⚠️ ${p} — Long Running`,`Agent has been generating for over ${h.replace(/[()]/g,"")}`,`long-${s.targetSessionId||s.daemonId||"daemon"}`)}else if(s.event==="team:view_request"){const h=s.requesterName||"A team member",y=s.requestId,l=s.orgId;if(b=`👁️ ${h} wants to view your session`,S="warning",y&&l&&this.viewRequestRespondFn){const j=Date.now(),P=Bl(l,y,this.viewRequestRespondFn,(k,g)=>console.error(`[EventManager] ${k} view request failed:`,g));this.emitToast({id:j,message:b,type:S,timestamp:j,actions:P,duration:3e4}),b=""}Ps("browser")&&!document.hasFocus()&&hn("👁️ View Request",`${h} wants to view your session`,`view-request-${y}`)}else s.event==="team:view_request_approved"?(b="✅ View request approved",S="success"):s.event==="team:view_request_rejected"&&(b=`❌ ${s.targetName||"Team member"} declined your view request`,S="warning");if(b){const h=Date.now();this.emitToast({id:h,message:b,type:S,timestamp:h,targetKey:n||s.daemonId,duration:5e3})}}}const tt=new Kl,va=new Map;function ys(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Po(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Wl(e){return!ys(e)||!ys(e.controlResult)||!Array.isArray(e.controlResult.options)?null:e.controlResult}function Zs(e){return!ys(e)||!ys(e.controlResult)||typeof e.controlResult.ok!="boolean"?null:e.controlResult}function Cs(e){if(!(!ys(e)||typeof e.error!="string"||!e.error.trim()))return e.error}function Qs(e){return ys(e)&&e.success===!1}function Ol(e){var s,r;for(const n of e||[]){if(n.type==="toast"&&((s=n.toast)!=null&&s.message)){const o=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";tt.showToast(n.toast.message,o);continue}if(n.type==="notification"&&((r=n.notification)!=null&&r.body)){const o=n.notification.level==="warning"?"warning":n.notification.level==="success"?"success":"info";tt.showToast(n.notification.body,o)}}}function Hl(e,s){return e&&Po(e.currentValue)?e.currentValue:s}function fr(e,s){return e.options||s[e.id]||[]}function Ul(e,s,r){var o;return r?((o=fr(e,s).find(i=>i.value===r))==null?void 0:o.label)||r:""}const zl={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Fl({routeId:e,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,controls:i,controlValues:c}){const{sendCommand:d}=Ct(),m=`${e}:${s||n}`,f=zl[n]||"#94a3b8",[p,x]=a.useState({}),b=a.useRef(0),S={};for(const D of i||[])D.defaultValue!==void 0&&(S[D.id]=D.defaultValue);const A={...S,...c||{},...Date.now()<b.current?p:{}};a.useEffect(()=>{c&&Date.now()>b.current&&x({})},[c]);const[u,h]=a.useState(va.get(m)||{}),[y,l]=a.useState(null),[j,P]=a.useState(null),k=a.useCallback(async(D,C={})=>{const V={...C,...s&&{targetSessionId:s}};return await d(e,D,V)},[e,s,d]),g=a.useCallback(async(D,C={})=>{const V=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};return await k("invoke_provider_script",{...V,scriptName:D,...C})},[k,n,r,s]);if(!i||i.length===0)return null;const N=i.filter(D=>D.placement==="bar"&&D.hidden!==!0).sort((D,C)=>(D.order??50)-(C.order??50));if(N.length===0)return null;const v=a.useCallback((D,C,V)=>{const J=Hl(V,C);x(I=>({...I,[D.id]:J})),Ol(V==null?void 0:V.effects)},[]),w=a.useCallback((D,C)=>{x(V=>{const J={...V};return C===void 0?delete J[D.id]:J[D.id]=C,J}),b.current=0},[]),M=async D=>{if(y===D.id){l(null);return}if(fr(D,u).length>0){l(D.id);return}if(D.dynamic&&D.listScript){P(D.id);try{const V=await g(D.listScript,{}),J=Wl(V);if(!J){const R=Cs(V);R&&tt.showToast(R,"warning");return}const I=J.options;if(h(R=>{const B={...R,[D.id]:I};return va.set(m,B),B}),Po(J.currentValue)){const R=J.currentValue;x(B=>({...B,[D.id]:R}))}l(D.id)}catch(V){const J=V instanceof Error?V.message:`Could not load ${D.label}`;tt.showToast(J,"warning")}finally{P(null)}}},T=async(D,C)=>{l(null);const V=(c==null?void 0:c[D.id])??S[D.id];x(J=>({...J,[D.id]:C})),b.current=Date.now()+5e3;try{if(!D.setScript)return;const J=await g(D.setScript,{model:D.id==="model"?C:void 0,mode:D.id==="mode"?C:void 0,value:C}),I=Zs(J);if(I&&!I.ok||Qs(J))throw new Error((I==null?void 0:I.error)||Cs(J)||`Could not update ${D.label}`);v(D,C,I)}catch(J){w(D,V);const I=J instanceof Error?J.message:`Could not update ${D.label}`;tt.showToast(I,"warning")}},$=async D=>{const C=fr(D,u).map(z=>z.value);if(C.length===0)return;const V=String(A[D.id]||""),I=(C.indexOf(V)+1)%C.length,R=C[I];if(typeof R!="string")return;const B=(c==null?void 0:c[D.id])??S[D.id];x(z=>({...z,[D.id]:R})),b.current=Date.now()+5e3;try{if(!D.setScript)return;const z=await g(D.setScript,{value:R}),Z=Zs(z);if(Z&&!Z.ok||Qs(z))throw new Error((Z==null?void 0:Z.error)||Cs(z)||`Could not update ${D.label}`);v(D,R,Z)}catch(z){w(D,B);const Z=z instanceof Error?z.message:`Could not update ${D.label}`;tt.showToast(Z,"warning")}},E=async D=>{const V=!A[D.id],J=(c==null?void 0:c[D.id])??S[D.id];x(I=>({...I,[D.id]:V})),b.current=Date.now()+5e3;try{if(!D.setScript)return;const I=await g(D.setScript,{value:V}),R=Zs(I);if(R&&!R.ok||Qs(I))throw new Error((R==null?void 0:R.error)||Cs(I)||`Could not update ${D.label}`);v(D,V,R)}catch(I){w(D,J);const R=I instanceof Error?I.message:`Could not update ${D.label}`;tt.showToast(R,"warning")}},F=async D=>{if(!D.invokeScript)return;if(D.confirmMessage){const V=[D.confirmTitle,D.confirmMessage,D.confirmLabel].filter(I=>typeof I=="string"&&I.trim().length>0);if(!window.confirm(V.join(`
30
30
 
31
- `)))return}const C=(c==null?void 0:c[D.id])??S[D.id];try{const V=await g(D.invokeScript),J=Zs(V);if(J&&!J.ok||Qs(V))throw new Error((J==null?void 0:J.error)||Cs(V)||`Could not run ${D.label}`);J&&v(D,C??!0,J)}catch(V){w(D,C);const J=V instanceof Error?V.message:`Could not run ${D.label}`;tt.showToast(J,"warning")}};return t.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1 flex-wrap text-[10px] border-t border-border-subtle bg-surface-primary font-[var(--font)]",children:[t.jsx("span",{className:"text-[9px] font-bold tracking-wide opacity-70",style:{color:f},children:o}),t.jsx("span",{className:"text-border-subtle text-[10px]",children:"│"}),N.map(D=>{const C=String(A[D.id]||""),V=Ul(D,u,C),J=y===D.id,I=j===D.id,R=fr(D,u);switch(D.type){case"select":return t.jsxs("div",{className:"relative",children:[t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all bg-[var(--surface-tertiary)] whitespace-nowrap max-w-40 overflow-hidden text-ellipsis",style:{borderColor:J?`${f}55`:"transparent",border:"1px solid",color:C?"var(--text-primary)":"var(--text-muted)"},onClick:()=>M(D),children:[D.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:D.icon}),I?"...":V||D.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),J&&R.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>l(null)}),t.jsxs("div",{className:"absolute bottom-full left-0 z-[60] bg-[var(--surface-primary)] border border-border-subtle rounded-lg mb-1 max-h-[220px] overflow-y-auto min-w-40 shadow-[0_-4px_16px_rgba(0,0,0,0.3)]",children:[t.jsx("div",{className:"px-3 py-1.5 text-[9px] font-bold text-text-muted tracking-wider border-b border-border-subtle",children:D.label.toUpperCase()}),R.map(B=>t.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:B.value===C?`${f}18`:"transparent",color:B.value===C?f:"var(--text-secondary)",fontWeight:B.value===C?600:400,borderLeft:B.value===C?`2px solid ${f}`:"2px solid transparent"},title:B.description||B.label,onMouseEnter:z=>{z.currentTarget.style.background=`${f}12`},onMouseLeave:z=>{z.currentTarget.style.background=B.value===C?`${f}18`:"transparent"},onClick:()=>T(D,B.value),children:B.label},B.value))]})]})]},D.id);case"cycle":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all bg-[var(--surface-tertiary)] whitespace-nowrap",style:{border:"1px solid transparent",color:C?"var(--text-primary)":"var(--text-muted)"},onClick:()=>$(D),title:`Click to cycle: ${R.map(B=>B.label).join(" → ")}`,children:[D.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:D.icon}),V||D.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"⟳"})]},D.id);case"toggle":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all whitespace-nowrap",style:{border:"1px solid",borderColor:C?`${f}44`:"transparent",background:C?`${f}14`:"var(--surface-tertiary)",color:C?f:"var(--text-muted)"},onClick:()=>E(D),children:[D.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:D.icon}),D.label]},D.id);case"action":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all hover:bg-[var(--surface-tertiary-hover)] whitespace-nowrap",style:{border:"1px solid var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>F(D),children:[D.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:D.icon}),D.resultDisplay==="inline"&&C?`${D.label}: ${C}`:D.label]},D.id);case"display":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium whitespace-nowrap",style:{border:"1px solid var(--border-default)",background:"var(--surface-tertiary)",color:C?"var(--text-primary)":"var(--text-muted)"},children:[D.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:D.icon}),C?`${D.label}: ${C}`:D.label]},D.id);default:return null}})]})}const Vl=a.memo(function({contextKey:s,panelLabel:r,isSending:n,onSend:o,isActive:i=!0}){const c=a.useRef(null),[d,m]=a.useState("");a.useEffect(()=>{m("")},[s]),a.useEffect(()=>{var p;i&&((p=c.current)==null||p.focus())},[s,i]);const f=()=>{const p=d.trim();!p||n||(m(""),o(p))};return t.jsx("div",{className:"dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden transition-all duration-200 ease-out",style:{borderTop:i?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:i?72:0,opacity:i?1:0,transform:i?"translateY(0)":"translateY(10px)",padding:i?"10px 12px":"0 12px",pointerEvents:i?"auto":"none"},"aria-hidden":!i,children:t.jsxs("div",{className:"flex gap-2.5 items-center",title:i?`Send message to ${r}`:void 0,children:[t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:c,type:"text",placeholder:`Send message to ${r}...`,value:d,onChange:p=>m(p.target.value),onPaste:p=>{const x=p.clipboardData.getData("text");x&&m(b=>b+x),p.preventDefault()},onKeyDown:p=>{if(p.key==="Enter"){if(p.nativeEvent.isComposing){p.preventDefault();return}p.preventDefault(),f()}},onBlur:p=>{if(window.innerWidth<768){const x=p.relatedTarget;if((x==null?void 0:x.tagName)==="BUTTON")return;setTimeout(()=>{document.documentElement.scrollTop=0},300)}},className:"w-full h-10 rounded-[20px] px-4 bg-bg-secondary text-sm text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),t.jsx("button",{onClick:f,disabled:!d.trim()||n,className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${d.trim()&&!n?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:d.trim()&&!n?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:t.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:d.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})}),Ye=e=>e.transport==="pty",vs=(e,s)=>Ye(e)?e.mode||"terminal":"chat",Ro=(e,s)=>Ye(e)&&vs(e)==="terminal",Ve=e=>e.transport==="acp";function $t(e){return e.streamSource!=="agent-stream"}function Ut(e){var s;return e.daemonId||((s=e.routeId)==null?void 0:s.split(":")[0])||e.routeId||""}function Lo(e){return e.machineName||""}function wr(e){return Ut(e)}function wt(e){return e.agentType||""}function En(e){return e.hostIdeType||""}function Rr(e){return e.displayPrimary||e.agentName||"Agent"}function $n(e){return[e.displaySecondary,Lo(e)].filter(Boolean)}function Vs(e){return e.agentName||et(wt(e))}function Gl(e){var s,r;if(!$t(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return et(En(e)||wt(e))}function Bn(e){return $t(e)?e.sessionId:e.nativeSessionId}function wa(e){return $t(e)?"native":e.tabKey}function ql(e){return e.sessionId}function Yl(e,s){if(s)return $t(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function Xl(e,s){const r=wt(e),n=$t(e)?s!=null&&s.type?et(s.type):et(En(e)||r):Vs(e);return{isNativeConversation:$t(e),isCli:Ye(e),isAcp:Ve(e),isCliTerminal:Ro(e),providerType:r,displayLabel:n,targetEntry:Yl(e,s)}}function Do({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:o=!0}){const i=ws(),c=Ut(e),d=Lo(e),m=e.transport==="cdp-page"||e.transport==="cdp-webview",f=e.streamSource==="agent-stream"&&!!e.agentName,p=!f&&(e.transport==="pty"||e.transport==="acp"),x=Vs(e),b=Gl(e),S=a.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),A=a.useCallback(()=>{if(r){r();return}const u=Bn(e);u&&i(`/dashboard?activeTab=${encodeURIComponent(u)}`)},[e,i,r]);return t.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[m&&(o?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:A,title:b,children:[t.jsx(kt,{size:12}),t.jsx("span",{children:b})]}):t.jsxs("span",{className:"conversation-meta-chip",title:b,children:[t.jsx(kt,{size:12}),t.jsx("span",{children:b})]})),f&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[t.jsx(Ks,{size:12}),t.jsx("span",{children:x})]}),p&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[t.jsx(Ks,{size:12}),t.jsx("span",{children:x})]}),d&&(o?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:S,title:d,children:[t.jsx(Bt,{size:12}),t.jsx("span",{children:d})]}):t.jsxs("span",{className:"conversation-meta-chip",title:d,children:[t.jsx(Bt,{size:12}),t.jsx("span",{children:d})]}))]})}function ja(e,s){return`${e}:${s}`}function Jl(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function er(e,s){Jl()&&console.debug(`[subscription-manager] ${e}`,s)}class Zl{constructor(){lt(this,"active",new Map)}subscribe(s,r,n,o){var f;const i=ja(n.topic,n.key),c=this.active.get(i);let d=!0;if(c)c.handlers.add(o),c.lastUpdate&&o(c.lastUpdate);else{const p={daemonId:r,request:n,handlers:new Set([o])};this.active.set(i,p),er("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((f=s.sendData)==null?void 0:f.call(s,r,n))??!1}const m=()=>{var b;const p=this.active.get(i);if(!p||(p.handlers.delete(o),p.handlers.size>0))return;this.active.delete(i);const x={type:"unsubscribe",topic:n.topic,key:n.key};er("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(b=s.sendData)==null||b.call(s,r,x)};return m.initialSendAccepted=d,m}publish(s){const r=ja(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,ss.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.publish",topic:s.topic,payload:{key:s.key}}),n.handlers.forEach(o=>{o(s),ss.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.handler_invoked",topic:s.topic,payload:{key:s.key}})}))}resubscribeAll(s){var r;er("resubscribe_all",{count:this.active.size,subscriptions:Array.from(this.active.values()).map(n=>({daemonId:n.daemonId,topic:n.request.topic,key:n.request.key}))});for(const n of this.active.values())(r=s.sendData)==null||r.call(s,n.daemonId,n.request)}resubscribeForDaemon(s,r){var o;const n=Array.from(this.active.values()).filter(i=>i.daemonId===s);er("resubscribe_daemon",{daemonId:s,count:n.length,subscriptions:n.map(i=>({topic:i.request.topic,key:i.request.key}))});for(const i of n)(o=r.sendData)==null||o.call(r,i.daemonId,i.request)}}const Ot=new Zl;function Ql(e,s){const r=new Map;for(const n of e||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===s&&n.sessionId){r.set(n.sessionId,{parentSessionId:n.parentSessionId,providerSessionId:n.providerSessionId,workspace:n.workspace??null,sessionCapabilities:n.sessionCapabilities,cdpConnected:n.cdpConnected,currentModel:n.currentModel,currentPlan:n.currentPlan,currentAutoApprove:n.currentAutoApprove,controlValues:n.controlValues,providerControls:n.providerControls,acpConfigOptions:n.acpConfigOptions,acpModes:n.acpModes,runtimeWriteOwner:n.runtimeWriteOwner,runtimeAttachedClients:n.runtimeAttachedClients,cliName:n.cliName,type:n.type,status:n.status,lastMessagePreview:n.lastMessagePreview,lastMessageRole:n.lastMessageRole,lastMessageAt:n.lastMessageAt,lastMessageHash:n.lastMessageHash});for(const i of n.childSessions||[]){if(!(i!=null&&i.id))continue;const c=r.get(i.id)||{};r.set(i.id,{...c,...i})}}return r}function tr(e,s){return{...e,parentId:e.parentId??(s==null?void 0:s.parentSessionId)??null,providerName:e.providerName??(s==null?void 0:s.cliName)??(s==null?void 0:s.type)??e.providerType,workspace:e.workspace??(s==null?void 0:s.workspace)??null,capabilities:e.capabilities??(s==null?void 0:s.sessionCapabilities)??[],cdpConnected:e.cdpConnected??(s==null?void 0:s.cdpConnected),currentModel:e.currentModel??(s==null?void 0:s.currentModel),currentPlan:e.currentPlan??(s==null?void 0:s.currentPlan),currentAutoApprove:e.currentAutoApprove??(s==null?void 0:s.currentAutoApprove),controlValues:e.controlValues??(s==null?void 0:s.controlValues),providerControls:e.providerControls??(s==null?void 0:s.providerControls),acpConfigOptions:e.acpConfigOptions??(s==null?void 0:s.acpConfigOptions),acpModes:e.acpModes??(s==null?void 0:s.acpModes),runtimeWriteOwner:e.runtimeWriteOwner??(s==null?void 0:s.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(s==null?void 0:s.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(s==null?void 0:s.lastMessagePreview),lastMessageRole:e.lastMessageRole??(s==null?void 0:s.lastMessageRole),lastMessageAt:e.lastMessageAt??(s==null?void 0:s.lastMessageAt),lastMessageHash:e.lastMessageHash??(s==null?void 0:s.lastMessageHash)}}function ed(e){const s=[],r=new Map;for(const n of e)if(n.parentId){const o=r.get(n.parentId)||[];o.push(n),r.set(n.parentId,o)}else s.push(n);return{topLevel:s,childrenByParent:r}}function jr(e,s){const r=[],{daemonId:n,existingDaemon:o,existingEntries:i,timestamp:c}=s,d=c||e.timestamp||Date.now(),m=e.sessions||[],{topLevel:f,childrenByParent:p}=ed(m),x=Ql(i,n),b=e.machine?{...(o==null?void 0:o.machine)||{},...e.machine}:o==null?void 0:o.machine,S=f.filter(h=>h.kind==="workspace"&&h.transport==="cdp-page"),A=f.filter(h=>h.kind==="agent"&&h.transport==="pty"),u=f.filter(h=>h.kind==="agent"&&h.transport==="acp");r.push({...o||{},id:n,type:"adhdev-daemon",status:"online",timestamp:d,...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},cdpConnected:S.some(h=>!!h.cdpConnected)});for(const h of S){const y=x.get(h.id),l=tr(h,y),j=(p.get(h.id)||[]).map(P=>tr(P,x.get(P.id)));r.push({id:`${n}:ide:${h.id}`,sessionId:h.id,providerSessionId:h.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:l.parentId,sessionKind:l.kind,transport:l.transport,sessionCapabilities:l.capabilities,type:l.providerType,status:l.cdpConnected?"online":"detected",daemonId:n,instanceId:h.id,workspace:l.workspace,terminals:0,childSessions:j,agents:j.map(P=>({id:P.id,name:P.providerName||P.providerType,type:P.providerType,status:P.status})),activeChat:l.activeChat,chats:[],cdpConnected:l.cdpConnected,...l.currentModel!==void 0&&{currentModel:l.currentModel},...l.currentPlan!==void 0&&{currentPlan:l.currentPlan},...l.currentAutoApprove!==void 0&&{currentAutoApprove:l.currentAutoApprove},...l.lastMessagePreview!==void 0&&{lastMessagePreview:l.lastMessagePreview},...l.lastMessageRole!==void 0&&{lastMessageRole:l.lastMessageRole},...l.lastMessageAt!==void 0&&{lastMessageAt:l.lastMessageAt},...l.lastMessageHash!==void 0&&{lastMessageHash:l.lastMessageHash},lastUpdated:l.lastUpdated,unread:l.unread,lastSeenAt:l.lastSeenAt,inboxBucket:l.inboxBucket,surfaceHidden:l.surfaceHidden,...l.controlValues!==void 0&&{controlValues:l.controlValues},...l.providerControls!==void 0&&{providerControls:l.providerControls},timestamp:d})}for(const h of A){const y=x.get(h.id),l=tr(h,y);r.push({id:`${n}:cli:${h.id}`,sessionId:h.id,providerSessionId:h.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:l.parentId,sessionKind:l.kind,transport:l.transport,sessionCapabilities:l.capabilities,type:l.providerType,agentType:l.providerType,status:l.status||"running",daemonId:n,instanceId:h.id,cliName:l.providerName||l.providerType,mode:l.mode||(y==null?void 0:y.mode)||"terminal",workspace:l.workspace||"",activeChat:l.activeChat,...l.resume!==void 0&&{resume:l.resume},...l.runtimeKey!==void 0&&{runtimeKey:l.runtimeKey},...l.runtimeDisplayName!==void 0&&{runtimeDisplayName:l.runtimeDisplayName},...l.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:l.runtimeWorkspaceLabel},...l.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:l.runtimeWriteOwner},...l.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:l.runtimeAttachedClients},...l.lastMessagePreview!==void 0&&{lastMessagePreview:l.lastMessagePreview},...l.lastMessageRole!==void 0&&{lastMessageRole:l.lastMessageRole},...l.lastMessageAt!==void 0&&{lastMessageAt:l.lastMessageAt},...l.lastMessageHash!==void 0&&{lastMessageHash:l.lastMessageHash},lastUpdated:l.lastUpdated,unread:l.unread,lastSeenAt:l.lastSeenAt,inboxBucket:l.inboxBucket,surfaceHidden:l.surfaceHidden,...l.controlValues!==void 0&&{controlValues:l.controlValues},...l.providerControls!==void 0&&{providerControls:l.providerControls},timestamp:d,_isCli:!0})}for(const h of u){const y=x.get(h.id),l=tr(h,y);r.push({id:`${n}:acp:${h.id}`,sessionId:h.id,providerSessionId:h.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:l.parentId,sessionKind:l.kind,transport:l.transport,sessionCapabilities:l.capabilities,type:l.providerType,agentType:l.providerType,status:l.status||"running",daemonId:n,instanceId:h.id,cliName:l.providerName||l.providerType,mode:"chat",workspace:l.workspace||"",activeChat:l.activeChat,...l.runtimeKey!==void 0&&{runtimeKey:l.runtimeKey},...l.runtimeDisplayName!==void 0&&{runtimeDisplayName:l.runtimeDisplayName},...l.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:l.runtimeWorkspaceLabel},...l.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:l.runtimeWriteOwner},...l.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:l.runtimeAttachedClients},...l.currentModel!==void 0&&{currentModel:l.currentModel},...l.currentPlan!==void 0&&{currentPlan:l.currentPlan},...l.lastMessagePreview!==void 0&&{lastMessagePreview:l.lastMessagePreview},...l.lastMessageRole!==void 0&&{lastMessageRole:l.lastMessageRole},...l.lastMessageAt!==void 0&&{lastMessageAt:l.lastMessageAt},...l.lastMessageHash!==void 0&&{lastMessageHash:l.lastMessageHash},lastUpdated:l.lastUpdated,unread:l.unread,lastSeenAt:l.lastSeenAt,inboxBucket:l.inboxBucket,surfaceHidden:l.surfaceHidden,...l.acpConfigOptions!==void 0&&{acpConfigOptions:l.acpConfigOptions},...l.acpModes!==void 0&&{acpModes:l.acpModes},...l.controlValues!==void 0&&{controlValues:l.controlValues},...l.providerControls!==void 0&&{providerControls:l.providerControls},timestamp:d,_isAcp:!0})}return r}const Vr=new Map,Gr=new Map,qr=new Set,Rs=new Map,td=1200;function sd(e){if(!e||typeof e!="object")return null;const s=e,r=s.status;if(r&&typeof r=="object")return r;const n=s.result;if(n&&typeof n=="object"&&"status"in n){const o=n.status;if(o&&typeof o=="object")return o}return s}function ka(e,s){const r=Rs.get(e);!r||r.size===0||(Rs.delete(e),r.forEach(n=>n(s)))}function rd(e,s){return new Promise(r=>{const n=Rs.get(e)||new Set;Rs.set(e,n);const o=c=>{clearTimeout(i),n.delete(o),n.size===0&&Rs.delete(e),r(c)},i=setTimeout(()=>o(!1),s);n.add(o)})}function Gs(){const{sendCommand:e,sendData:s}=Ct(),{injectEntries:r,getIdes:n}=vr();return a.useCallback(async(o,i)=>{if(!o)return;const c=(i==null?void 0:i.minFreshMs)??6e4,d=Gr.get(o)||0;if(!(i!=null&&i.force)&&qr.has(o)&&d>0||!(i!=null&&i.force)&&d>0&&Date.now()-d<c)return;const m=Vr.get(o);if(m)return m;const f=(async()=>{if(s&&!qr.has(o)&&(qr.add(o),Ot.subscribe({sendData:s},o,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${o}`,params:{includeSessions:!0}},u=>{const h=n(),y=h.find(j=>j.id===o),l=jr(u.status,{daemonId:o,existingDaemon:y,existingEntries:h,timestamp:u.timestamp});l.length>0&&r(l),Gr.set(o,Date.now()),ka(o,!0)}),!(i!=null&&i.force)&&await rd(o,td)))return;const p=await e(o,"get_status_metadata"),x=sd(p);if(!x)return;const b=n(),S=b.find(u=>u.id===o),A=jr(x,{daemonId:o,existingDaemon:S,existingEntries:b,timestamp:x.timestamp||Date.now()});A.length>0&&r(A,{authoritativeDaemonIds:[o]}),Gr.set(o,Date.now()),ka(o,!0)})().finally(()=>{Vr.delete(o)});return Vr.set(o,f),f},[n,r,e,s])}function os(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}function Eo(e,s){if(!e||!s)return!1;if(e===s||e.id&&s.id&&String(e.id)===String(s.id)||e._localId&&s._localId&&String(e._localId)===String(s._localId))return!0;const r=String(e.role||"").toLowerCase(),n=String(s.role||"").toLowerCase();if(r!==n)return!1;const o=as(e.content),i=as(s.content);if(!o||o!==i)return!1;const c=os(e),d=os(s);return c&&d?Math.abs(c-d)<=15e3:!!e._localId!=!!s._localId}function Na(e){let s=0;return e!=null&&e._localId||(s+=4),e!=null&&e.id&&(s+=3),e!=null&&e._turnKey&&(s+=2),os(e)&&(s+=1),s}function nd(e,s){const r=Na(e),n=Na(s);return n!==r?n>r?s:e:as(s.content).length>=as(e.content).length?s:e}function Ls(e){const s=[];for(const r of e){const n=s.findIndex(o=>Eo(o,r));if(n>=0){s.splice(n,1,nd(s[n],r));continue}s.push(r)}return s}function Sa(e){return[...e].sort((s,r)=>{const n=os(s),o=os(r);return n&&o&&n!==o?n-o:0})}function Ca(e){return`${String((e==null?void 0:e.role)||"").toLowerCase()}:${as(e==null?void 0:e.content).slice(0,100)}`}function Ia(e,s){const r=e.filter(n=>String((n==null?void 0:n.role)||"").toLowerCase()==="user").slice();return s.filter(n=>{const o=r.findIndex(i=>Eo(i,n));return o>=0?(r.splice(o,1),!1):!0})}function ad(e,s){const r=new Set(s.map(n=>Ca(n)));return e.filter(n=>!r.has(Ca(n)))}const od=60,id=200;function cd(e={}){return e.isCliLike?id:od}function ld(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function dd(e){let s=2166136261;for(const r of e){const n=String(r||"");for(let o=0;o<n.length;o+=1)s^=n.charCodeAt(o),s=Math.imul(s,16777619)>>>0;s^=255,s=Math.imul(s,16777619)>>>0}return s.toString(16).padStart(8,"0")}function Ta(e,s){const r=e[e.length-1];if(!r)return"empty:";let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return["",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function $o(e){if(!e)return"";let s="";try{s=JSON.stringify(e.content??"")}catch{s=String(e.content??"")}return dd([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),s])}function ud(e){return{knownMessageCount:e.length,lastMessageSignature:$o(e[e.length-1])}}function md(e,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return e;case"append":return Ls([...e,...r]);case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??e.length),e.length));return Ls([...e.slice(0,n),...r])}case"full":default:return r}}const Aa=60;function bn({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,handleFocusAgent:o,isFocusingAgent:i,actionLogs:c,userName:d,showMetaChips:m=!1,scrollToBottomRequestNonce:f,isInputActive:p=!0}){var Q,xe;const x=a.useRef(new Map),b=a.useRef(new Map),S=a.useRef(new Map),{sendCommand:A,sendData:u}=Ct(),h=Gs();zs("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:c.length,isSendingChat:n});const y=rt.useMemo(()=>ks(e),[e.status,e.connectionState]),l=a.useMemo(()=>Xl(e,s),[e,s]),j=cd({isCliLike:l.isCli||l.isAcp}),P=a.useRef(new Map),k=a.useCallback(W=>(P.current.has(W)||P.current.set(W,{messages:[],offset:0,hasMore:!0,error:null,visibleLiveCount:j}),P.current.get(W)),[j]),g=a.useCallback((W,ee)=>{const ne=k(W);P.current.set(W,{...ne,...ee}),N(oe=>oe+1)},[k]),[,N]=a.useState(0),v=e.tabKey,w=k(v),M=w.messages,T=w.hasMore,$=w.error,E=b.current.get(v),F=e.messages.filter(W=>!!(W!=null&&W._localId)),D=E?Ls([...E,...F]):e.messages;a.useEffect(()=>{w.visibleLiveCount>=j||g(v,{visibleLiveCount:j})},[j,w.visibleLiveCount,v,g]);const C=Math.max(0,D.length-w.visibleLiveCount),V=Rr(e),J=wr(e),I=e.sessionId||"",R=e.providerSessionId||I,[B,z]=a.useState(!1);a.useEffect(()=>{const W=l.targetEntry;J&&(!W||W.providerControls===void 0||W.controlValues===void 0)&&h(J,{minFreshMs:3e4}).catch(()=>{})},[J,l.isAcp,(Q=l.targetEntry)==null?void 0:Q.providerControls,(xe=l.targetEntry)==null?void 0:xe.controlValues,h]),a.useEffect(()=>{if(!J||!I||!u)return;const W=b.current.get(v)||[],ee=S.current.get(v),ne=ee&&ee.knownMessageCount?ee:ud(W),oe=`daemon:${J}:session:${I}`;return Ot.subscribe({sendData:u},J,{type:"subscribe",topic:"session.chat_tail",key:oe,params:{targetSessionId:I,historySessionId:R,knownMessageCount:ne.knownMessageCount,lastMessageSignature:ne.lastMessageSignature,...ne.knownMessageCount?{}:{tailLimit:Aa}}},te=>{const de=b.current.get(v)||[],se=md(de,te),pe=Math.max(se.length,Number(te.totalMessages||0));S.current.set(v,{knownMessageCount:pe,lastMessageSignature:typeof te.lastMessageSignature=="string"?te.lastMessageSignature:$o(se[se.length-1])}),Ta(de)!==Ta(se)&&(b.current.set(v,se),ss.record({interactionId:te.interactionId,kind:"dashboard.chat_tail_applied",topic:"session.chat_tail",payload:{sessionId:I,syncMode:te.syncMode,previousCount:de.length,nextCount:se.length}}),N(Ne=>Ne+1))})},[J,R,u,I,v]);const Z=a.useCallback(async()=>{if(B)return;const W=e.tabKey,ee=k(W);if(D.length>ee.visibleLiveCount){g(W,{visibleLiveCount:Math.min(D.length,ee.visibleLiveCount+Aa),error:null});return}z(!0),g(W,{error:null});try{const ne=wr(e);if(!ne){g(W,{hasMore:!1});return}const oe=wt(e),he=await A(ne,"chat_history",{agentType:oe,offset:ee.offset,limit:30,targetSessionId:e.sessionId,historySessionId:e.providerSessionId||e.sessionId}),te=ld(he),de=te.messages||[];if(de.length>0){const se=k(W);g(W,{messages:[...de,...se.messages],offset:se.offset+de.length,hasMore:!!te.hasMore})}else g(W,{hasMore:!!te.hasMore})}catch(ne){const oe=(ne==null?void 0:ne.message)||"";oe.includes("P2P not available")||oe.includes("channel not open")||oe.includes("P2P not connected")||oe.includes("timeout")?g(W,{error:"Connection not ready — tap to retry"}):g(W,{hasMore:!1,error:"Failed to load history"})}finally{z(!1)}},[B,e,D.length,A,k,g]),{allMessages:fe,receivedAtMap:Pe}=a.useMemo(()=>{const W=C>0?D.slice(-w.visibleLiveCount):D;if(M.length===0){const he=Sa(Ls(W)),te={};return he.forEach((de,se)=>{const pe=`${e.tabKey}:${fs(de,se)}`;let ae=os(de)||x.current.get(pe)||0;ae||(ae=Date.now(),x.current.set(pe,ae)),te[fs(de,se)]=ae}),{allMessages:he,receivedAtMap:te}}const ee=ad(M,W),ne=Sa(Ls([...ee,...W])),oe={};return ne.forEach((he,te)=>{const de=`${e.tabKey}:${fs(he,te)}`;let se=os(he)||x.current.get(de)||0;se||(se=Date.now(),x.current.set(de,se)),oe[fs(he,te)]=se}),{allMessages:ne,receivedAtMap:oe}},[e.tabKey,C,M,D,w.visibleLiveCount]),ke=a.useMemo(()=>c.filter(W=>W.routeId===e.tabKey).sort((W,ee)=>W.timestamp-ee.timestamp),[c,e.tabKey]),ve=a.useMemo(()=>{if(D.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[t.jsx("div",{className:"connecting-logo-float",children:t.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),t.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[t.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",t.jsx("span",{className:"connecting-dots"})]}),t.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((y.isGenerating||e.status==="streaming")&&z(!1),e.status==="not_monitored")return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-3xl opacity-60",children:t.jsx(Ks,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),t.jsx("button",{onClick:o,disabled:i,className:"btn btn-primary",children:i?"⌛ Switching...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(gs,{size:14})," Open ",V," Panel"]})}),t.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden")return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-3xl opacity-60",children:t.jsx(yo,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),t.jsx("button",{onClick:o,disabled:i,className:"btn btn-primary",children:i?"⌛ Opening...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(gs,{size:14})," Open ",V," Panel"]})}),t.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Open the agent panel or chat view in the app you are using to start viewing messages"})]});if(e.status==="idle"&&!B)return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),t.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,o,i,B,D.length,V,y.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[m&&t.jsx(Do,{conversation:e,className:"chat-pane-meta-row"}),t.jsx(Xc,{messages:fe,actionLogs:ke,agentName:Vs(e)||V||"Agent",userName:d,isCliMode:l.isCli||l.isAcp,isWorking:y.isGenerating,contextKey:e.tabKey,receivedAtMap:Pe,onLoadMore:Z,isLoadingMore:B,hasMoreHistory:T,hiddenLiveCount:C,loadError:$??void 0,emptyState:ve,scrollToBottomRequestNonce:f}),p&&!l.isCliTerminal&&(()=>{var W,ee;return t.jsx(Fl,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:l.providerType,displayLabel:l.displayLabel,controls:(W=l.targetEntry)==null?void 0:W.providerControls,controlValues:(ee=l.targetEntry)==null?void 0:ee.controlValues})})(),!l.isCliTerminal&&t.jsx(Vl,{contextKey:e.tabKey,panelLabel:V,isSending:n,onSend:r,isActive:p})]})}let Bo=rs;function Ko(){return Bo()}class pd{constructor(){lt(this,"listeners",new Map)}send(s){}isConnected(){return!1}on(s,r){return this.listeners.has(s)||this.listeners.set(s,new Set),this.listeners.get(s).add(r),()=>{var n;(n=this.listeners.get(s))==null||n.delete(r)}}emit(s,...r){var n;(n=this.listeners.get(s))==null||n.forEach(o=>o(...r))}}let Wo=new pd;class fd{sendPtyInput(s,r,n){return!1}sendPtyResize(s,r,n,o){return!1}retryConnection(s){}getState(s){return"disconnected"}sendData(s,r){return!1}get(s){}onScreenshot(s,r){return()=>{}}onRuntimeEvent(s,r){return()=>{}}requestRuntimeSnapshot(s,r){return Promise.resolve()}}let at=new fd;function xd(e){e.dashboardWS&&(Wo=e.dashboardWS),e.connectionManager&&(at=e.connectionManager),e.useDaemonsHook&&(Bo=e.useDaemonsHook)}function st(e){return Rr(e)}function is(e){return $n(e).join(" · ")}function Oo(e){if(e.lastMessagePreview)return e.lastMessagePreview;const s=[...e.messages].reverse().find(n=>!(n!=null&&n._localId))||e.messages[e.messages.length-1],r=as(s==null?void 0:s.content);return r||(e.title?e.title:is(e)||"No messages yet")}function Ho(e,s){const{isReconnecting:r,isConnecting:n}=ks(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function hd(e,s){const r=["Chat",...$n(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function qt(e){return Ho(e)||is(e)}function bd(e){return`${st(e)} · ${Oo(e)}`}function gd(e){const s=En(e)||wt(e);return`${st(e)} — ${et(s)}`}function yd(e){return Vs(e)||"CLI"}function Uo(e){return e.title||Vs(e)||e.routeId}function zo(e){return e?`Remote · ${st(e)||e.workspaceName||"Session"}`:"Remote"}function vd({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:o=!1,isVisible:i=!0}){var R;const{ides:c}=rs(),d=a.useRef(null),{sendCommand:m,sendData:f}=Ct(),[p,x]=a.useState(""),[b,S]=a.useState(!1),[A,u]=a.useState(1),h=a.useRef(!1),y=a.useRef(0),l=a.useRef(!1),j=a.useRef(""),P=a.useRef(null),k=a.useRef(!1),g=a.useRef(null),N=e.tabKey,v=e.sessionId||"",w=e.daemonId||((R=e.routeId)==null?void 0:R.split(":")[0])||e.routeId||"",M=c.find(B=>B.id===w&&B.type==="adhdev-daemon"),T=(M==null?void 0:M.terminalSizingMode)==="fit"?"fit":"measured",$=.6,E=1.15,F=()=>{if(typeof window>"u")return 1;const B=window.innerWidth||0;return B<=360?.68:B<=390?.74:B<=430?.82:B<=480?.9:1},D=()=>{var B,z;y.current=0,l.current=!1,j.current="",P.current=null,k.current=!1,g.current!==null&&(cancelAnimationFrame(g.current),g.current=null),S(!1),(z=(B=r.current)==null?void 0:B.reset)==null||z.call(B)},C=()=>{var B,z;y.current=0,l.current=!1,j.current="",P.current=null,k.current=!1,g.current!==null&&(cancelAnimationFrame(g.current),g.current=null),S(!0),(z=(B=r.current)==null?void 0:B.reset)==null||z.call(B)},V=()=>{var z;if(g.current=null,!i)return;const B=j.current;B&&(j.current="",(z=r.current)==null||z.write(B))},J=B=>{B&&(j.current+=B,i&&g.current===null&&(g.current=requestAnimationFrame(V)))},I=(B,z=0,Z,fe)=>{var Pe,ke,ve,Q,xe;z>0&&y.current>=z||z===0&&l.current||(y.current=z,S(!0),typeof Z=="number"&&typeof fe=="number"&&Z>0&&fe>0&&((ke=(Pe=r.current)==null?void 0:Pe.resize)==null||ke.call(Pe,Z,fe)),(Q=(ve=r.current)==null?void 0:ve.reset)==null||Q.call(ve),B&&((xe=r.current)==null||xe.write(B)))};return a.useEffect(()=>{D()},[v]),a.useEffect(()=>{var z;if(!v)return;const B=((z=at.onRuntimeEvent)==null?void 0:z.call(at,v,Z=>{if(!(!Z||Z.sessionId!==v)){if(Z.type==="runtime_snapshot"){if(!i){P.current={text:Z.text||"",seq:Z.seq||0,cols:Z.cols,rows:Z.rows};return}I(Z.text||"",Z.seq||0,Z.cols,Z.rows);return}if(Z.type==="session_output"){l.current=!0,typeof Z.seq=="number"&&(y.current=Math.max(y.current,Z.seq)),b||S(!0),typeof Z.data=="string"&&J(Z.data);return}if(Z.type==="session_cleared"){if(!i){k.current=!0,j.current="",P.current=null;return}C()}}}))||(()=>{});return()=>{B()}},[w,v,r,i,b]),a.useEffect(()=>{var z,Z,fe;if(!v)return;w&&((z=at.getState)==null?void 0:z.call(at,w))==="connected"&&(S(!0),(Z=at.requestRuntimeSnapshot)==null||Z.call(at,w,v).catch(()=>{}));const B=(fe=at.onStateChange)==null?void 0:fe.call(at,(Pe,ke)=>{var ve;Pe!==w||ke!=="connected"||(S(!0),(ve=at.requestRuntimeSnapshot)==null||ve.call(at,w,v).catch(()=>{}))});return()=>{B==null||B()}},[w,v,r]),a.useEffect(()=>{s&&D()},[s,N,r]),a.useEffect(()=>{x("")},[e.tabKey]),a.useEffect(()=>{const B=()=>{h.current||u(F())};return B(),window.addEventListener("resize",B),()=>window.removeEventListener("resize",B)},[]),a.useEffect(()=>{var z;if(!i){(z=d.current)==null||z.blur();return}k.current&&(k.current=!1,C());const B=P.current;B&&(P.current=null,I(B.text,B.seq,B.cols,B.rows)),j.current&&g.current===null&&(g.current=requestAnimationFrame(V)),requestAnimationFrame(()=>{var Z;(Z=r.current)==null||Z.bumpResize()})},[i]),a.useEffect(()=>()=>{g.current!==null&&(cancelAnimationFrame(g.current),g.current=null)},[]),a.useEffect(()=>{const B=z=>{var fe;const Z=z.detail;Z!=null&&Z.sessionId&&Z.sessionId!==v||b&&((fe=r.current)==null||fe.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",B),()=>{window.removeEventListener("adhdev:fit-cli-terminal",B)}},[b,v,r]),t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[t.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[t.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{h.current=!0,u(B=>Math.max($,Number((B-.1).toFixed(2))))},title:"Shrink terminal viewport",children:"-"}),t.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{h.current=!0,u(B=>Math.min(E,Number((B+.1).toFixed(2))))},title:"Increase terminal viewport",children:"+"})]}),t.jsx("div",{className:"w-full h-full overflow-auto rounded-lg",children:t.jsx("div",{style:{width:`${100/A}%`,height:`${100/A}%`,transform:`scale(${A})`,transformOrigin:"top left"},children:t.jsx(No,{ref:r,readOnly:!b||!i,sizingMode:T,onInput:B=>{b&&(f!=null&&f(w,{type:"pty_input",targetSessionId:v,data:B})||m(w,"pty_input",{targetSessionId:v,data:B}).catch(console.error))}})})}),!b&&t.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:"Runtime terminal unavailable"})]}),t.jsx("div",{className:"px-3 py-2 bg-[var(--surface-primary)] border-t border-border-subtle shrink-0",children:t.jsxs("div",{className:"flex gap-2.5 items-center",children:[t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:d,type:"text",placeholder:`Send message to ${st(e)}...`,value:p,disabled:!b||!i||o,onChange:B=>x(B.target.value),onPaste:B=>{const z=B.clipboardData.getData("text");z&&x(Z=>Z+z),B.preventDefault()},onKeyDown:B=>{if(B.key!=="Enter")return;if(B.nativeEvent.isComposing){B.preventDefault();return}B.preventDefault();const z=p.trim();!b||!z||o||(x(""),n(z))},className:"w-full h-9 rounded-[18px] px-4 bg-bg-secondary text-[13px] text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),t.jsx("button",{onClick:()=>{const B=p.trim();!b||!B||o||(x(""),n(B))},disabled:!b||!i||!p.trim()||o,className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${p.trim()&&!o?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:p.trim()&&!o?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:p.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})]})}function wd({wsStatus:e,showReconnected:s,loginUrl:r}){const n=e==="disconnected"||e==="reconnecting"||e==="offline"||e==="auth_failed",o=e==="auth_failed"?"red":e==="offline"?"orange":"accent",i={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},c={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},d={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"};return t.jsxs(t.Fragment,{children:[n&&t.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5 justify-center",style:{background:i[o],borderBottom:c[o],color:d[o]},children:[t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),e==="offline"&&"Network offline — waiting for connection...",e==="disconnected"&&"Reconnecting to server...",e==="reconnecting"&&"Reconnecting to server...",e==="auth_failed"&&(r?t.jsxs(t.Fragment,{children:["Session expired."," ",t.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — please restart the server.")]}),s&&e==="connected"&&t.jsxs("div",{className:"py-2 px-4 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-b border-green-500/15 animate-[fadeIn_0.3s_ease]",children:[t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})]})}function jd({terminalBackend:e,isStandalone:s=!1,machineLabel:r,machineKey:n}){const o=a.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[i,c]=a.useState(!1);if(a.useEffect(()=>{if(!o){c(!1);return}try{c(localStorage.getItem(o)==="1")}catch{c(!1)}},[o]),!s||!e||e.backend!=="xterm"||i)return null;const d=(r==null?void 0:r.trim())||"This machine",m=()=>{if(o)try{localStorage.setItem(o,"1")}catch{}c(!0)};return t.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5",style:{background:"linear-gradient(90deg, rgba(245,158,11,0.12), rgba(245,158,11,0.04))",borderBottom:"1px solid rgba(245,158,11,0.2)",color:"#d97706"},children:[t.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[t.jsxs("span",{children:[d," is using `xterm` fallback."]}),t.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),t.jsx("button",{type:"button",onClick:m,className:"shrink-0 text-[12px] font-semibold px-2 py-1 rounded-md transition-colors",style:{color:"#b45309",background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.18)"},"aria-label":"Dismiss terminal backend warning",title:"Dismiss",children:"Dismiss"})]})}function Kn({mode:e,onChange:s,compact:r=!1}){const n=r?14:15;return t.jsx("button",{type:"button",onClick:()=>s(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:e==="chat"?"Switch to Terminal view":"Switch to Chat view",children:e==="chat"?t.jsx(Mr,{size:n}):t.jsx(Kt,{size:n})})}function kd(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Date.parse(e);if(Number.isFinite(s))return s}return 0}function Ht(e){const s=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1];return e.lastMessageAt||kd(s==null?void 0:s.receivedAt)||0}function gn(e,s=0){return Ht(e)||e.lastUpdated||s||0}function Fo(e){return Ht(e)||e.lastUpdated||0}function kr(e,s,r=Fo){const n=r(s)-r(e);if(n!==0)return n;const o=(e.machineName||"").localeCompare(s.machineName||"");if(o!==0)return o;const i=e.displayPrimary.localeCompare(s.displayPrimary);if(i!==0)return i;const c=e.displaySecondary.localeCompare(s.displaySecondary);return c!==0?c:e.tabKey.localeCompare(s.tabKey)}function yn(e){var r;const s=bt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function Nd(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!yn(e)&&!e.title.trim()}function Sd(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(yn(r))-Number(yn(s));if(n!==0)return n;const o=r.messages.length-s.messages.length;return o!==0?o:kr(s,r)})[0]||null}function Lt(e,s){const r=e.filter(c=>c.routeId===s);if(r.length===0)return null;const n=r.find(c=>c.streamSource==="native")||null,o=r.filter(c=>c.streamSource==="agent-stream"),i=Sd(o);return n?i&&Nd(n)?i:n:i||r[0]||null}function Ma({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function _a({conversation:e,isAttention:s,shortcutIndex:r,onClick:n}){const o=$n(e),i=Rn(Ht(e)),c=[...o,i].filter(Boolean);return t.jsxs("button",{type:"button",className:`dashboard-header-inbox-item ${s?"is-attention":""}`.trim(),onClick:n,children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:Rr(e)}),(r||c.length>0)&&t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[r?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",r]}):null,c.join(" · ")]})]})}function Cd({activeConv:e,agentCount:s,wsStatus:r,isConnected:n,conversations:o,onOpenHistory:i,onOpenRemote:c,onStopCli:d,activeCliViewMode:m,onSetCliViewMode:f,onOpenConversation:p,onHideConversation:x,hiddenConversations:b=[],onShowConversation:S,onShowAllHidden:A,onResetPanelsToMain:u,inboxOpen:h,onInboxOpenChange:y,hiddenOpen:l,onHiddenOpenChange:j,onOpenNewSession:P,actionShortcuts:k}){const{ides:g,p2pStates:N={}}=rs(),v=!!e&&Ye(e)&&!Ve(e),w=!!e&&Ve(e),M=m||(e?Ro(e)?"terminal":"chat":null),[T,$]=a.useState(!1),E=a.useRef(null),F=a.useRef(null),D=n?"#22c55e":r==="connected"?"#eab308":"#ef4444",C=n?"0 0 4px #22c55e80":r==="connected"?"0 0 4px #eab30880":"0 0 4px #ef444480",V=g.filter(W=>W.type==="adhdev-daemon"),J=a.useMemo(()=>Fs(g),[g]),I=Object.values(N),R=I.filter(W=>W==="connected").length,B=I.filter(W=>W==="connecting"||W==="new"||W==="checking").length,Z=r!=="connected"||V.length===0?null:B>0&&R===0?"P2P connecting...":R>0&&s===0?"Waiting for IDE...":null,fe=a.useMemo(()=>o.filter(W=>!il(W,o,J)),[o,J]),Pe=a.useMemo(()=>fe.filter(W=>Os(W,J).requiresAction).sort(kr),[fe,J]),ke=a.useMemo(()=>fe.filter(W=>{const ee=(e==null?void 0:e.tabKey)===W.tabKey;return Os(W,J,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ee}).unread}).sort(kr),[e,fe,J]),ve=a.useMemo(()=>[...Pe,...ke].slice(0,9),[Pe,ke]),Q=Pe.length+ke.length;a.useEffect(()=>{if(!h)return;const W=ee=>{var ne;(ne=E.current)!=null&&ne.contains(ee.target)||y(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[h,y]),a.useEffect(()=>{if(!l)return;const W=ee=>{var ne;(ne=F.current)!=null&&ne.contains(ee.target)||j(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[l,j]),a.useEffect(()=>{if(!l&&!h)return;const W=ee=>{if(!ee.altKey)return;const ne=ee.code.match(/^Digit([1-9])$/);if(!ne)return;const oe=Number(ne[1])-1,he=l?b[oe]:void 0,te=h?ve[oe]:void 0,de=he||te;if(de){if(ee.preventDefault(),ee.stopPropagation(),he){S==null||S(he),j(!1);return}p==null||p(de),y(!1)}};return window.addEventListener("keydown",W,!0),()=>window.removeEventListener("keydown",W,!0)},[b,l,h,ve,j,y,p,S]);const xe=W=>{if(!W)return;const ee=o.find(ne=>ne.tabKey===W);ee&&(x==null||x(ee))};return t.jsxs("div",{className:"dashboard-header",children:[t.jsx("div",{className:"flex items-center gap-3",children:t.jsx("div",{className:"header-title-block",children:t.jsxs("div",{className:"header-title-row",children:[t.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[t.jsx(Kt,{size:18}),t.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),t.jsx("span",{className:"header-title-mobile",children:e?st(e):"Dashboard"}),t.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:t.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:D,boxShadow:C}})})]}),t.jsxs("div",{className:"header-subtitle flex items-center",children:[t.jsx("span",{title:n?"Connected":r==="connected"?"Partial":"Disconnected",className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:D,boxShadow:C}}),Z&&t.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",Z]}),P&&t.jsx("button",{type:"button",onClick:P,className:"btn btn-secondary btn-sm ml-2",title:"Start or recover a session","aria-label":"Start or recover a session",children:t.jsx(Ac,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(v||w||!Ve(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:is(e)||st(e),children:st(e)}),(v||w)&&d&&t.jsxs(t.Fragment,{children:[v&&f&&M&&t.jsx(Kn,{mode:M,onChange:f,compact:!0}),t.jsx("button",{onClick:()=>d(e),className:"btn btn-secondary btn-sm",title:w?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:t.jsx(vt,{size:14})})]}),!Ve(e)&&t.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:t.jsx(Mn,{size:14})}),!v&&!Ve(e)&&t.jsx("button",{onClick:c,className:"btn btn-secondary btn-sm",title:"Remote Control",children:t.jsx(kt,{size:14})})]}),t.jsxs("div",{className:"dashboard-header-inbox",ref:E,children:[t.jsxs("div",{className:`dashboard-header-hidden${T?" is-drop-target":""}`,ref:F,onDragEnter:W=>{W.dataTransfer.types.includes("text/tab-key")&&(W.preventDefault(),$(!0))},onDragOver:W=>{W.dataTransfer.types.includes("text/tab-key")&&(W.preventDefault(),W.dataTransfer.dropEffect="move",$(!0))},onDragLeave:W=>{W.currentTarget.contains(W.relatedTarget)||$(!1)},onDrop:W=>{const ee=W.dataTransfer.getData("text/tab-key");W.preventDefault(),$(!1),xe(ee)},children:[t.jsxs("button",{type:"button",onClick:()=>j(!l),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${k!=null&&k.toggleHiddenTabs?` (${k.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[t.jsx(vo,{size:16}),b.length>0&&t.jsx("span",{className:"dashboard-header-hidden-badge",children:b.length})]}),l&&t.jsxs("div",{className:"dashboard-header-hidden-popover",children:[t.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[t.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),t.jsx(Ma,{value:k==null?void 0:k.toggleHiddenTabs})]}),t.jsxs("div",{className:"dashboard-header-hidden-actions",children:[u&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u,children:"Reset panels"}),b.length>0&&A&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{A(),j(!1)},children:"Restore all"})]})]}),e&&x&&t.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>x(e),children:[t.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[t.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),t.jsx(Ma,{value:k==null?void 0:k.hideCurrentTab})]}),t.jsx("span",{className:"dashboard-header-hidden-current-title",children:st(e)})]}),b.length>0?t.jsx("div",{className:"dashboard-header-hidden-list",children:b.map(W=>t.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{S==null||S(W),j(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:st(W)}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[b.indexOf(W)<9?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",b.indexOf(W)+1]}):null,is(W)]})]},W.tabKey))}):t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),t.jsxs("button",{type:"button",onClick:()=>y(!h),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[t.jsx(_r,{size:16}),Q>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:Q})]}),h&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[Pe.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Needs attention"}),Pe.map(W=>t.jsx(_a,{conversation:W,isAttention:!0,shortcutIndex:ve.indexOf(W)>=0?ve.indexOf(W)+1:void 0,onClick:()=>{p==null||p(W),y(!1)}},W.tabKey))]}),ke.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Task complete"}),ke.map(W=>t.jsx(_a,{conversation:W,shortcutIndex:ve.indexOf(W)>=0?ve.indexOf(W)+1:void 0,onClick:()=>{p==null||p(W),y(!1)}},W.tabKey))]}),Q===0&&t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function Nr(e){return e?"Resume saved history":"Start fresh"}function Wn(e){return e?"Resuming saved history…":"Starting fresh…"}function Vo(){return"Start fresh"}function Id(){return"Recover hosted runtime"}function Go(){return"Open saved history"}function Td(){return"Saved History"}function Ad(){return"No saved history found yet."}function Md(){return"Refresh saved history"}function _d(){return"Refreshing saved history…"}function Yt(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function Xt(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 Jt(e){return e==="start-fresh"?"Start fresh":"Restart"}function Zt(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function qo(e){return`Resume saved history with ${e}?`}function Yo(){return"Review or change the target workspace before resuming saved history."}function Pd(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 On({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:o=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,onClose:d,onNewChat:m,onSwitchSession:f,onRefreshHistory:p,onResumeSavedSession:x}){var y;const b=s.find(l=>l.id===e.routeId),S=(b==null?void 0:b.chats)||[],A=(y=b==null?void 0:b.activeChat)==null?void 0:y.id,u=Ye(e)&&!Ve(e),h=t.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-center justify-center",children:[t.jsx("div",{onClick:d,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),t.jsxs("div",{className:"card fade-in relative w-[90%] max-w-[500px] max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[20px]",children:[t.jsxs("div",{className:"px-6 py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)]",children:[t.jsxs("div",{children:[t.jsx("h3",{className:"m-0 text-lg font-extrabold",children:u?Td():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:gd(e)})]}),t.jsx("button",{onClick:d,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:t.jsx(vt,{size:16})})]}),t.jsxs("div",{className:"flex-1 overflow-y-auto p-3 bg-bg-primary",children:[!u&&t.jsx("button",{onClick:m,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),u?t.jsx(t.Fragment,{children:o.map(l=>{const j=e.providerSessionId===l.providerSessionId,P=j||!l.canResume||!!c;return t.jsxs("button",{type:"button",onClick:()=>{P||!x||x(l)},disabled:P,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${j?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${P?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:`font-bold text-sm mb-1 truncate ${j?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:l.title||"Untitled Session"}),t.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:l.providerSessionId})]}),t.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Pd(l.lastMessageAt)})]}),t.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:l.preview||"No saved preview yet"}),t.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[t.jsxs("div",{className:"truncate",children:[l.workspace||"Workspace unknown",l.currentModel?` · ${l.currentModel}`:"",l.messageCount>0?` · ${l.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:j?"ACTIVE":l.canResume?c===l.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},l.id)})}):S.map(l=>t.jsxs("div",{onClick:()=>{f(e.routeId,l.id),d()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${A===l.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[t.jsx("div",{className:`font-bold text-sm mb-1 ${A===l.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:l.title||"Untitled Session"}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[l.id.substring(0,12),"..."]}),A===l.id&&t.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},l.id)),(u&&!i&&o.length===0||!u&&S.length===0)&&t.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[t.jsx("div",{className:"text-3xl mb-3 opacity-60",children:t.jsx(Rc,{size:32})}),t.jsx("div",{className:"text-[13px]",children:u?Ad():"No recent chat sessions found."})]}),u&&i&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:_d()})})]}),t.jsx("div",{className:"px-5 py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right",children:t.jsx("button",{onClick:p,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(js,{size:13})," ",u?Md():"Refresh History"]})})})]})]});return typeof document>"u"?h:Bs.createPortal(h,document.body)}const Pa={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 Xo({toasts:e,onDismiss:s,onClickToast:r}){return t.jsx("div",{className:"fixed right-4 z-[9999] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(n=>{const o=Pa[n.type]||Pa.info;return t.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=n.actions)!=null&&i.length||r&&r(n)},children:[t.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${o.accent}, color-mix(in srgb, ${o.accent} 55%, transparent))`}}),t.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),s(n.id)},"aria-label":"Dismiss",children:t.jsx(vt,{size:14})}),t.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[t.jsx("div",{className:"flex items-center gap-2 pr-8",children:t.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:o.chipBg,color:o.chipText,border:`1px solid color-mix(in srgb, ${o.accent} 22%, transparent)`},children:o.label})}),t.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&t.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((i,c)=>t.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:d=>{d.stopPropagation(),i.onClick(),s(n.id)},children:i.label},c))})]})]},n.id)})})}const Rd=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Ld(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function Dd(e){return e.sessionId||e.instanceId||e.agentType}function Yr(e,s){return e||s}function Ra(e,s){const r=new Set,n=[];for(const o of s)if(o)for(const i of e[o]||[]){const c=i._localId||`${i.role}:${i.timestamp}:${i.content}`;r.has(c)||(r.add(c),n.push(i))}return n.sort((o,i)=>o.timestamp-i.timestamp)}function Jo(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=jt(r,{fallbackId:r.id}));return s}function Zo(e,s={}){var n,o;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((o=s.machineNames)==null?void 0:o[e.daemonId])||void 0,connectionState:s.connectionStates?s.connectionStates[r]||s.defaultConnectionState||"new":s.defaultConnectionState}}function Hn(e,s,r={}){return Ed(e,s,Zo(e,r))}function Ed(e,s,r={}){var b,S,A,u,h,y;const n=[],o=r.machineName,i=r.connectionState,c=Ld(e),d=et(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(l=>{var j,P;return{sessionId:l.id,instanceId:l.id,providerSessionId:l.providerSessionId,transport:l.transport,agentType:l.providerType,agentName:l.providerName||et(l.providerType),status:l.status,title:l.title,lastMessagePreview:l.lastMessagePreview,lastMessageRole:l.lastMessageRole,lastMessageAt:l.lastMessageAt,lastMessageHash:l.lastMessageHash,messages:((j=l.activeChat)==null?void 0:j.messages)||[],activeModal:((P=l.activeChat)==null?void 0:P.activeModal)||void 0,unread:l.unread,lastSeenAt:l.lastSeenAt,lastUpdated:l.lastUpdated,inboxBucket:l.inboxBucket,surfaceHidden:l.surfaceHidden}}):[],f=Rd(e),p=e.activeChat||{title:""},x=p.title&&String(p.title).trim()?String(p.title).trim():"";if(f){const l=e.sessionId||e.instanceId,j=ba(e.type),P=(b=e.activeChat)==null?void 0:b.activeModal,k=P&&Array.isArray(P.buttons)&&P.buttons.length>0,g=bt((S=e.activeChat)==null?void 0:S.status,{activeModal:(A=e.activeChat)==null?void 0:A.activeModal})||bt((h=(u=e.agents)==null?void 0:u[0])==null?void 0:h.status)||"idle",N=e.activeChat||{title:"",messages:[]};let v=N.title&&String(N.title).trim()?String(N.title).trim():"";const w=(y=e.activeChat)==null?void 0:y.id,M=e.chats;if(w&&Array.isArray(M)&&M.length>0){const C=M.find(V=>V.id===w||V.id&&String(V.id)===String(w));C!=null&&C.title&&String(C.title).trim()&&(v=String(C.title).trim())}const T=(Ye(e)||Ve(e),e.type),$=(Ye(e)||Ve(e))&&ga(v,j,T)?"":v,E=N.messages||[],F=Ra(s,[e.id,l]),D=Ia(E,F);n.push({routeId:e.id,sessionId:l,providerSessionId:e.providerSessionId,nativeSessionId:l,transport:e.transport,daemonId:e.daemonId||void 0,mode:Ye(e)?e.mode||"terminal":"chat",agentName:j,agentType:T,status:g,title:$,messages:[...E,...D],resume:e.resume,hostIdeType:!Ye(e)&&!Ve(e)?e.type:void 0,workspaceName:c,displayPrimary:c||$||(Ye(e)?e.mode==="chat"?j:"Terminal":j),displaySecondary:d,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:k?P.buttons:void 0,modalMessage:k?P.message:void 0,streamSource:"native",tabKey:Yr(l,e.id),machineName:o,connectionState:i})}if(f&&(Ye(e)||Ve(e)))return n;for(const l of m){const j=l.activeModal&&Array.isArray(l.activeModal.buttons)&&l.activeModal.buttons.length>0,P=xl(l),k=Dd(l),g=`${e.id}:${k}`,N=l.title&&String(l.title).trim()||"",v=ga(N,l.agentName,l.agentType)?"":N,w=l.messages||[],M=Ra(s,[g,l.sessionId,l.instanceId]),T=Ia(w,M);(l.transport==="cdp-webview"||l.sessionId||l.providerSessionId||w.length>0||T.length>0||j||v||!["idle","panel_hidden","disconnected","not_monitored"].includes(P))&&n.push({routeId:e.id,sessionId:l.sessionId||l.instanceId,providerSessionId:l.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:l.transport||"cdp-webview",daemonId:e.daemonId||void 0,mode:"chat",agentName:l.agentName,agentType:l.agentType,status:P,title:v,messages:[...w,...T],hostIdeType:e.type,workspaceName:c,displayPrimary:c||x||v||d,displaySecondary:`${d} · ${l.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:l.lastMessagePreview,lastMessageRole:l.lastMessageRole,lastMessageAt:l.lastMessageAt,lastMessageHash:l.lastMessageHash,lastUpdated:l.lastUpdated||e.lastUpdated,modalButtons:j?l.activeModal.buttons:void 0,modalMessage:j?l.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Yr(l.sessionId||l.instanceId,g),machineName:o,connectionState:i})}return n.length===0&&n.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,mode:"chat",agentName:ba(e.type),agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:c,displayPrimary:c||d,displaySecondary:d,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Yr(e.sessionId||e.instanceId,e.id),connectionState:i}),n}function $d(e){const s=e.split(":");return s.length>=3&&(s[1]==="ide"||s[1]==="cli"||s[1]==="acp")?{daemonId:s[0],targetSessionId:s.slice(2).join(":")||void 0}:{daemonId:e}}function Bd(e,s){const r=$d(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Qo=[{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:"🏄"}],ei=[{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:"🧩"}],ti=[{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:"🟠"}],Kd=Qo,Wd=ei,Od=ti;function cs(...e){return nc(ac(e))}function Hd({icon:e,title:s,subtitle:r,badge:n,actions:o,className:i}){return t.jsxs("div",{className:cs("dashboard-header",i),children:[t.jsxs("div",{children:[t.jsxs("h1",{className:"header-title flex items-center gap-2",children:[t.jsx("span",{className:"flex items-center text-lg",children:e})," ",s,n&&t.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[n.count!==void 0?n.count:""," ",n.text]})]}),r&&t.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),o&&t.jsx("div",{className:"flex gap-2",children:o})]})}function si({icon:e,title:s,subtitle:r,badge:n,actions:o,widthClassName:i="max-w-6xl",contentClassName:c,children:d}){return t.jsxs("div",{className:"flex flex-col h-full",children:[t.jsx(Hd,{icon:e,title:s,subtitle:r,badge:n,actions:o}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:cs("mx-auto flex w-full flex-col gap-4",i,c),children:d})})]})}function Mt({title:e,icon:s,description:r,accentColor:n,className:o,children:i}){return t.jsxs("div",{className:cs("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]",o),style:n?{borderLeftColor:n}:void 0,children:[(e||r)&&t.jsxs("div",{className:"mb-4",children:[e&&t.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[s&&t.jsx("span",{className:"mr-1.5",children:s}),e]}),r&&t.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),i]})}function ri({icon:e,title:s,description:r,action:n,className:o}){return t.jsxs("div",{className:cs("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",o),children:[t.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),t.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:s}),t.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const Ud={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"},zd={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Fd({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:cs("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Ud[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:zd[e]}),t.jsx("span",{children:s})]}),r&&t.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}const Vd={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"},Gd={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function qd({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:cs("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Vd[e],r),children:[t.jsx("span",{className:cs("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Gd[e])}),n]})}const vn="adhdev:themechange";function Yd(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function ms(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function ps(e){return e==="system"?Yd():e}function ni(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function xr(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(vn,{detail:{preference:e,theme:s}}))}function Xd(){const e=ms(),s=ps(e);ni(s),xr(e,s)}function Un(){const[e,s]=a.useState(ms),[r,n]=a.useState(()=>ps(ms()));a.useEffect(()=>{ni(r)},[r]),a.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),d=m=>{if(e==="system"){const f=m.matches?"light":"dark";n(f),xr("system",f)}};return c.addEventListener("change",d),()=>c.removeEventListener("change",d)},[e]),a.useEffect(()=>{const c=m=>{const f=m.detail||{},p=f.preference,x=f.theme;s(p==="dark"||p==="light"||p==="system"?p:ms()),n(x==="dark"||x==="light"?x:ps(ms()))},d=m=>{if(m.key!=="theme")return;const f=ms(),p=ps(f);s(f),n(p)};return window.addEventListener(vn,c),window.addEventListener("storage",d),()=>{window.removeEventListener(vn,c),window.removeEventListener("storage",d)}},[]);const o=a.useCallback(c=>{const d=ps(c);s(c),n(d);try{localStorage.setItem("theme",c)}catch{}xr(c,d)},[]),i=a.useCallback(()=>{s(c=>{const d=c==="dark"?"light":c==="light"?"system":"dark",m=ps(d);n(m);try{localStorage.setItem("theme",d)}catch{}return xr(d,m),d})},[]);return{theme:r,preference:e,setPreference:o,cycleTheme:i,isDark:r==="dark"}}const La={dark:"Dark",light:"Light",system:"System"};function Jd({collapsed:e}){const{preference:s,cycleTheme:r}=Un(),n=s==="dark"?t.jsx(Dc,{size:16}):s==="light"?t.jsx(Lc,{size:16}):t.jsx(Ec,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${La[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:La[s]})]})}function Gt({label:e,description:s,checked:r,disabled:n,onChange:o,extra:i}){return t.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[t.jsxs("div",{className:"pr-4",children:[t.jsx("div",{className:"font-medium text-sm",children:e}),t.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:s})]}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,t.jsxs("button",{type:"button",role:"switch","aria-checked":r,"aria-disabled":n,disabled:n,onClick:()=>o(!r),className:`relative inline-flex items-center ${n?"cursor-not-allowed":"cursor-pointer"}`,children:[t.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:r?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),t.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${r?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function Zd({onPrefChange:e}){const[s,r]=Sl(),n=(o,i)=>{r({[o]:i}),e==null||e(o,i)};return t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(Gt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(_r,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:o=>n("globalEnabled",o)}),s.globalEnabled&&t.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&t.jsx(Gt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(kt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:o=>n("browserNotifications",o)}),s.globalEnabled&&s.browserNotifications&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.jsx(Gt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx($c,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:o=>n("completionAlert",o)}),t.jsx(Gt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Bc,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:o=>n("approvalAlert",o)}),t.jsx(Gt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ks,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:o=>n("disconnectAlert",o)})]}),!s.globalEnabled&&t.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function Sr(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function Qd(e,s){const r=Sr(e),n=Sr(s);if(!r||!n)return e.localeCompare(s);for(let o=0;o<3;o+=1){if(r[o]<n[o])return-1;if(r[o]>n[o])return 1}return 0}function ai(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function Ds(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||Qd(r,s)>=0)return!1;const n=Sr(r),o=Sr(s);return!n||!o?!1:n[0]!==o[0]||n[1]!==o[1]}function eu(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Xr(e,s){return e instanceof Error?e.message:s}function tu({ides:e,emptyMessage:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o}){const i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?t.jsx(ri,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:"No machines connected",description:s||"Install ADHDev on a machine and sign in to connect it here."}):t.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>t.jsx(ru,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o},c.id))})}function Da({title:e,message:s,confirmLabel:r,confirmColor:n,onConfirm:o,onCancel:i}){const c=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return Bs.createPortal(t.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:d=>d.stopPropagation(),children:[t.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),t.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:s}),t.jsxs("div",{className:"flex gap-2 justify-end",children:[t.jsx("button",{onClick:i,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:"Cancel"}),t.jsx("button",{onClick:o,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 su(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Kd,...Wd,...Od].find(o=>o.id===s||s.includes(o.id)||o.id.includes(s));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function ru({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o}){var F,D;const[i,c]=a.useState("idle"),[d,m]=a.useState(""),[f,p]=a.useState(null),[x,b]=a.useState("idle"),[S,A]=a.useState(""),u=e.version||null,h=((F=e.machine)==null?void 0:F.platform)||((D=e.system)==null?void 0:D.platform)||"",y=jt(e,{fallbackId:e.id}),l=h==="win32"?"🪟":h==="darwin"?"🍎":"🐧",j=s.filter(C=>C.daemonId===e.id&&C.transport==="cdp-page"),P=s.filter(C=>C.daemonId===e.id&&C.transport==="pty"),k=s.filter(C=>C.daemonId===e.id&&C.transport==="acp"),g=e.p2p,N=async()=>{if(r){c("upgrading"),m("Starting upgrade...");try{const C=eu(await r(e.id,"daemon_upgrade",{}));C.alreadyLatest?(c("done"),m(`Already on v${C.version||"latest"}.`)):C.upgraded||C.success?(c("done"),m(`Upgrade to v${C.version||"latest"} started. Daemon is restarting...`)):(c("error"),m(C.error||"Upgrade failed"))}catch(C){c("error"),m(Xr(C,"Connection lost during upgrade"))}}},v=async()=>{if(p(null),!!n){b("loading");try{await n(e.id),b("done"),A("Machine disconnected.")}catch(C){b("error"),A(Xr(C,"Failed to disconnect"))}}},w=async()=>{if(p(null),!!o){b("loading");try{await o(e.id),b("done"),A("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(C){b("error"),A(Xr(C,"Failed to revoke token"))}}},M="0.8.54",T=ai(e,M),$=Ds(e,M),E=j.length+P.length+k.length;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("span",{className:"text-xl",children:l}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-sm",children:y}),t.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[t.jsxs("span",{children:[e.id.substring(0,12),"…"]}),u&&t.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${T?"":"bg-bg-secondary"}`,style:T?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",u,!T&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&T&&t.jsx("button",{onClick:N,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${M}`,children:i==="upgrading"?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${$?"↑ Update now":`↑ Update${` to v${M}`}`}`}),n&&t.jsx("button",{onClick:()=>p("disconnect"),disabled:x==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),o&&t.jsx("button",{onClick:()=>p("revoke"),disabled:x==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),t.jsx(qd,{status:e.status==="online"?"online":"error"})]})]}),t.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[g&&t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${g.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${g.state==="connecting"||g.state==="new"?"animate-pulse":""}`,style:g.state==="connecting"||g.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",g.state==="connected"?"connected":g.state==="connecting"||g.state==="new"?"connecting...":g.state||"off"]}),g.peers!==void 0&&g.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",g.peers," peer",g.peers!==1?"s":"",")"]})]}),g&&E>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),E>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[j.map(C=>{const V=su(C.type),J=C.cdpConnected;return t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:V.icon}),t.jsx("span",{children:V.name}),J!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${J?"bg-green-400":"animate-pulse"}`,style:J?void 0:{background:"var(--status-warning)"},title:J?"CDP connected":"CDP connecting..."})]},C.id)}),P.map(C=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"⌨️"}),t.jsx("span",{children:C.cliName||"CLI"})]},C.id)),k.map(C=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"🔗"}),t.jsx("span",{children:C.cliName||"ACP"})]},C.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(d||S)&&t.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||x==="error"?"text-red-400":i==="done"||x==="done"?"text-green-400":"text-text-muted"}`,children:S||d})]}),f==="disconnect"&&t.jsx(Da,{title:"🔌 Disconnect Machine",message:`Disconnect "${y}" from ADHDev?
31
+ `)))return}const C=(c==null?void 0:c[D.id])??S[D.id];try{const V=await g(D.invokeScript),J=Zs(V);if(J&&!J.ok||Qs(V))throw new Error((J==null?void 0:J.error)||Cs(V)||`Could not run ${D.label}`);J&&v(D,C??!0,J)}catch(V){w(D,C);const J=V instanceof Error?V.message:`Could not run ${D.label}`;tt.showToast(J,"warning")}};return t.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1 flex-wrap text-[10px] border-t border-border-subtle bg-surface-primary font-[var(--font)]",children:[t.jsx("span",{className:"text-[9px] font-bold tracking-wide opacity-70",style:{color:f},children:o}),t.jsx("span",{className:"text-border-subtle text-[10px]",children:"│"}),N.map(D=>{const C=String(A[D.id]||""),V=Ul(D,u,C),J=y===D.id,I=j===D.id,R=fr(D,u);switch(D.type){case"select":return t.jsxs("div",{className:"relative",children:[t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all bg-[var(--surface-tertiary)] whitespace-nowrap max-w-40 overflow-hidden text-ellipsis",style:{borderColor:J?`${f}55`:"transparent",border:"1px solid",color:C?"var(--text-primary)":"var(--text-muted)"},onClick:()=>M(D),children:[D.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:D.icon}),I?"...":V||D.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),J&&R.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>l(null)}),t.jsxs("div",{className:"absolute bottom-full left-0 z-[60] bg-[var(--surface-primary)] border border-border-subtle rounded-lg mb-1 max-h-[220px] overflow-y-auto min-w-40 shadow-[0_-4px_16px_rgba(0,0,0,0.3)]",children:[t.jsx("div",{className:"px-3 py-1.5 text-[9px] font-bold text-text-muted tracking-wider border-b border-border-subtle",children:D.label.toUpperCase()}),R.map(B=>t.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:B.value===C?`${f}18`:"transparent",color:B.value===C?f:"var(--text-secondary)",fontWeight:B.value===C?600:400,borderLeft:B.value===C?`2px solid ${f}`:"2px solid transparent"},title:B.description||B.label,onMouseEnter:z=>{z.currentTarget.style.background=`${f}12`},onMouseLeave:z=>{z.currentTarget.style.background=B.value===C?`${f}18`:"transparent"},onClick:()=>T(D,B.value),children:B.label},B.value))]})]})]},D.id);case"cycle":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all bg-[var(--surface-tertiary)] whitespace-nowrap",style:{border:"1px solid transparent",color:C?"var(--text-primary)":"var(--text-muted)"},onClick:()=>$(D),title:`Click to cycle: ${R.map(B=>B.label).join(" → ")}`,children:[D.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:D.icon}),V||D.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"⟳"})]},D.id);case"toggle":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all whitespace-nowrap",style:{border:"1px solid",borderColor:C?`${f}44`:"transparent",background:C?`${f}14`:"var(--surface-tertiary)",color:C?f:"var(--text-muted)"},onClick:()=>E(D),children:[D.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:D.icon}),D.label]},D.id);case"action":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all hover:bg-[var(--surface-tertiary-hover)] whitespace-nowrap",style:{border:"1px solid var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>F(D),children:[D.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:D.icon}),D.resultDisplay==="inline"&&C?`${D.label}: ${C}`:D.label]},D.id);case"display":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium whitespace-nowrap",style:{border:"1px solid var(--border-default)",background:"var(--surface-tertiary)",color:C?"var(--text-primary)":"var(--text-muted)"},children:[D.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:D.icon}),C?`${D.label}: ${C}`:D.label]},D.id);default:return null}})]})}const Vl=a.memo(function({contextKey:s,panelLabel:r,isSending:n,onSend:o,isActive:i=!0}){const c=a.useRef(null),[d,m]=a.useState("");a.useEffect(()=>{m("")},[s]),a.useEffect(()=>{var p;i&&((p=c.current)==null||p.focus())},[s,i]);const f=()=>{const p=d.trim();!p||n||(m(""),o(p))};return t.jsx("div",{className:"dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden transition-all duration-200 ease-out",style:{borderTop:i?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:i?72:0,opacity:i?1:0,transform:i?"translateY(0)":"translateY(10px)",padding:i?"10px 12px":"0 12px",pointerEvents:i?"auto":"none"},"aria-hidden":!i,children:t.jsxs("div",{className:"flex gap-2.5 items-center",title:i?`Send message to ${r}`:void 0,children:[t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:c,type:"text",placeholder:`Send message to ${r}...`,value:d,onChange:p=>m(p.target.value),onPaste:p=>{const x=p.clipboardData.getData("text");x&&m(b=>b+x),p.preventDefault()},onKeyDown:p=>{if(p.key==="Enter"){if(p.nativeEvent.isComposing){p.preventDefault();return}p.preventDefault(),f()}},onBlur:p=>{if(window.innerWidth<768){const x=p.relatedTarget;if((x==null?void 0:x.tagName)==="BUTTON")return;setTimeout(()=>{document.documentElement.scrollTop=0},300)}},className:"w-full h-10 rounded-[20px] px-4 bg-bg-secondary text-sm text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),t.jsx("button",{onClick:f,disabled:!d.trim()||n,className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${d.trim()&&!n?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:d.trim()&&!n?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:t.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:d.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})}),Ye=e=>e.transport==="pty",vs=(e,s)=>Ye(e)?e.mode||"terminal":"chat",Ro=(e,s)=>Ye(e)&&vs(e)==="terminal",Ve=e=>e.transport==="acp";function $t(e){return e.streamSource!=="agent-stream"}function Ut(e){var s;return e.daemonId||((s=e.routeId)==null?void 0:s.split(":")[0])||e.routeId||""}function Lo(e){return e.machineName||""}function wr(e){return Ut(e)}function wt(e){return e.agentType||""}function En(e){return e.hostIdeType||""}function Rr(e){return e.displayPrimary||e.agentName||"Agent"}function $n(e){return[e.displaySecondary,Lo(e)].filter(Boolean)}function Vs(e){return e.agentName||et(wt(e))}function Gl(e){var s,r;if(!$t(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return et(En(e)||wt(e))}function Bn(e){return $t(e)?e.sessionId:e.nativeSessionId}function wa(e){return $t(e)?"native":e.tabKey}function ql(e){return e.sessionId}function Yl(e,s){if(s)return $t(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function Xl(e,s){const r=wt(e),n=$t(e)?s!=null&&s.type?et(s.type):et(En(e)||r):Vs(e);return{isNativeConversation:$t(e),isCli:Ye(e),isAcp:Ve(e),isCliTerminal:Ro(e),providerType:r,displayLabel:n,targetEntry:Yl(e,s)}}function Do({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:o=!0}){const i=ws(),c=Ut(e),d=Lo(e),m=e.transport==="cdp-page"||e.transport==="cdp-webview",f=e.streamSource==="agent-stream"&&!!e.agentName,p=!f&&(e.transport==="pty"||e.transport==="acp"),x=Vs(e),b=Gl(e),S=a.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),A=a.useCallback(()=>{if(r){r();return}const u=Bn(e);u&&i(`/dashboard?activeTab=${encodeURIComponent(u)}`)},[e,i,r]);return t.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[m&&(o?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:A,title:b,children:[t.jsx(kt,{size:12}),t.jsx("span",{children:b})]}):t.jsxs("span",{className:"conversation-meta-chip",title:b,children:[t.jsx(kt,{size:12}),t.jsx("span",{children:b})]})),f&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[t.jsx(Ks,{size:12}),t.jsx("span",{children:x})]}),p&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[t.jsx(Ks,{size:12}),t.jsx("span",{children:x})]}),d&&(o?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:S,title:d,children:[t.jsx(Bt,{size:12}),t.jsx("span",{children:d})]}):t.jsxs("span",{className:"conversation-meta-chip",title:d,children:[t.jsx(Bt,{size:12}),t.jsx("span",{children:d})]}))]})}function ja(e,s){return`${e}:${s}`}function Jl(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function er(e,s){Jl()&&console.debug(`[subscription-manager] ${e}`,s)}class Zl{constructor(){lt(this,"active",new Map)}subscribe(s,r,n,o){var f;const i=ja(n.topic,n.key),c=this.active.get(i);let d=!0;if(c)c.handlers.add(o),c.lastUpdate&&o(c.lastUpdate);else{const p={daemonId:r,request:n,handlers:new Set([o])};this.active.set(i,p),er("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((f=s.sendData)==null?void 0:f.call(s,r,n))??!1}const m=()=>{var b;const p=this.active.get(i);if(!p||(p.handlers.delete(o),p.handlers.size>0))return;this.active.delete(i);const x={type:"unsubscribe",topic:n.topic,key:n.key};er("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(b=s.sendData)==null||b.call(s,r,x)};return m.initialSendAccepted=d,m}publish(s){const r=ja(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,ss.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.publish",topic:s.topic,payload:{key:s.key}}),n.handlers.forEach(o=>{o(s),ss.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.handler_invoked",topic:s.topic,payload:{key:s.key}})}))}resubscribeAll(s){var r;er("resubscribe_all",{count:this.active.size,subscriptions:Array.from(this.active.values()).map(n=>({daemonId:n.daemonId,topic:n.request.topic,key:n.request.key}))});for(const n of this.active.values())(r=s.sendData)==null||r.call(s,n.daemonId,n.request)}resubscribeForDaemon(s,r){var o;const n=Array.from(this.active.values()).filter(i=>i.daemonId===s);er("resubscribe_daemon",{daemonId:s,count:n.length,subscriptions:n.map(i=>({topic:i.request.topic,key:i.request.key}))});for(const i of n)(o=r.sendData)==null||o.call(r,i.daemonId,i.request)}}const Ot=new Zl;function Ql(e,s){const r=new Map;for(const n of e||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===s&&n.sessionId){r.set(n.sessionId,{parentSessionId:n.parentSessionId,providerSessionId:n.providerSessionId,workspace:n.workspace??null,sessionCapabilities:n.sessionCapabilities,cdpConnected:n.cdpConnected,currentModel:n.currentModel,currentPlan:n.currentPlan,currentAutoApprove:n.currentAutoApprove,controlValues:n.controlValues,providerControls:n.providerControls,acpConfigOptions:n.acpConfigOptions,acpModes:n.acpModes,runtimeWriteOwner:n.runtimeWriteOwner,runtimeAttachedClients:n.runtimeAttachedClients,cliName:n.cliName,type:n.type,status:n.status,lastMessagePreview:n.lastMessagePreview,lastMessageRole:n.lastMessageRole,lastMessageAt:n.lastMessageAt,lastMessageHash:n.lastMessageHash});for(const i of n.childSessions||[]){if(!(i!=null&&i.id))continue;const c=r.get(i.id)||{};r.set(i.id,{...c,...i})}}return r}function tr(e,s){return{...e,parentId:e.parentId??(s==null?void 0:s.parentSessionId)??null,providerName:e.providerName??(s==null?void 0:s.cliName)??(s==null?void 0:s.type)??e.providerType,workspace:e.workspace??(s==null?void 0:s.workspace)??null,capabilities:e.capabilities??(s==null?void 0:s.sessionCapabilities)??[],cdpConnected:e.cdpConnected??(s==null?void 0:s.cdpConnected),currentModel:e.currentModel??(s==null?void 0:s.currentModel),currentPlan:e.currentPlan??(s==null?void 0:s.currentPlan),currentAutoApprove:e.currentAutoApprove??(s==null?void 0:s.currentAutoApprove),controlValues:e.controlValues??(s==null?void 0:s.controlValues),providerControls:e.providerControls??(s==null?void 0:s.providerControls),acpConfigOptions:e.acpConfigOptions??(s==null?void 0:s.acpConfigOptions),acpModes:e.acpModes??(s==null?void 0:s.acpModes),runtimeWriteOwner:e.runtimeWriteOwner??(s==null?void 0:s.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(s==null?void 0:s.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(s==null?void 0:s.lastMessagePreview),lastMessageRole:e.lastMessageRole??(s==null?void 0:s.lastMessageRole),lastMessageAt:e.lastMessageAt??(s==null?void 0:s.lastMessageAt),lastMessageHash:e.lastMessageHash??(s==null?void 0:s.lastMessageHash)}}function ed(e){const s=[],r=new Map;for(const n of e)if(n.parentId){const o=r.get(n.parentId)||[];o.push(n),r.set(n.parentId,o)}else s.push(n);return{topLevel:s,childrenByParent:r}}function jr(e,s){const r=[],{daemonId:n,existingDaemon:o,existingEntries:i,timestamp:c}=s,d=c||e.timestamp||Date.now(),m=e.sessions||[],{topLevel:f,childrenByParent:p}=ed(m),x=Ql(i,n),b=e.machine?{...(o==null?void 0:o.machine)||{},...e.machine}:o==null?void 0:o.machine,S=f.filter(h=>h.kind==="workspace"&&h.transport==="cdp-page"),A=f.filter(h=>h.kind==="agent"&&h.transport==="pty"),u=f.filter(h=>h.kind==="agent"&&h.transport==="acp");r.push({...o||{},id:n,type:"adhdev-daemon",status:"online",timestamp:d,...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},cdpConnected:S.some(h=>!!h.cdpConnected)});for(const h of S){const y=x.get(h.id),l=tr(h,y),j=(p.get(h.id)||[]).map(P=>tr(P,x.get(P.id)));r.push({id:`${n}:ide:${h.id}`,sessionId:h.id,providerSessionId:h.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:l.parentId,sessionKind:l.kind,transport:l.transport,sessionCapabilities:l.capabilities,type:l.providerType,status:l.cdpConnected?"online":"detected",daemonId:n,instanceId:h.id,workspace:l.workspace,terminals:0,childSessions:j,agents:j.map(P=>({id:P.id,name:P.providerName||P.providerType,type:P.providerType,status:P.status})),activeChat:l.activeChat,chats:[],cdpConnected:l.cdpConnected,...l.currentModel!==void 0&&{currentModel:l.currentModel},...l.currentPlan!==void 0&&{currentPlan:l.currentPlan},...l.currentAutoApprove!==void 0&&{currentAutoApprove:l.currentAutoApprove},...l.lastMessagePreview!==void 0&&{lastMessagePreview:l.lastMessagePreview},...l.lastMessageRole!==void 0&&{lastMessageRole:l.lastMessageRole},...l.lastMessageAt!==void 0&&{lastMessageAt:l.lastMessageAt},...l.lastMessageHash!==void 0&&{lastMessageHash:l.lastMessageHash},lastUpdated:l.lastUpdated,unread:l.unread,lastSeenAt:l.lastSeenAt,inboxBucket:l.inboxBucket,surfaceHidden:l.surfaceHidden,...l.controlValues!==void 0&&{controlValues:l.controlValues},...l.providerControls!==void 0&&{providerControls:l.providerControls},timestamp:d})}for(const h of A){const y=x.get(h.id),l=tr(h,y);r.push({id:`${n}:cli:${h.id}`,sessionId:h.id,providerSessionId:h.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:l.parentId,sessionKind:l.kind,transport:l.transport,sessionCapabilities:l.capabilities,type:l.providerType,agentType:l.providerType,status:l.status||"running",daemonId:n,instanceId:h.id,cliName:l.providerName||l.providerType,mode:l.mode||(y==null?void 0:y.mode)||"terminal",workspace:l.workspace||"",activeChat:l.activeChat,...l.resume!==void 0&&{resume:l.resume},...l.runtimeKey!==void 0&&{runtimeKey:l.runtimeKey},...l.runtimeDisplayName!==void 0&&{runtimeDisplayName:l.runtimeDisplayName},...l.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:l.runtimeWorkspaceLabel},...l.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:l.runtimeWriteOwner},...l.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:l.runtimeAttachedClients},...l.lastMessagePreview!==void 0&&{lastMessagePreview:l.lastMessagePreview},...l.lastMessageRole!==void 0&&{lastMessageRole:l.lastMessageRole},...l.lastMessageAt!==void 0&&{lastMessageAt:l.lastMessageAt},...l.lastMessageHash!==void 0&&{lastMessageHash:l.lastMessageHash},lastUpdated:l.lastUpdated,unread:l.unread,lastSeenAt:l.lastSeenAt,inboxBucket:l.inboxBucket,surfaceHidden:l.surfaceHidden,...l.controlValues!==void 0&&{controlValues:l.controlValues},...l.providerControls!==void 0&&{providerControls:l.providerControls},timestamp:d,_isCli:!0})}for(const h of u){const y=x.get(h.id),l=tr(h,y);r.push({id:`${n}:acp:${h.id}`,sessionId:h.id,providerSessionId:h.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:l.parentId,sessionKind:l.kind,transport:l.transport,sessionCapabilities:l.capabilities,type:l.providerType,agentType:l.providerType,status:l.status||"running",daemonId:n,instanceId:h.id,cliName:l.providerName||l.providerType,mode:"chat",workspace:l.workspace||"",activeChat:l.activeChat,...l.runtimeKey!==void 0&&{runtimeKey:l.runtimeKey},...l.runtimeDisplayName!==void 0&&{runtimeDisplayName:l.runtimeDisplayName},...l.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:l.runtimeWorkspaceLabel},...l.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:l.runtimeWriteOwner},...l.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:l.runtimeAttachedClients},...l.currentModel!==void 0&&{currentModel:l.currentModel},...l.currentPlan!==void 0&&{currentPlan:l.currentPlan},...l.lastMessagePreview!==void 0&&{lastMessagePreview:l.lastMessagePreview},...l.lastMessageRole!==void 0&&{lastMessageRole:l.lastMessageRole},...l.lastMessageAt!==void 0&&{lastMessageAt:l.lastMessageAt},...l.lastMessageHash!==void 0&&{lastMessageHash:l.lastMessageHash},lastUpdated:l.lastUpdated,unread:l.unread,lastSeenAt:l.lastSeenAt,inboxBucket:l.inboxBucket,surfaceHidden:l.surfaceHidden,...l.acpConfigOptions!==void 0&&{acpConfigOptions:l.acpConfigOptions},...l.acpModes!==void 0&&{acpModes:l.acpModes},...l.controlValues!==void 0&&{controlValues:l.controlValues},...l.providerControls!==void 0&&{providerControls:l.providerControls},timestamp:d,_isAcp:!0})}return r}const Vr=new Map,Gr=new Map,qr=new Set,Rs=new Map,td=1200;function sd(e){if(!e||typeof e!="object")return null;const s=e,r=s.status;if(r&&typeof r=="object")return r;const n=s.result;if(n&&typeof n=="object"&&"status"in n){const o=n.status;if(o&&typeof o=="object")return o}return s}function ka(e,s){const r=Rs.get(e);!r||r.size===0||(Rs.delete(e),r.forEach(n=>n(s)))}function rd(e,s){return new Promise(r=>{const n=Rs.get(e)||new Set;Rs.set(e,n);const o=c=>{clearTimeout(i),n.delete(o),n.size===0&&Rs.delete(e),r(c)},i=setTimeout(()=>o(!1),s);n.add(o)})}function Gs(){const{sendCommand:e,sendData:s}=Ct(),{injectEntries:r,getIdes:n}=vr();return a.useCallback(async(o,i)=>{if(!o)return;const c=(i==null?void 0:i.minFreshMs)??6e4,d=Gr.get(o)||0;if(!(i!=null&&i.force)&&qr.has(o)&&d>0||!(i!=null&&i.force)&&d>0&&Date.now()-d<c)return;const m=Vr.get(o);if(m)return m;const f=(async()=>{if(s&&!qr.has(o)&&(qr.add(o),Ot.subscribe({sendData:s},o,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${o}`,params:{includeSessions:!0}},u=>{const h=n(),y=h.find(j=>j.id===o),l=jr(u.status,{daemonId:o,existingDaemon:y,existingEntries:h,timestamp:u.timestamp});l.length>0&&r(l),Gr.set(o,Date.now()),ka(o,!0)}),!(i!=null&&i.force)&&await rd(o,td)))return;const p=await e(o,"get_status_metadata"),x=sd(p);if(!x)return;const b=n(),S=b.find(u=>u.id===o),A=jr(x,{daemonId:o,existingDaemon:S,existingEntries:b,timestamp:x.timestamp||Date.now()});A.length>0&&r(A,{authoritativeDaemonIds:[o]}),Gr.set(o,Date.now()),ka(o,!0)})().finally(()=>{Vr.delete(o)});return Vr.set(o,f),f},[n,r,e,s])}function os(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}function Eo(e,s){if(!e||!s)return!1;if(e===s||e.id&&s.id&&String(e.id)===String(s.id)||e._localId&&s._localId&&String(e._localId)===String(s._localId))return!0;const r=String(e.role||"").toLowerCase(),n=String(s.role||"").toLowerCase();if(r!==n)return!1;const o=as(e.content),i=as(s.content);if(!o||o!==i)return!1;const c=os(e),d=os(s);return c&&d?Math.abs(c-d)<=15e3:!!e._localId!=!!s._localId}function Na(e){let s=0;return e!=null&&e._localId||(s+=4),e!=null&&e.id&&(s+=3),e!=null&&e._turnKey&&(s+=2),os(e)&&(s+=1),s}function nd(e,s){const r=Na(e),n=Na(s);return n!==r?n>r?s:e:as(s.content).length>=as(e.content).length?s:e}function Ls(e){const s=[];for(const r of e){const n=s.findIndex(o=>Eo(o,r));if(n>=0){s.splice(n,1,nd(s[n],r));continue}s.push(r)}return s}function Sa(e){return[...e].sort((s,r)=>{const n=os(s),o=os(r);return n&&o&&n!==o?n-o:0})}function Ca(e){return`${String((e==null?void 0:e.role)||"").toLowerCase()}:${as(e==null?void 0:e.content).slice(0,100)}`}function Ia(e,s){const r=e.filter(n=>String((n==null?void 0:n.role)||"").toLowerCase()==="user").slice();return s.filter(n=>{const o=r.findIndex(i=>Eo(i,n));return o>=0?(r.splice(o,1),!1):!0})}function ad(e,s){const r=new Set(s.map(n=>Ca(n)));return e.filter(n=>!r.has(Ca(n)))}const od=60,id=200;function cd(e={}){return e.isCliLike?id:od}function ld(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function dd(e){let s=2166136261;for(const r of e){const n=String(r||"");for(let o=0;o<n.length;o+=1)s^=n.charCodeAt(o),s=Math.imul(s,16777619)>>>0;s^=255,s=Math.imul(s,16777619)>>>0}return s.toString(16).padStart(8,"0")}function Ta(e,s){const r=e[e.length-1];if(!r)return"empty:";let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return["",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function $o(e){if(!e)return"";let s="";try{s=JSON.stringify(e.content??"")}catch{s=String(e.content??"")}return dd([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),s])}function ud(e){return{knownMessageCount:e.length,lastMessageSignature:$o(e[e.length-1])}}function md(e,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return e;case"append":return Ls([...e,...r]);case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??e.length),e.length));return Ls([...e.slice(0,n),...r])}case"full":default:return r}}const Aa=60;function bn({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,handleFocusAgent:o,isFocusingAgent:i,actionLogs:c,userName:d,showMetaChips:m=!1,scrollToBottomRequestNonce:f,isInputActive:p=!0}){var Q,xe;const x=a.useRef(new Map),b=a.useRef(new Map),S=a.useRef(new Map),{sendCommand:A,sendData:u}=Ct(),h=Gs();zs("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:c.length,isSendingChat:n});const y=rt.useMemo(()=>ks(e),[e.status,e.connectionState]),l=a.useMemo(()=>Xl(e,s),[e,s]),j=cd({isCliLike:l.isCli||l.isAcp}),P=a.useRef(new Map),k=a.useCallback(W=>(P.current.has(W)||P.current.set(W,{messages:[],offset:0,hasMore:!0,error:null,visibleLiveCount:j}),P.current.get(W)),[j]),g=a.useCallback((W,ee)=>{const ne=k(W);P.current.set(W,{...ne,...ee}),N(oe=>oe+1)},[k]),[,N]=a.useState(0),v=e.tabKey,w=k(v),M=w.messages,T=w.hasMore,$=w.error,E=b.current.get(v),F=e.messages.filter(W=>!!(W!=null&&W._localId)),D=E?Ls([...E,...F]):e.messages;a.useEffect(()=>{w.visibleLiveCount>=j||g(v,{visibleLiveCount:j})},[j,w.visibleLiveCount,v,g]);const C=Math.max(0,D.length-w.visibleLiveCount),V=Rr(e),J=wr(e),I=e.sessionId||"",R=e.providerSessionId||I,[B,z]=a.useState(!1);a.useEffect(()=>{const W=l.targetEntry;J&&(!W||W.providerControls===void 0||W.controlValues===void 0)&&h(J,{minFreshMs:3e4}).catch(()=>{})},[J,l.isAcp,(Q=l.targetEntry)==null?void 0:Q.providerControls,(xe=l.targetEntry)==null?void 0:xe.controlValues,h]),a.useEffect(()=>{if(!J||!I||!u)return;const W=b.current.get(v)||[],ee=S.current.get(v),ne=ee&&ee.knownMessageCount?ee:ud(W),oe=`daemon:${J}:session:${I}`;return Ot.subscribe({sendData:u},J,{type:"subscribe",topic:"session.chat_tail",key:oe,params:{targetSessionId:I,historySessionId:R,knownMessageCount:ne.knownMessageCount,lastMessageSignature:ne.lastMessageSignature,...ne.knownMessageCount?{}:{tailLimit:Aa}}},te=>{const de=b.current.get(v)||[],se=md(de,te),pe=Math.max(se.length,Number(te.totalMessages||0));S.current.set(v,{knownMessageCount:pe,lastMessageSignature:typeof te.lastMessageSignature=="string"?te.lastMessageSignature:$o(se[se.length-1])}),Ta(de)!==Ta(se)&&(b.current.set(v,se),ss.record({interactionId:te.interactionId,kind:"dashboard.chat_tail_applied",topic:"session.chat_tail",payload:{sessionId:I,syncMode:te.syncMode,previousCount:de.length,nextCount:se.length}}),N(Ne=>Ne+1))})},[J,R,u,I,v]);const Z=a.useCallback(async()=>{if(B)return;const W=e.tabKey,ee=k(W);if(D.length>ee.visibleLiveCount){g(W,{visibleLiveCount:Math.min(D.length,ee.visibleLiveCount+Aa),error:null});return}z(!0),g(W,{error:null});try{const ne=wr(e);if(!ne){g(W,{hasMore:!1});return}const oe=wt(e),he=await A(ne,"chat_history",{agentType:oe,offset:ee.offset,limit:30,targetSessionId:e.sessionId,historySessionId:e.providerSessionId||e.sessionId}),te=ld(he),de=te.messages||[];if(de.length>0){const se=k(W);g(W,{messages:[...de,...se.messages],offset:se.offset+de.length,hasMore:!!te.hasMore})}else g(W,{hasMore:!!te.hasMore})}catch(ne){const oe=(ne==null?void 0:ne.message)||"";oe.includes("P2P not available")||oe.includes("channel not open")||oe.includes("P2P not connected")||oe.includes("timeout")?g(W,{error:"Connection not ready — tap to retry"}):g(W,{hasMore:!1,error:"Failed to load history"})}finally{z(!1)}},[B,e,D.length,A,k,g]),{allMessages:fe,receivedAtMap:Pe}=a.useMemo(()=>{const W=C>0?D.slice(-w.visibleLiveCount):D;if(M.length===0){const he=Sa(Ls(W)),te={};return he.forEach((de,se)=>{const pe=`${e.tabKey}:${fs(de,se)}`;let ae=os(de)||x.current.get(pe)||0;ae||(ae=Date.now(),x.current.set(pe,ae)),te[fs(de,se)]=ae}),{allMessages:he,receivedAtMap:te}}const ee=ad(M,W),ne=Sa(Ls([...ee,...W])),oe={};return ne.forEach((he,te)=>{const de=`${e.tabKey}:${fs(he,te)}`;let se=os(he)||x.current.get(de)||0;se||(se=Date.now(),x.current.set(de,se)),oe[fs(he,te)]=se}),{allMessages:ne,receivedAtMap:oe}},[e.tabKey,C,M,D,w.visibleLiveCount]),ke=a.useMemo(()=>c.filter(W=>W.routeId===e.tabKey).sort((W,ee)=>W.timestamp-ee.timestamp),[c,e.tabKey]),ve=a.useMemo(()=>{if(D.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[t.jsx("div",{className:"connecting-logo-float",children:t.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),t.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[t.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",t.jsx("span",{className:"connecting-dots"})]}),t.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((y.isGenerating||e.status==="streaming")&&z(!1),e.status==="not_monitored")return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-3xl opacity-60",children:t.jsx(Ks,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),t.jsx("button",{onClick:o,disabled:i,className:"btn btn-primary",children:i?"⌛ Switching...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(gs,{size:14})," Open ",V," Panel"]})}),t.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden")return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-3xl opacity-60",children:t.jsx(yo,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),t.jsx("button",{onClick:o,disabled:i,className:"btn btn-primary",children:i?"⌛ Opening...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(gs,{size:14})," Open ",V," Panel"]})}),t.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Open the agent panel or chat view in the app you are using to start viewing messages"})]});if(e.status==="idle"&&!B)return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),t.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,o,i,B,D.length,V,y.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[m&&t.jsx(Do,{conversation:e,className:"chat-pane-meta-row"}),t.jsx(Xc,{messages:fe,actionLogs:ke,agentName:Vs(e)||V||"Agent",userName:d,isCliMode:l.isCli||l.isAcp,isWorking:y.isGenerating,contextKey:e.tabKey,receivedAtMap:Pe,onLoadMore:Z,isLoadingMore:B,hasMoreHistory:T,hiddenLiveCount:C,loadError:$??void 0,emptyState:ve,scrollToBottomRequestNonce:f}),p&&!l.isCliTerminal&&(()=>{var W,ee;return t.jsx(Fl,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:l.providerType,displayLabel:l.displayLabel,controls:(W=l.targetEntry)==null?void 0:W.providerControls,controlValues:(ee=l.targetEntry)==null?void 0:ee.controlValues})})(),!l.isCliTerminal&&t.jsx(Vl,{contextKey:e.tabKey,panelLabel:V,isSending:n,onSend:r,isActive:p})]})}let Bo=rs;function Ko(){return Bo()}class pd{constructor(){lt(this,"listeners",new Map)}send(s){}isConnected(){return!1}on(s,r){return this.listeners.has(s)||this.listeners.set(s,new Set),this.listeners.get(s).add(r),()=>{var n;(n=this.listeners.get(s))==null||n.delete(r)}}emit(s,...r){var n;(n=this.listeners.get(s))==null||n.forEach(o=>o(...r))}}let Wo=new pd;class fd{sendPtyInput(s,r,n){return!1}sendPtyResize(s,r,n,o){return!1}retryConnection(s){}getState(s){return"disconnected"}sendData(s,r){return!1}get(s){}onScreenshot(s,r){return()=>{}}onRuntimeEvent(s,r){return()=>{}}requestRuntimeSnapshot(s,r){return Promise.resolve()}}let at=new fd;function xd(e){e.dashboardWS&&(Wo=e.dashboardWS),e.connectionManager&&(at=e.connectionManager),e.useDaemonsHook&&(Bo=e.useDaemonsHook)}function st(e){return Rr(e)}function is(e){return $n(e).join(" · ")}function Oo(e){if(e.lastMessagePreview)return e.lastMessagePreview;const s=[...e.messages].reverse().find(n=>!(n!=null&&n._localId))||e.messages[e.messages.length-1],r=as(s==null?void 0:s.content);return r||(e.title?e.title:is(e)||"No messages yet")}function Ho(e,s){const{isReconnecting:r,isConnecting:n}=ks(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function hd(e,s){const r=["Chat",...$n(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function qt(e){return Ho(e)||is(e)}function bd(e){return`${st(e)} · ${Oo(e)}`}function gd(e){const s=En(e)||wt(e);return`${st(e)} — ${et(s)}`}function yd(e){return Vs(e)||"CLI"}function Uo(e){return e.title||Vs(e)||e.routeId}function zo(e){return e?`Remote · ${st(e)||e.workspaceName||"Session"}`:"Remote"}function vd({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:o=!1,isVisible:i=!0}){var R;const{ides:c}=rs(),d=a.useRef(null),{sendCommand:m,sendData:f}=Ct(),[p,x]=a.useState(""),[b,S]=a.useState(!1),[A,u]=a.useState(1),h=a.useRef(!1),y=a.useRef(0),l=a.useRef(!1),j=a.useRef(""),P=a.useRef(null),k=a.useRef(!1),g=a.useRef(null),N=e.tabKey,v=e.sessionId||"",w=e.daemonId||((R=e.routeId)==null?void 0:R.split(":")[0])||e.routeId||"",M=c.find(B=>B.id===w&&B.type==="adhdev-daemon"),T=(M==null?void 0:M.terminalSizingMode)==="fit"?"fit":"measured",$=.6,E=1.15,F=()=>{if(typeof window>"u")return 1;const B=window.innerWidth||0;return B<=360?.68:B<=390?.74:B<=430?.82:B<=480?.9:1},D=()=>{var B,z;y.current=0,l.current=!1,j.current="",P.current=null,k.current=!1,g.current!==null&&(cancelAnimationFrame(g.current),g.current=null),S(!1),(z=(B=r.current)==null?void 0:B.reset)==null||z.call(B)},C=()=>{var B,z;y.current=0,l.current=!1,j.current="",P.current=null,k.current=!1,g.current!==null&&(cancelAnimationFrame(g.current),g.current=null),S(!0),(z=(B=r.current)==null?void 0:B.reset)==null||z.call(B)},V=()=>{var z;if(g.current=null,!i)return;const B=j.current;B&&(j.current="",(z=r.current)==null||z.write(B))},J=B=>{B&&(j.current+=B,i&&g.current===null&&(g.current=requestAnimationFrame(V)))},I=(B,z=0,Z,fe)=>{var Pe,ke,ve,Q,xe;z>0&&y.current>=z||z===0&&l.current||(y.current=z,S(!0),typeof Z=="number"&&typeof fe=="number"&&Z>0&&fe>0&&((ke=(Pe=r.current)==null?void 0:Pe.resize)==null||ke.call(Pe,Z,fe)),(Q=(ve=r.current)==null?void 0:ve.reset)==null||Q.call(ve),B&&((xe=r.current)==null||xe.write(B)))};return a.useEffect(()=>{D()},[v]),a.useEffect(()=>{var z;if(!v)return;const B=((z=at.onRuntimeEvent)==null?void 0:z.call(at,v,Z=>{if(!(!Z||Z.sessionId!==v)){if(Z.type==="runtime_snapshot"){if(!i){P.current={text:Z.text||"",seq:Z.seq||0,cols:Z.cols,rows:Z.rows};return}I(Z.text||"",Z.seq||0,Z.cols,Z.rows);return}if(Z.type==="session_output"){l.current=!0,typeof Z.seq=="number"&&(y.current=Math.max(y.current,Z.seq)),b||S(!0),typeof Z.data=="string"&&J(Z.data);return}if(Z.type==="session_cleared"){if(!i){k.current=!0,j.current="",P.current=null;return}C()}}}))||(()=>{});return()=>{B()}},[w,v,r,i,b]),a.useEffect(()=>{var z,Z,fe;if(!v)return;w&&((z=at.getState)==null?void 0:z.call(at,w))==="connected"&&(S(!0),(Z=at.requestRuntimeSnapshot)==null||Z.call(at,w,v).catch(()=>{}));const B=(fe=at.onStateChange)==null?void 0:fe.call(at,(Pe,ke)=>{var ve;Pe!==w||ke!=="connected"||(S(!0),(ve=at.requestRuntimeSnapshot)==null||ve.call(at,w,v).catch(()=>{}))});return()=>{B==null||B()}},[w,v,r]),a.useEffect(()=>{s&&D()},[s,N,r]),a.useEffect(()=>{x("")},[e.tabKey]),a.useEffect(()=>{const B=()=>{h.current||u(F())};return B(),window.addEventListener("resize",B),()=>window.removeEventListener("resize",B)},[]),a.useEffect(()=>{var z;if(!i){(z=d.current)==null||z.blur();return}k.current&&(k.current=!1,C());const B=P.current;B&&(P.current=null,I(B.text,B.seq,B.cols,B.rows)),j.current&&g.current===null&&(g.current=requestAnimationFrame(V)),requestAnimationFrame(()=>{var Z;(Z=r.current)==null||Z.bumpResize()})},[i]),a.useEffect(()=>()=>{g.current!==null&&(cancelAnimationFrame(g.current),g.current=null)},[]),a.useEffect(()=>{const B=z=>{var fe;const Z=z.detail;Z!=null&&Z.sessionId&&Z.sessionId!==v||b&&((fe=r.current)==null||fe.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",B),()=>{window.removeEventListener("adhdev:fit-cli-terminal",B)}},[b,v,r]),t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[t.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[t.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{h.current=!0,u(B=>Math.max($,Number((B-.1).toFixed(2))))},title:"Shrink terminal viewport",children:"-"}),t.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{h.current=!0,u(B=>Math.min(E,Number((B+.1).toFixed(2))))},title:"Increase terminal viewport",children:"+"})]}),t.jsx("div",{className:"w-full h-full overflow-auto rounded-lg",children:t.jsx("div",{style:{width:`${100/A}%`,height:`${100/A}%`,transform:`scale(${A})`,transformOrigin:"top left"},children:t.jsx(No,{ref:r,readOnly:!b||!i,sizingMode:T,onInput:B=>{b&&(f!=null&&f(w,{type:"pty_input",targetSessionId:v,data:B})||m(w,"pty_input",{targetSessionId:v,data:B}).catch(console.error))}})})}),!b&&t.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:"Runtime terminal unavailable"})]}),t.jsx("div",{className:"px-3 py-2 bg-[var(--surface-primary)] border-t border-border-subtle shrink-0",children:t.jsxs("div",{className:"flex gap-2.5 items-center",children:[t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:d,type:"text",placeholder:`Send message to ${st(e)}...`,value:p,disabled:!b||!i||o,onChange:B=>x(B.target.value),onPaste:B=>{const z=B.clipboardData.getData("text");z&&x(Z=>Z+z),B.preventDefault()},onKeyDown:B=>{if(B.key!=="Enter")return;if(B.nativeEvent.isComposing){B.preventDefault();return}B.preventDefault();const z=p.trim();!b||!z||o||(x(""),n(z))},className:"w-full h-9 rounded-[18px] px-4 bg-bg-secondary text-[13px] text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),t.jsx("button",{onClick:()=>{const B=p.trim();!b||!B||o||(x(""),n(B))},disabled:!b||!i||!p.trim()||o,className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${p.trim()&&!o?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:p.trim()&&!o?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:p.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})]})}function wd({wsStatus:e,showReconnected:s,loginUrl:r}){const n=e==="disconnected"||e==="reconnecting"||e==="offline"||e==="auth_failed",o=e==="auth_failed"?"red":e==="offline"?"orange":"accent",i={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},c={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},d={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"};return t.jsxs(t.Fragment,{children:[n&&t.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5 justify-center",style:{background:i[o],borderBottom:c[o],color:d[o]},children:[t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),e==="offline"&&"Network offline — waiting for connection...",e==="disconnected"&&"Reconnecting to server...",e==="reconnecting"&&"Reconnecting to server...",e==="auth_failed"&&(r?t.jsxs(t.Fragment,{children:["Session expired."," ",t.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — please restart the server.")]}),s&&e==="connected"&&t.jsxs("div",{className:"py-2 px-4 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-b border-green-500/15 animate-[fadeIn_0.3s_ease]",children:[t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})]})}function jd({terminalBackend:e,isStandalone:s=!1,machineLabel:r,machineKey:n}){const o=a.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[i,c]=a.useState(!1);if(a.useEffect(()=>{if(!o){c(!1);return}try{c(localStorage.getItem(o)==="1")}catch{c(!1)}},[o]),!s||!e||e.backend!=="xterm"||i)return null;const d=(r==null?void 0:r.trim())||"This machine",m=()=>{if(o)try{localStorage.setItem(o,"1")}catch{}c(!0)};return t.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5",style:{background:"linear-gradient(90deg, rgba(245,158,11,0.12), rgba(245,158,11,0.04))",borderBottom:"1px solid rgba(245,158,11,0.2)",color:"#d97706"},children:[t.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[t.jsxs("span",{children:[d," is using `xterm` fallback."]}),t.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),t.jsx("button",{type:"button",onClick:m,className:"shrink-0 text-[12px] font-semibold px-2 py-1 rounded-md transition-colors",style:{color:"#b45309",background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.18)"},"aria-label":"Dismiss terminal backend warning",title:"Dismiss",children:"Dismiss"})]})}function Kn({mode:e,onChange:s,compact:r=!1}){const n=r?14:15;return t.jsx("button",{type:"button",onClick:()=>s(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:e==="chat"?"Switch to Terminal view":"Switch to Chat view",children:e==="chat"?t.jsx(Mr,{size:n}):t.jsx(Kt,{size:n})})}function kd(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Date.parse(e);if(Number.isFinite(s))return s}return 0}function Ht(e){const s=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1];return e.lastMessageAt||kd(s==null?void 0:s.receivedAt)||0}function gn(e,s=0){return Ht(e)||e.lastUpdated||s||0}function Fo(e){return Ht(e)||e.lastUpdated||0}function kr(e,s,r=Fo){const n=r(s)-r(e);if(n!==0)return n;const o=(e.machineName||"").localeCompare(s.machineName||"");if(o!==0)return o;const i=e.displayPrimary.localeCompare(s.displayPrimary);if(i!==0)return i;const c=e.displaySecondary.localeCompare(s.displaySecondary);return c!==0?c:e.tabKey.localeCompare(s.tabKey)}function yn(e){var r;const s=bt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function Nd(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!yn(e)&&!e.title.trim()}function Sd(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(yn(r))-Number(yn(s));if(n!==0)return n;const o=r.messages.length-s.messages.length;return o!==0?o:kr(s,r)})[0]||null}function Lt(e,s){const r=e.filter(c=>c.routeId===s);if(r.length===0)return null;const n=r.find(c=>c.streamSource==="native")||null,o=r.filter(c=>c.streamSource==="agent-stream"),i=Sd(o);return n?i&&Nd(n)?i:n:i||r[0]||null}function Ma({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function _a({conversation:e,isAttention:s,shortcutIndex:r,onClick:n}){const o=$n(e),i=Rn(Ht(e)),c=[...o,i].filter(Boolean);return t.jsxs("button",{type:"button",className:`dashboard-header-inbox-item ${s?"is-attention":""}`.trim(),onClick:n,children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:Rr(e)}),(r||c.length>0)&&t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[r?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",r]}):null,c.join(" · ")]})]})}function Cd({activeConv:e,agentCount:s,wsStatus:r,isConnected:n,conversations:o,onOpenHistory:i,onOpenRemote:c,onStopCli:d,activeCliViewMode:m,onSetCliViewMode:f,onOpenConversation:p,onHideConversation:x,hiddenConversations:b=[],onShowConversation:S,onShowAllHidden:A,onResetPanelsToMain:u,inboxOpen:h,onInboxOpenChange:y,hiddenOpen:l,onHiddenOpenChange:j,onOpenNewSession:P,actionShortcuts:k}){const{ides:g,p2pStates:N={}}=rs(),v=!!e&&Ye(e)&&!Ve(e),w=!!e&&Ve(e),M=m||(e?Ro(e)?"terminal":"chat":null),[T,$]=a.useState(!1),E=a.useRef(null),F=a.useRef(null),D=n?"#22c55e":r==="connected"?"#eab308":"#ef4444",C=n?"0 0 4px #22c55e80":r==="connected"?"0 0 4px #eab30880":"0 0 4px #ef444480",V=g.filter(W=>W.type==="adhdev-daemon"),J=a.useMemo(()=>Fs(g),[g]),I=Object.values(N),R=I.filter(W=>W==="connected").length,B=I.filter(W=>W==="connecting"||W==="new"||W==="checking").length,Z=r!=="connected"||V.length===0?null:B>0&&R===0?"P2P connecting...":R>0&&s===0?"Waiting for IDE...":null,fe=a.useMemo(()=>o.filter(W=>!il(W,o,J)),[o,J]),Pe=a.useMemo(()=>fe.filter(W=>Os(W,J).requiresAction).sort(kr),[fe,J]),ke=a.useMemo(()=>fe.filter(W=>{const ee=(e==null?void 0:e.tabKey)===W.tabKey;return Os(W,J,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ee}).unread}).sort(kr),[e,fe,J]),ve=a.useMemo(()=>[...Pe,...ke].slice(0,9),[Pe,ke]),Q=Pe.length+ke.length;a.useEffect(()=>{if(!h)return;const W=ee=>{var ne;(ne=E.current)!=null&&ne.contains(ee.target)||y(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[h,y]),a.useEffect(()=>{if(!l)return;const W=ee=>{var ne;(ne=F.current)!=null&&ne.contains(ee.target)||j(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[l,j]),a.useEffect(()=>{if(!l&&!h)return;const W=ee=>{if(!ee.altKey)return;const ne=ee.code.match(/^Digit([1-9])$/);if(!ne)return;const oe=Number(ne[1])-1,he=l?b[oe]:void 0,te=h?ve[oe]:void 0,de=he||te;if(de){if(ee.preventDefault(),ee.stopPropagation(),he){S==null||S(he),j(!1);return}p==null||p(de),y(!1)}};return window.addEventListener("keydown",W,!0),()=>window.removeEventListener("keydown",W,!0)},[b,l,h,ve,j,y,p,S]);const xe=W=>{if(!W)return;const ee=o.find(ne=>ne.tabKey===W);ee&&(x==null||x(ee))};return t.jsxs("div",{className:"dashboard-header",children:[t.jsx("div",{className:"flex items-center gap-3",children:t.jsx("div",{className:"header-title-block",children:t.jsxs("div",{className:"header-title-row",children:[t.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[t.jsx(Kt,{size:18}),t.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),t.jsx("span",{className:"header-title-mobile",children:e?st(e):"Dashboard"}),t.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:t.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:D,boxShadow:C}})})]}),t.jsxs("div",{className:"header-subtitle flex items-center",children:[t.jsx("span",{title:n?"Connected":r==="connected"?"Partial":"Disconnected",className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:D,boxShadow:C}}),Z&&t.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",Z]}),P&&t.jsx("button",{type:"button",onClick:P,className:"btn btn-secondary btn-sm ml-2",title:"Start or recover a session","aria-label":"Start or recover a session",children:t.jsx(Ac,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(v||w||!Ve(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:is(e)||st(e),children:st(e)}),(v||w)&&d&&t.jsxs(t.Fragment,{children:[v&&f&&M&&t.jsx(Kn,{mode:M,onChange:f,compact:!0}),t.jsx("button",{onClick:()=>d(e),className:"btn btn-secondary btn-sm",title:w?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:t.jsx(vt,{size:14})})]}),!Ve(e)&&t.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:t.jsx(Mn,{size:14})}),!v&&!Ve(e)&&t.jsx("button",{onClick:c,className:"btn btn-secondary btn-sm",title:"Remote Control",children:t.jsx(kt,{size:14})})]}),t.jsxs("div",{className:"dashboard-header-inbox",ref:E,children:[t.jsxs("div",{className:`dashboard-header-hidden${T?" is-drop-target":""}`,ref:F,onDragEnter:W=>{W.dataTransfer.types.includes("text/tab-key")&&(W.preventDefault(),$(!0))},onDragOver:W=>{W.dataTransfer.types.includes("text/tab-key")&&(W.preventDefault(),W.dataTransfer.dropEffect="move",$(!0))},onDragLeave:W=>{W.currentTarget.contains(W.relatedTarget)||$(!1)},onDrop:W=>{const ee=W.dataTransfer.getData("text/tab-key");W.preventDefault(),$(!1),xe(ee)},children:[t.jsxs("button",{type:"button",onClick:()=>j(!l),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${k!=null&&k.toggleHiddenTabs?` (${k.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[t.jsx(vo,{size:16}),b.length>0&&t.jsx("span",{className:"dashboard-header-hidden-badge",children:b.length})]}),l&&t.jsxs("div",{className:"dashboard-header-hidden-popover",children:[t.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[t.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),t.jsx(Ma,{value:k==null?void 0:k.toggleHiddenTabs})]}),t.jsxs("div",{className:"dashboard-header-hidden-actions",children:[u&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u,children:"Reset panels"}),b.length>0&&A&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{A(),j(!1)},children:"Restore all"})]})]}),e&&x&&t.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>x(e),children:[t.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[t.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),t.jsx(Ma,{value:k==null?void 0:k.hideCurrentTab})]}),t.jsx("span",{className:"dashboard-header-hidden-current-title",children:st(e)})]}),b.length>0?t.jsx("div",{className:"dashboard-header-hidden-list",children:b.map(W=>t.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{S==null||S(W),j(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:st(W)}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[b.indexOf(W)<9?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",b.indexOf(W)+1]}):null,is(W)]})]},W.tabKey))}):t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),t.jsxs("button",{type:"button",onClick:()=>y(!h),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[t.jsx(_r,{size:16}),Q>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:Q})]}),h&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[Pe.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Needs attention"}),Pe.map(W=>t.jsx(_a,{conversation:W,isAttention:!0,shortcutIndex:ve.indexOf(W)>=0?ve.indexOf(W)+1:void 0,onClick:()=>{p==null||p(W),y(!1)}},W.tabKey))]}),ke.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Task complete"}),ke.map(W=>t.jsx(_a,{conversation:W,shortcutIndex:ve.indexOf(W)>=0?ve.indexOf(W)+1:void 0,onClick:()=>{p==null||p(W),y(!1)}},W.tabKey))]}),Q===0&&t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function Nr(e){return e?"Resume saved history":"Start fresh"}function Wn(e){return e?"Resuming saved history…":"Starting fresh…"}function Vo(){return"Start fresh"}function Id(){return"Recover hosted runtime"}function Go(){return"Open saved history"}function Td(){return"Saved History"}function Ad(){return"No saved history found yet."}function Md(){return"Refresh saved history"}function _d(){return"Refreshing saved history…"}function Yt(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function Xt(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 Jt(e){return e==="start-fresh"?"Start fresh":"Restart"}function Zt(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function qo(e){return`Resume saved history with ${e}?`}function Yo(){return"Review or change the target workspace before resuming saved history."}function Pd(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 On({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:o=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,onClose:d,onNewChat:m,onSwitchSession:f,onRefreshHistory:p,onResumeSavedSession:x}){var y;const b=s.find(l=>l.id===e.routeId),S=(b==null?void 0:b.chats)||[],A=(y=b==null?void 0:b.activeChat)==null?void 0:y.id,u=Ye(e)&&!Ve(e),h=t.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-center justify-center",children:[t.jsx("div",{onClick:d,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),t.jsxs("div",{className:"card fade-in relative w-[90%] max-w-[500px] max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[20px]",children:[t.jsxs("div",{className:"px-6 py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)]",children:[t.jsxs("div",{children:[t.jsx("h3",{className:"m-0 text-lg font-extrabold",children:u?Td():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:gd(e)})]}),t.jsx("button",{onClick:d,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:t.jsx(vt,{size:16})})]}),t.jsxs("div",{className:"flex-1 overflow-y-auto p-3 bg-bg-primary",children:[!u&&t.jsx("button",{onClick:m,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),u?t.jsx(t.Fragment,{children:o.map(l=>{const j=e.providerSessionId===l.providerSessionId,P=j||!l.canResume||!!c;return t.jsxs("button",{type:"button",onClick:()=>{P||!x||x(l)},disabled:P,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${j?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${P?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:`font-bold text-sm mb-1 truncate ${j?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:l.title||"Untitled Session"}),t.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:l.providerSessionId})]}),t.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Pd(l.lastMessageAt)})]}),t.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:l.preview||"No saved preview yet"}),t.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[t.jsxs("div",{className:"truncate",children:[l.workspace||"Workspace unknown",l.currentModel?` · ${l.currentModel}`:"",l.messageCount>0?` · ${l.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:j?"ACTIVE":l.canResume?c===l.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},l.id)})}):S.map(l=>t.jsxs("div",{onClick:()=>{f(e.routeId,l.id),d()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${A===l.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[t.jsx("div",{className:`font-bold text-sm mb-1 ${A===l.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:l.title||"Untitled Session"}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[l.id.substring(0,12),"..."]}),A===l.id&&t.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},l.id)),(u&&!i&&o.length===0||!u&&S.length===0)&&t.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[t.jsx("div",{className:"text-3xl mb-3 opacity-60",children:t.jsx(Rc,{size:32})}),t.jsx("div",{className:"text-[13px]",children:u?Ad():"No recent chat sessions found."})]}),u&&i&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:_d()})})]}),t.jsx("div",{className:"px-5 py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right",children:t.jsx("button",{onClick:p,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(js,{size:13})," ",u?Md():"Refresh History"]})})})]})]});return typeof document>"u"?h:Bs.createPortal(h,document.body)}const Pa={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 Xo({toasts:e,onDismiss:s,onClickToast:r}){return t.jsx("div",{className:"fixed right-4 z-[9999] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(n=>{const o=Pa[n.type]||Pa.info;return t.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=n.actions)!=null&&i.length||r&&r(n)},children:[t.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${o.accent}, color-mix(in srgb, ${o.accent} 55%, transparent))`}}),t.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),s(n.id)},"aria-label":"Dismiss",children:t.jsx(vt,{size:14})}),t.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[t.jsx("div",{className:"flex items-center gap-2 pr-8",children:t.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:o.chipBg,color:o.chipText,border:`1px solid color-mix(in srgb, ${o.accent} 22%, transparent)`},children:o.label})}),t.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&t.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((i,c)=>t.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:d=>{d.stopPropagation(),i.onClick(),s(n.id)},children:i.label},c))})]})]},n.id)})})}const Rd=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Ld(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function Dd(e){return e.sessionId||e.instanceId||e.agentType}function Yr(e,s){return e||s}function Ra(e,s){const r=new Set,n=[];for(const o of s)if(o)for(const i of e[o]||[]){const c=i._localId||`${i.role}:${i.timestamp}:${i.content}`;r.has(c)||(r.add(c),n.push(i))}return n.sort((o,i)=>o.timestamp-i.timestamp)}function Jo(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=jt(r,{fallbackId:r.id}));return s}function Zo(e,s={}){var n,o;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((o=s.machineNames)==null?void 0:o[e.daemonId])||void 0,connectionState:s.connectionStates?s.connectionStates[r]||s.defaultConnectionState||"new":s.defaultConnectionState}}function Hn(e,s,r={}){return Ed(e,s,Zo(e,r))}function Ed(e,s,r={}){var b,S,A,u,h,y;const n=[],o=r.machineName,i=r.connectionState,c=Ld(e),d=et(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(l=>{var j,P;return{sessionId:l.id,instanceId:l.id,providerSessionId:l.providerSessionId,transport:l.transport,agentType:l.providerType,agentName:l.providerName||et(l.providerType),status:l.status,title:l.title,lastMessagePreview:l.lastMessagePreview,lastMessageRole:l.lastMessageRole,lastMessageAt:l.lastMessageAt,lastMessageHash:l.lastMessageHash,messages:((j=l.activeChat)==null?void 0:j.messages)||[],activeModal:((P=l.activeChat)==null?void 0:P.activeModal)||void 0,unread:l.unread,lastSeenAt:l.lastSeenAt,lastUpdated:l.lastUpdated,inboxBucket:l.inboxBucket,surfaceHidden:l.surfaceHidden}}):[],f=Rd(e),p=e.activeChat||{title:""},x=p.title&&String(p.title).trim()?String(p.title).trim():"";if(f){const l=e.sessionId||e.instanceId,j=ba(e.type),P=(b=e.activeChat)==null?void 0:b.activeModal,k=P&&Array.isArray(P.buttons)&&P.buttons.length>0,g=bt((S=e.activeChat)==null?void 0:S.status,{activeModal:(A=e.activeChat)==null?void 0:A.activeModal})||bt((h=(u=e.agents)==null?void 0:u[0])==null?void 0:h.status)||"idle",N=e.activeChat||{title:"",messages:[]};let v=N.title&&String(N.title).trim()?String(N.title).trim():"";const w=(y=e.activeChat)==null?void 0:y.id,M=e.chats;if(w&&Array.isArray(M)&&M.length>0){const C=M.find(V=>V.id===w||V.id&&String(V.id)===String(w));C!=null&&C.title&&String(C.title).trim()&&(v=String(C.title).trim())}const T=(Ye(e)||Ve(e),e.type),$=(Ye(e)||Ve(e))&&ga(v,j,T)?"":v,E=N.messages||[],F=Ra(s,[e.id,l]),D=Ia(E,F);n.push({routeId:e.id,sessionId:l,providerSessionId:e.providerSessionId,nativeSessionId:l,transport:e.transport,daemonId:e.daemonId||void 0,mode:Ye(e)?e.mode||"terminal":"chat",agentName:j,agentType:T,status:g,title:$,messages:[...E,...D],resume:e.resume,hostIdeType:!Ye(e)&&!Ve(e)?e.type:void 0,workspaceName:c,displayPrimary:c||$||(Ye(e)?e.mode==="chat"?j:"Terminal":j),displaySecondary:d,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:k?P.buttons:void 0,modalMessage:k?P.message:void 0,streamSource:"native",tabKey:Yr(l,e.id),machineName:o,connectionState:i})}if(f&&(Ye(e)||Ve(e)))return n;for(const l of m){const j=l.activeModal&&Array.isArray(l.activeModal.buttons)&&l.activeModal.buttons.length>0,P=xl(l),k=Dd(l),g=`${e.id}:${k}`,N=l.title&&String(l.title).trim()||"",v=ga(N,l.agentName,l.agentType)?"":N,w=l.messages||[],M=Ra(s,[g,l.sessionId,l.instanceId]),T=Ia(w,M);(l.transport==="cdp-webview"||l.sessionId||l.providerSessionId||w.length>0||T.length>0||j||v||!["idle","panel_hidden","disconnected","not_monitored"].includes(P))&&n.push({routeId:e.id,sessionId:l.sessionId||l.instanceId,providerSessionId:l.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:l.transport||"cdp-webview",daemonId:e.daemonId||void 0,mode:"chat",agentName:l.agentName,agentType:l.agentType,status:P,title:v,messages:[...w,...T],hostIdeType:e.type,workspaceName:c,displayPrimary:c||x||v||d,displaySecondary:`${d} · ${l.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:l.lastMessagePreview,lastMessageRole:l.lastMessageRole,lastMessageAt:l.lastMessageAt,lastMessageHash:l.lastMessageHash,lastUpdated:l.lastUpdated||e.lastUpdated,modalButtons:j?l.activeModal.buttons:void 0,modalMessage:j?l.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Yr(l.sessionId||l.instanceId,g),machineName:o,connectionState:i})}return n.length===0&&n.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,mode:"chat",agentName:ba(e.type),agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:c,displayPrimary:c||d,displaySecondary:d,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Yr(e.sessionId||e.instanceId,e.id),connectionState:i}),n}function $d(e){const s=e.split(":");return s.length>=3&&(s[1]==="ide"||s[1]==="cli"||s[1]==="acp")?{daemonId:s[0],targetSessionId:s.slice(2).join(":")||void 0}:{daemonId:e}}function Bd(e,s){const r=$d(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Qo=[{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:"🏄"}],ei=[{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:"🧩"}],ti=[{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:"🟠"}],Kd=Qo,Wd=ei,Od=ti;function cs(...e){return nc(ac(e))}function Hd({icon:e,title:s,subtitle:r,badge:n,actions:o,className:i}){return t.jsxs("div",{className:cs("dashboard-header",i),children:[t.jsxs("div",{children:[t.jsxs("h1",{className:"header-title flex items-center gap-2",children:[t.jsx("span",{className:"flex items-center text-lg",children:e})," ",s,n&&t.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[n.count!==void 0?n.count:""," ",n.text]})]}),r&&t.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),o&&t.jsx("div",{className:"flex gap-2",children:o})]})}function si({icon:e,title:s,subtitle:r,badge:n,actions:o,widthClassName:i="max-w-6xl",contentClassName:c,children:d}){return t.jsxs("div",{className:"flex flex-col h-full",children:[t.jsx(Hd,{icon:e,title:s,subtitle:r,badge:n,actions:o}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:cs("mx-auto flex w-full flex-col gap-4",i,c),children:d})})]})}function Mt({title:e,icon:s,description:r,accentColor:n,className:o,children:i}){return t.jsxs("div",{className:cs("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]",o),style:n?{borderLeftColor:n}:void 0,children:[(e||r)&&t.jsxs("div",{className:"mb-4",children:[e&&t.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[s&&t.jsx("span",{className:"mr-1.5",children:s}),e]}),r&&t.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),i]})}function ri({icon:e,title:s,description:r,action:n,className:o}){return t.jsxs("div",{className:cs("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",o),children:[t.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),t.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:s}),t.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const Ud={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"},zd={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Fd({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:cs("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Ud[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:zd[e]}),t.jsx("span",{children:s})]}),r&&t.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}const Vd={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"},Gd={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function qd({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:cs("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Vd[e],r),children:[t.jsx("span",{className:cs("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Gd[e])}),n]})}const vn="adhdev:themechange";function Yd(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function ms(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function ps(e){return e==="system"?Yd():e}function ni(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function xr(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(vn,{detail:{preference:e,theme:s}}))}function Xd(){const e=ms(),s=ps(e);ni(s),xr(e,s)}function Un(){const[e,s]=a.useState(ms),[r,n]=a.useState(()=>ps(ms()));a.useEffect(()=>{ni(r)},[r]),a.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),d=m=>{if(e==="system"){const f=m.matches?"light":"dark";n(f),xr("system",f)}};return c.addEventListener("change",d),()=>c.removeEventListener("change",d)},[e]),a.useEffect(()=>{const c=m=>{const f=m.detail||{},p=f.preference,x=f.theme;s(p==="dark"||p==="light"||p==="system"?p:ms()),n(x==="dark"||x==="light"?x:ps(ms()))},d=m=>{if(m.key!=="theme")return;const f=ms(),p=ps(f);s(f),n(p)};return window.addEventListener(vn,c),window.addEventListener("storage",d),()=>{window.removeEventListener(vn,c),window.removeEventListener("storage",d)}},[]);const o=a.useCallback(c=>{const d=ps(c);s(c),n(d);try{localStorage.setItem("theme",c)}catch{}xr(c,d)},[]),i=a.useCallback(()=>{s(c=>{const d=c==="dark"?"light":c==="light"?"system":"dark",m=ps(d);n(m);try{localStorage.setItem("theme",d)}catch{}return xr(d,m),d})},[]);return{theme:r,preference:e,setPreference:o,cycleTheme:i,isDark:r==="dark"}}const La={dark:"Dark",light:"Light",system:"System"};function Jd({collapsed:e}){const{preference:s,cycleTheme:r}=Un(),n=s==="dark"?t.jsx(Dc,{size:16}):s==="light"?t.jsx(Lc,{size:16}):t.jsx(Ec,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${La[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:La[s]})]})}function Gt({label:e,description:s,checked:r,disabled:n,onChange:o,extra:i}){return t.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[t.jsxs("div",{className:"pr-4",children:[t.jsx("div",{className:"font-medium text-sm",children:e}),t.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:s})]}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,t.jsxs("button",{type:"button",role:"switch","aria-checked":r,"aria-disabled":n,disabled:n,onClick:()=>o(!r),className:`relative inline-flex items-center ${n?"cursor-not-allowed":"cursor-pointer"}`,children:[t.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:r?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),t.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${r?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function Zd({onPrefChange:e}){const[s,r]=Sl(),n=(o,i)=>{r({[o]:i}),e==null||e(o,i)};return t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(Gt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(_r,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:o=>n("globalEnabled",o)}),s.globalEnabled&&t.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&t.jsx(Gt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(kt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:o=>n("browserNotifications",o)}),s.globalEnabled&&s.browserNotifications&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.jsx(Gt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx($c,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:o=>n("completionAlert",o)}),t.jsx(Gt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Bc,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:o=>n("approvalAlert",o)}),t.jsx(Gt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ks,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:o=>n("disconnectAlert",o)})]}),!s.globalEnabled&&t.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function Sr(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function Qd(e,s){const r=Sr(e),n=Sr(s);if(!r||!n)return e.localeCompare(s);for(let o=0;o<3;o+=1){if(r[o]<n[o])return-1;if(r[o]>n[o])return 1}return 0}function ai(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function Ds(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||Qd(r,s)>=0)return!1;const n=Sr(r),o=Sr(s);return!n||!o?!1:n[0]!==o[0]||n[1]!==o[1]}function eu(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Xr(e,s){return e instanceof Error?e.message:s}function tu({ides:e,emptyMessage:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o}){const i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?t.jsx(ri,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:"No machines connected",description:s||"Install ADHDev on a machine and sign in to connect it here."}):t.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>t.jsx(ru,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o},c.id))})}function Da({title:e,message:s,confirmLabel:r,confirmColor:n,onConfirm:o,onCancel:i}){const c=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return Bs.createPortal(t.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:d=>d.stopPropagation(),children:[t.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),t.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:s}),t.jsxs("div",{className:"flex gap-2 justify-end",children:[t.jsx("button",{onClick:i,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:"Cancel"}),t.jsx("button",{onClick:o,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 su(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Kd,...Wd,...Od].find(o=>o.id===s||s.includes(o.id)||o.id.includes(s));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function ru({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o}){var F,D;const[i,c]=a.useState("idle"),[d,m]=a.useState(""),[f,p]=a.useState(null),[x,b]=a.useState("idle"),[S,A]=a.useState(""),u=e.version||null,h=((F=e.machine)==null?void 0:F.platform)||((D=e.system)==null?void 0:D.platform)||"",y=jt(e,{fallbackId:e.id}),l=h==="win32"?"🪟":h==="darwin"?"🍎":"🐧",j=s.filter(C=>C.daemonId===e.id&&C.transport==="cdp-page"),P=s.filter(C=>C.daemonId===e.id&&C.transport==="pty"),k=s.filter(C=>C.daemonId===e.id&&C.transport==="acp"),g=e.p2p,N=async()=>{if(r){c("upgrading"),m("Starting upgrade...");try{const C=eu(await r(e.id,"daemon_upgrade",{}));C.alreadyLatest?(c("done"),m(`Already on v${C.version||"latest"}.`)):C.upgraded||C.success?(c("done"),m(`Upgrade to v${C.version||"latest"} started. Daemon is restarting...`)):(c("error"),m(C.error||"Upgrade failed"))}catch(C){c("error"),m(Xr(C,"Connection lost during upgrade"))}}},v=async()=>{if(p(null),!!n){b("loading");try{await n(e.id),b("done"),A("Machine disconnected.")}catch(C){b("error"),A(Xr(C,"Failed to disconnect"))}}},w=async()=>{if(p(null),!!o){b("loading");try{await o(e.id),b("done"),A("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(C){b("error"),A(Xr(C,"Failed to revoke token"))}}},M="0.8.56",T=ai(e,M),$=Ds(e,M),E=j.length+P.length+k.length;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("span",{className:"text-xl",children:l}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-sm",children:y}),t.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[t.jsxs("span",{children:[e.id.substring(0,12),"…"]}),u&&t.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${T?"":"bg-bg-secondary"}`,style:T?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",u,!T&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&T&&t.jsx("button",{onClick:N,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${M}`,children:i==="upgrading"?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${$?"↑ Update now":`↑ Update${` to v${M}`}`}`}),n&&t.jsx("button",{onClick:()=>p("disconnect"),disabled:x==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),o&&t.jsx("button",{onClick:()=>p("revoke"),disabled:x==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),t.jsx(qd,{status:e.status==="online"?"online":"error"})]})]}),t.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[g&&t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${g.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${g.state==="connecting"||g.state==="new"?"animate-pulse":""}`,style:g.state==="connecting"||g.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",g.state==="connected"?"connected":g.state==="connecting"||g.state==="new"?"connecting...":g.state||"off"]}),g.peers!==void 0&&g.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",g.peers," peer",g.peers!==1?"s":"",")"]})]}),g&&E>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),E>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[j.map(C=>{const V=su(C.type),J=C.cdpConnected;return t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:V.icon}),t.jsx("span",{children:V.name}),J!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${J?"bg-green-400":"animate-pulse"}`,style:J?void 0:{background:"var(--status-warning)"},title:J?"CDP connected":"CDP connecting..."})]},C.id)}),P.map(C=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"⌨️"}),t.jsx("span",{children:C.cliName||"CLI"})]},C.id)),k.map(C=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"🔗"}),t.jsx("span",{children:C.cliName||"ACP"})]},C.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(d||S)&&t.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||x==="error"?"text-red-400":i==="done"||x==="done"?"text-green-400":"text-text-muted"}`,children:S||d})]}),f==="disconnect"&&t.jsx(Da,{title:"🔌 Disconnect Machine",message:`Disconnect "${y}" from ADHDev?
32
32
 
33
33
  This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
34
34
 
@@ -39,7 +39,7 @@ This will:
39
39
  • Delete the machine registration
40
40
  • Require restarting ADHDev on that machine
41
41
 
42
- Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:w,onCancel:()=>p(null)})]})}const nu=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function au(){const{preference:e,setPreference:s}=Un();return t.jsx("div",{className:"flex gap-2",children:nu.map(r=>t.jsxs("button",{onClick:()=>s(r.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===r.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===r.id?{color:"var(--accent-on-primary)"}:void 0,children:[t.jsx("span",{children:r.icon}),r.label]},r.id))})}function ou(e){const s=e.trim();return/^#[0-9a-fA-F]{6}$/.test(s)?s:/^#[0-9a-fA-F]{3}$/.test(s)?`#${s[1]}${s[1]}${s[2]}${s[2]}${s[3]}${s[3]}`:null}function iu(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Jr(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function Ea(e){const{r:s,g:r,b:n}=iu(e);return .2126*Jr(s)+.7152*Jr(r)+.0722*Jr(n)}function $a(e,s){const r=Ea(e),n=Ea(s),o=Math.max(r,n),i=Math.min(r,n);return(o+.05)/(i+.05)}function oi(e){const s=ou(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return $a(s,r)>=$a(s,n)?r:n}const wn={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},jn={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},cu=[{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"}}}],ii="adhdev-chat-theme",ci="adhdev-chat-theme-custom";function hr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(ii)||"ember"}catch{return"ember"}}function _t(e){try{const s=localStorage.getItem(ci);if(s){const r=JSON.parse(s);return{...e==="dark"?wn:jn,...r[e]}}}catch{}return e==="dark"?wn:jn}function sr(e,s){try{localStorage.setItem(ci,JSON.stringify({dark:e,light:s}))}catch{}}function Nt(e,s){const r=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16);return`rgba(${r}, ${n}, ${o}, ${s})`}function Cr(e,s){const r=Math.min(255,parseInt(e.slice(1,3),16)+s),n=Math.min(255,parseInt(e.slice(3,5),16)+s),o=Math.min(255,parseInt(e.slice(5,7),16)+s);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`}const lu={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Es(e,s){var o;const r=(o=lu[e])==null?void 0:o[s];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",Cr(r,24)),n.style.setProperty("--accent-on-primary",oi(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Cr(r,18)})`),n.style.setProperty("--border-accent",Nt(r,.35)),n.style.setProperty("--nav-active-bg",Nt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Nt(r,.06)}`)}function Qt(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",Nt(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",Nt(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",Nt(e.borderSubtle,.25)),s.style.setProperty("--text-primary",e.textPrimary),s.style.setProperty("--text-secondary",e.textSecondary),s.style.setProperty("--text-muted",e.textMuted),s.style.setProperty("--border-subtle",Nt(e.borderSubtle,.5)),s.style.setProperty("--border-default",Nt(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",Cr(e.accentColor,30)),s.style.setProperty("--accent-on-primary",oi(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Cr(e.accentColor,40)})`),s.style.setProperty("--border-accent",Nt(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",Nt(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Nt(e.accentColor,.06)}`),s.style.setProperty("--chat-user-bg",e.userBubble),s.style.setProperty("--chat-user-color",e.userText),s.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),s.style.setProperty("--chat-assistant-bg",e.assistantBubble),s.style.setProperty("--chat-assistant-color",e.assistantText),s.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),s.style.setProperty("--chat-assistant-border",`1px solid ${Nt(e.accentColor,.12)}`),s.style.setProperty("--chat-container-bg",e.containerBg),s.style.setProperty("--dashboard-pane-bg",e.containerBg),s.style.setProperty("--chat-thought-accent",e.accentColor),s.style.setProperty("--chat-tool-accent",e.accentColor),s.style.setProperty("--chat-action-color",e.accentColor),s.style.setProperty("--chat-send-bg",e.sendButton),s.style.setProperty("--chat-input-border",e.inputBorder)}function zn(){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 du(e){try{localStorage.setItem(ii,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=es()?"dark":"light";Qt(_t(s))}else zn(),Es(e,es()?"dark":"light")}function uu(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=hr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=es()?"dark":"light";Qt(_t(s))}else zn(),Es(e,es()?"dark":"light")}function es(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function ht({label:e,value:s,onChange:r}){return t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[t.jsx("input",{type:"color",value:s,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),t.jsx("input",{type:"text",value:s,onChange:n=>{/^#[0-9a-fA-F]{0,6}$/.test(n.target.value)&&r(n.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function Is({title:e,children:s}){return t.jsxs("div",{style:{marginBottom:14},children:[t.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s})]})}function mu({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,o]=a.useState(()=>_t(r));a.useEffect(()=>{o(_t(r))},[r]);const i=a.useCallback((c,d)=>{o(m=>{const f={...m,[c]:d},x=_t(r==="dark"?"light":"dark");return r==="dark"?sr(f,x):sr(x,f),Qt(f),s(f),f})},[r,s]);return t.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[t.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",t.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsxs(Is,{title:"App Background",children:[t.jsx(ht,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),t.jsx(ht,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),t.jsx(ht,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),t.jsxs(Is,{title:"App Text",children:[t.jsx(ht,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),t.jsx(ht,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),t.jsx(ht,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),t.jsxs(Is,{title:"Borders & Accent",children:[t.jsx(ht,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),t.jsx(ht,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),t.jsx(ht,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),t.jsxs("div",{children:[t.jsxs(Is,{title:"Chat Bubbles",children:[t.jsx(ht,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),t.jsx(ht,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),t.jsx(ht,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),t.jsx(ht,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),t.jsxs(Is,{title:"Chat Layout",children:[t.jsx(ht,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),t.jsx(ht,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),t.jsx(ht,{label:"Input border",value:n.inputBorder,onChange:c=>i("inputBorder",c)}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[t.jsx("input",{type:"range",min:4,max:24,value:n.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),t.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),t.jsx("button",{onClick:()=>{const c=e?wn:jn,m=_t(e?"light":"dark");e?sr(c,m):sr(m,c),o(c),Qt(c),s(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:"Reset to defaults"})]})}function pu(){const[e,s]=a.useState(hr),[r,n]=a.useState(!0),[o,i]=a.useState(()=>_t("dark"));a.useEffect(()=>{n(es());const m=new MutationObserver(()=>{const x=es();n(x);const b=hr();b==="custom"?Qt(_t(x?"dark":"light")):Es(b,x?"dark":"light")});m.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const f=window.matchMedia("(prefers-color-scheme: dark)"),p=()=>{const x=es();n(x);const b=hr();b==="custom"?Qt(_t(x?"dark":"light")):Es(b,x?"dark":"light")};return f.addEventListener("change",p),()=>{m.disconnect(),f.removeEventListener("change",p)}},[]),a.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?Qt(_t(r?"dark":"light")):(zn(),Es(e,r?"dark":"light"))},[e,r]),a.useEffect(()=>{i(_t(r?"dark":"light"))},[r]);const c=m=>{s(m),du(m)},d=[...cu,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText},light:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText}}}];return t.jsxs("div",{children:[t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:d.map(m=>{const f=e===m.id,p=r?m.preview.dark:m.preview.light,x=m.id==="honey"||m.id==="ember"?"#1a1a1a":m.id==="custom"?o.userText:"#fff";return t.jsxs("button",{onClick:()=>c(m.id),className:"text-left rounded-xl p-3 transition-all",style:{background:f?"var(--bg-glass-hover)":"var(--bg-glass)",border:f?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:f?1:.75},children:[t.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:p.containerBg},children:[t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:p.assistantBubble,border:p.assistantBorder,color:p.textColor},children:"Hello! How can I help?"}),t.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:p.userBubble,color:x},children:"Fix the bug please"}),t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:p.assistantBubble,border:p.assistantBorder,color:p.textColor},children:"On it! ✨"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[f&&t.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:m.id==="custom"?"🎨 Custom":m.name}),t.jsx("div",{className:"text-[10px] text-text-muted",children:m.description})]})]})]},m.id)})}),e==="custom"&&t.jsx(mu,{dark:r,onColorsChange:m=>i(m)})]})}const li="adhdev_mobileDashboardMode_v1";function di(){try{return localStorage.getItem(li)==="workspace"?"workspace":"chat"}catch{return"chat"}}function fu(e){try{localStorage.setItem(li,e)}catch{}}function xu(){const[e,s]=a.useState(!0);return a.useEffect(()=>{s(di()==="chat")},[]),t.jsx(Gt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Kt,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:r=>{s(r),fu(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}function hu(e,s,r){return{...e||{},id:s,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:r.timestamp,platform:r.machine.platform,machine:{...(e==null?void 0:e.machine)||{},...r.machine}}}function bu(e,s){const{sendData:r}=Ct(),{injectEntries:n,getIdes:o}=vr(),i=Array.from(new Set(e.filter(Boolean))).join("|");a.useEffect(()=>{if(!(s!=null&&s.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const d=c.map(m=>Ot.subscribe({sendData:r},m,{type:"subscribe",topic:"machine.runtime",key:`machine:${m}`,params:{intervalMs:s==null?void 0:s.intervalMs}},f=>{const p=o().find(b=>b.id===m),x=hu(p,m,f);n([x])}));return()=>{d.forEach(m=>m())}},[i,o,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}const gu=4e3;function ui(e,s){const{sendData:r}=Ct(),[n,o]=a.useState(null),[i,c]=a.useState(!1);return a.useEffect(()=>{if(!e){o(null),c(!1);return}if(!(s!=null&&s.enabled)||!r){c(!1);return}o(null),c(!0);let d=null;const m=Ot.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(s==null?void 0:s.includeSessions)!==!1,...typeof(s==null?void 0:s.limit)=="number"?{limit:s.limit}:{},...typeof(s==null?void 0:s.intervalMs)=="number"?{intervalMs:s.intervalMs}:{}}},f=>{d&&(clearTimeout(d),d=null),o(f.diagnostics),c(!1)});return m.initialSendAccepted?d=setTimeout(()=>{c(!1)},gu):c(!1),()=>{d&&clearTimeout(d),m()}},[e,s==null?void 0:s.enabled,s==null?void 0:s.includeSessions,s==null?void 0:s.intervalMs,s==null?void 0:s.limit,r]),{diagnostics:n,loading:i,applyDiagnostics:o}}function yu(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function mi(e){const{sendData:s}=Ct(),[r,n]=a.useState({});return a.useEffect(()=>{const o=yu(e);if(!o||!e.sessionId||!s){n({});return}const i=Ot.subscribe({sendData:s},o,{type:"subscribe",topic:"session.modal",key:`daemon:${o}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),ss.record({interactionId:c.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:c.status,modalButtonCount:Array.isArray(c.modalButtons)?c.modalButtons.length:0}})});return()=>{i()}},[e.daemonId,e.routeId,e.sessionId,s]),r}const pi="adhdev_hiddenTabs";function vu(){try{const e=localStorage.getItem(pi);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ds(e){try{localStorage.setItem(pi,JSON.stringify([...e]))}catch{}}function wu(){const[e,s]=a.useState(vu),r=a.useCallback(f=>{s(p=>{const x=new Set(p);return x.has(f)?x.delete(f):x.add(f),ds(x),x})},[]),n=a.useCallback(f=>{s(p=>{if(p.has(f))return p;const x=new Set(p);return x.add(f),ds(x),x})},[]),o=a.useCallback(f=>{s(p=>{if(!p.has(f))return p;const x=new Set(p);return x.delete(f),ds(x),x})},[]),i=a.useCallback(()=>{s(f=>{if(f.size===0)return f;const p=new Set;return ds(p),p})},[]),c=a.useCallback((f,p)=>{s(x=>{const b=new Set(x);for(const S of p)b.add(S);return ds(b),b})},[]),d=a.useCallback((f,p)=>{s(x=>{const b=new Set(x);for(const S of p)b.delete(S);return ds(b),b})},[]),m=a.useCallback(f=>e.has(f),[e]);return{hiddenTabs:e,toggleTab:r,hideTab:n,showTab:o,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:d,isHidden:m}}function ju({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){a.useEffect(()=>{Il()},[]);const o=a.useMemo(()=>e.map(i=>({id:i.tabKey,name:Uo(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Al(o),a.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(d=>{const m=Date.now(),f={};for(const[p,x]of Object.entries(d))m-x<5e3&&(f[p]=x);return Object.keys(f).length===Object.keys(d).length?d:f})},5500);return()=>clearTimeout(c)},[s,r]),a.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(d=>{const m=d.filter(f=>f.timestamp>c).slice(-100);return m.length===d.length?d:m})},6e4);return()=>clearInterval(i)},[n]),null}function ku(e){const s=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of s){const o=r.get(n.id);if(!o){r.set(n.id,n);continue}const i=(o.workspace?1:0)+(o.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>i||(n.timestamp||0)>(o.timestamp||0))&&r.set(n.id,n)}return Array.from(r.values())}function rr(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==s[r])return!1;return!0}function Nu(e,s){const r=Date.now();return e.map(n=>{const o=s[n.tabKey];return o&&r-o<5e3?{...n,messages:[],title:""}:n})}function Su(e,s){const r=[],n=e.sessionId||e.instanceId;r.push({key:e.id,ref:s[e.id]}),n&&r.push({key:n,ref:s[n]});for(const o of e.childSessions||[]){const i=o.id||o.providerType,c=`${e.id}:${i}`;r.push({key:c,ref:s[c]}),r.push({key:o.id,ref:s[o.id]})}return r}function Cu(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r].key!==s[r].key||e[r].ref!==s[r].ref)return!1;return!0}function Iu(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function Tu(e){const s=Iu(e);if(!s)return`empty:${e.messages.length}`;if(s.id)return`id:${String(s.id)}`;if(s._localId)return`local:${String(s._localId)}`;const r=String(s.role||""),n=as(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Au({ides:e,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:o}){const i=a.useRef([]),c=a.useRef([]),d=a.useRef([]),m=a.useRef([]),f=a.useMemo(()=>{const g=ku(e);return rr(i.current,g)?i.current:(i.current=g,g)},[e]),p=a.useMemo(()=>Jo(e),[e]),x=a.useRef(new Map),b=a.useRef(new Map),S=a.useMemo(()=>{const g=new Map,N=[];for(const T of f){const{connectionState:$="new",machineName:E}=Zo(T,{machineNames:p,connectionStates:s,defaultConnectionState:"new"}),F=Su(T,r),D=x.current.get(T.id);if(D&&D.ide===T&&D.connectionState===$&&D.machineName===E&&Cu(D.localRefs,F)){g.set(T.id,D),N.push(...D.conversations);continue}const C=Hn(T,r,{machineNames:p,connectionStates:s,defaultConnectionState:"new"}),V={ide:T,connectionState:$,machineName:E,localRefs:F,conversations:C};g.set(T.id,V),N.push(...C)}x.current=g;const v=new Map,w=T=>{const $=Tu(T),E=b.current.get(T.tabKey);if(E&&E.signature===$)return v.set(T.tabKey,E),E.timestamp;const F={signature:$,timestamp:Fo(T)||(E==null?void 0:E.timestamp)||0};return v.set(T.tabKey,F),F.timestamp},M=[...N].sort((T,$)=>kr(T,$,w));return b.current=v,M},[f,r,s,p]),A=a.useMemo(()=>{const g=Nu(S,n);return rr(c.current,g)?c.current:(c.current=g,g)},[S,n]),u=a.useMemo(()=>{const g=new Map,N=Array.from(new Set(A.map(v=>v.routeId)));for(const v of N){const w=Lt(A,v);w&&g.set(v,w)}return g},[A]),h=a.useMemo(()=>{const g=new Map;for(const N of A)if(N.sessionId&&g.set(N.sessionId,N),N.streamSource==="native"&&N.sessionId){const v=u.get(N.routeId);v&&g.set(N.sessionId,v)}return g},[A,u]),y=a.useMemo(()=>{const g=new Map;for(const N of A)N.sessionId&&g.set(N.sessionId,N),g.set(N.routeId,u.get(N.routeId)||N),g.set(N.tabKey,N);return g},[A,u]),l=a.useCallback(g=>{if(g)return h.get(g)},[h]),j=a.useCallback(g=>{if(g)return y.get(g)},[y]),P=a.useMemo(()=>{const g=A.filter(N=>!o.has(N.tabKey));return rr(d.current,g)?d.current:(d.current=g,g)},[A,o]),k=a.useMemo(()=>{const g=P.map(N=>N.tabKey);return rr(m.current,g)?m.current:(m.current=g,g)},[P]);return{chatIdes:f,conversations:A,visibleConversations:P,visibleTabKeys:k,resolveConversationBySessionId:l,resolveConversationByTarget:j}}function Mu({isMobile:e,urlActiveTab:s,resolveConversationBySessionId:r,setSearchParams:n}){const o=a.useMemo(()=>{var d;return e||!s?null:((d=r(s))==null?void 0:d.tabKey)??null},[e,r,s]),i=a.useMemo(()=>{var d;return!e||!s?null:((d=r(s))==null?void 0:d.tabKey)??null},[e,r,s]),c=a.useCallback(()=>{s&&n(d=>{const m=new URLSearchParams(d);return m.delete("activeTab"),m},{replace:!0})},[n,s]);return{requestedDesktopTabKey:o,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function _u({ides:e,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:o}){a.useEffect(()=>{tt.setIdes(e)},[e]),a.useEffect(()=>{tt.setResolveAction((i,c,d)=>{s(i,c,d).catch(()=>{})})},[s]),a.useEffect(()=>{const i=tt.onToast(m=>{r(p=>p.some(b=>b.message===m.message&&m.timestamp-b.timestamp<3e3)?p:[...p.slice(-4),{id:m.id,message:m.message,type:m.type,timestamp:m.timestamp,targetKey:m.targetKey,actions:m.actions}]);const f=m.duration||5e3;setTimeout(()=>r(p=>p.filter(x=>x.id!==m.id)),f)}),c=tt.onSystemMessage((m,f)=>{var S,A;const p=o(m),x=(S=f._localId)==null?void 0:S.startsWith("sys_approval_"),b=!!(p&&(p.status==="waiting_approval"||(A=p.modalButtons)!=null&&A.length||p.modalMessage));x&&b||n(u=>({...u,[m]:[...u[m]||[],f]}))}),d=tt.onClearSystemMessage((m,f)=>{n(p=>{var x;return(x=p[m])!=null&&x.length?{...p,[m]:p[m].filter(b=>{var S;return!(b.role==="system"&&((S=b._localId)!=null&&S.startsWith(f)))})}:p})});return()=>{i(),c(),d()}},[r,n]),a.useEffect(()=>{const i=Wo.on("status_event",c=>{tt.handleRawEvent(c,"ws")});return()=>{i()}},[]),a.useEffect(()=>{var c;const i=d=>{var h;const m=d.data;if((m==null?void 0:m.type)!=="notification_action"||typeof m.action!="string"||!m.action.startsWith("approval_")||!(m.daemonId||m.targetSessionId||m.targetKey))return;const f=m.targetSessionId||m.targetKey||m.daemonId,p=o(f),x=(p==null?void 0:p.routeId)||m.daemonId;if(!x)return;const b=Number(m.buttonIndex),S=m.button||((h=p==null?void 0:p.modalButtons)==null?void 0:h[b])||"Approve",A=String(S).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),u=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(A);s(x,"resolve_action",{action:u?"approve":"reject",button:S,...Number.isFinite(b)&&{buttonIndex:b},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...m.targetSessionId&&{targetSessionId:m.targetSessionId}}).catch(y=>console.error("[SW Action] approval failed:",y))};return(c=navigator.serviceWorker)==null||c.addEventListener("message",i),()=>{var d;return(d=navigator.serviceWorker)==null?void 0:d.removeEventListener("message",i)}},[o,s])}const Pu="adhdev_dashboardLayout_v1",Ru="adhdev_dashboardDockview_v1",Lu="adhdev_dashboardDockviewHiddenRestore_v1",Ts={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Fn(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function fi(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function xi(e){return`${Pu}:${e}`}function Du(e){const s=xi(e);return Fn(s,null)}function Eu(e,s){try{const r=s.groupAssignments.length===0&&s.focusedGroup===0&&Object.keys(s.groupActiveTabIds).length===0&&Object.keys(s.groupTabOrders).length===0&&s.groupSizes.length===0,n=xi(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function hi(e){return`${Ru}:${e}`}function $u(e){const s=hi(e);return Fn(s,null)}function Bu(e,s){try{const r=hi(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function bi(e){return`${Lu}:${e}`}function Ku(e){const s=bi(e);return Fn(s,{})}function Wu(e,s){try{const r=bi(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Ou(){return{groupAssignments:[...Ts.groupAssignments],focusedGroup:Ts.focusedGroup,groupActiveTabIds:{...Ts.groupActiveTabIds},groupTabOrders:{...Ts.groupTabOrders},groupSizes:[...Ts.groupSizes]}}function Hu(){const[e]=a.useState(()=>fi(typeof window<"u"?window.innerWidth:1280)),[s,r]=a.useState(()=>new Map),[n,o]=a.useState(0),[i,c]=a.useState({}),[d,m]=a.useState({}),[f,p]=a.useState([]),[x,b]=a.useState(()=>typeof window<"u"&&window.innerWidth<768),[S,A]=a.useState(!1),u=a.useCallback(()=>{if(S)return;const h=Du(e)??Ou();r(new Map(h.groupAssignments)),o(h.focusedGroup),c(h.groupActiveTabIds),m(h.groupTabOrders),p(h.groupSizes),A(!0)},[S,e]);return a.useEffect(()=>{S&&Eu(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:d,groupSizes:f})},[S,e,s,n,i,d,f]),a.useEffect(()=>{const h=window.matchMedia("(max-width: 767px)"),y=l=>b(l.matches);return h.addEventListener("change",y),()=>h.removeEventListener("change",y)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:o,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:d,setGroupTabOrders:m,groupSizes:f,setGroupSizes:p,isMobile:x,hasHydratedStoredLayout:S,hydrateStoredLayout:u}}function Uu(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=[s.providerSessionId,s.sessionId].filter(o=>typeof o=="string"&&o.length>0);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function zu({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:o,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:d,setSearchParams:m,historyModalOpen:f,activeConv:p,isRefreshingHistory:x,ides:b,handleRefreshHistory:S}){const A=a.useRef(!1),u=a.useRef(!1),h=a.useRef(null),y=a.useRef(!1);a.useEffect(()=>{if(!e||A.current||s.length===0)return;if(!o){i();return}const l=r(e);if(!l)return;const j=n.get(l.tabKey)??0;c(P=>({...P,[j]:l.tabKey})),d(j),A.current=!0,u.current=!0,h.current!=null&&(window.clearTimeout(h.current),h.current=null),m(P=>{const k=new URLSearchParams(P);return k.delete("activeTab"),k},{replace:!0})},[e,s,r,n,o,i,c,d,m]),a.useEffect(()=>{if(!(u.current||o)&&s.length!==0){if(!e){i(),u.current=!0;return}if(A.current){u.current=!0;return}if(h.current==null)return h.current=window.setTimeout(()=>{h.current=null,!(u.current||o)&&(i(),u.current=!0)},1500),()=>{h.current!=null&&(window.clearTimeout(h.current),h.current=null)}}},[e,s.length,o,i]),a.useEffect(()=>{if(!f){y.current=!1;return}if(!p||y.current||x)return;const l=b.find(j=>j.id===p.routeId);l&&(!l.chats||l.chats.length===0||Uu(l.chats,p))&&(y.current=!0,S())},[f,p,x,b,S]),a.useEffect(()=>{if(!p)return;let l=null,j=0,P=-1,k=0;const g=()=>{l=null;const N=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(w=>w.offsetParent!==null);if(N.length===0){j<18&&(j+=1,l=requestAnimationFrame(g));return}let v=0;for(const w of N)w.scrollTop=w.scrollHeight,v+=w.scrollHeight;v===P?k+=1:(k=0,P=v),j+=1,!(k>=2||j>=18)&&(l=requestAnimationFrame(g))};return l=requestAnimationFrame(g),()=>{l!=null&&cancelAnimationFrame(l)}},[p==null?void 0:p.tabKey])}function Fu({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:o,conversations:i,ides:c,resolveConversationByTarget:d}){const[m,f]=a.useState(null),[p,x]=a.useState(null),b=a.useMemo(()=>{if(e||!n)return null;const y=d(n);return y&&!Ye(y)&&!Ve(y)?y:null},[e,n,d]),S=a.useMemo(()=>{const y=m==null?void 0:m.routeId;if(!y)return null;const l=m!=null&&m.tabKey?i.find(j=>j.tabKey===m.tabKey):o?i.find(j=>j.tabKey===o):null;return(l==null?void 0:l.routeId)===y?l:Lt(i,y)},[i,m,o]),A=a.useMemo(()=>{if(S)return c.find(y=>y.id===S.routeId)},[c,S]);a.useEffect(()=>{b&&(f({routeId:b.routeId,tabKey:wa(b)}),x(b),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,b]);const u=a.useCallback(y=>{y&&(f({routeId:y.routeId,tabKey:wa(y)}),x(y))},[]),h=a.useCallback(()=>{f(null),x(null)},[]);return{remoteDialogConv:S,remoteDialogIdeEntry:A,remoteDialogActiveConv:p,setRemoteDialogActiveConv:x,openRemoteDialog:u,closeRemoteDialog:h}}function hs(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:Ye(e)||Ve(e)?{agentType:wt(e)}:e.streamSource==="agent-stream"?{agentType:wt(e)}:s}function Us(e){return e?wr(e):""}function As(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function Zr(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0];if((r==null?void 0:r.active)===!0)return!0;const n=[s.providerSessionId,s.sessionId].filter(o=>typeof o=="string"&&o.length>0);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Ba({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:o,setLocalUserMessages:i,setClearedTabs:c}){const[d,m]=a.useState(!1),[f,p]=a.useState(!1),x=a.useCallback(async u=>{try{await e("standalone","launch_ide",{ideType:u,enableCdp:!0})}catch(h){console.error("Launch failed",h)}},[e]),b=a.useCallback(async(u,h)=>{try{const y=u||(s==null?void 0:s.daemonId)||"",l=await e(y,"switch_chat",{id:h,sessionId:h,...hs(s)}),j=l==null?void 0:l.result;if((l==null?void 0:l.success)===!0||j==="switched"||j==="switched-by-title")return;j===!1||j==="not_found"?As(o,"⚠️ Session tab not found — try refreshing history"):typeof j=="string"&&j.startsWith("error:")?As(o,`⚠️ Switch error: ${j}`):As(o,"⚠️ Session switch failed")}catch(y){console.error("Switch failed",y),As(o,`❌ Switch failed: ${y.message||"connection error"}`)}},[s,e,o]),S=a.useCallback(async()=>{if(!(!s||d)){m(!0);try{const u=Us(s);await e(u,"new_chat",{...hs(s)}),c(h=>({...h,[s.tabKey]:Date.now()})),i(h=>({...h,[s.tabKey]:[]}))}catch(u){console.error("New chat failed",u)}finally{m(!1)}}},[s,d,e,c,i]),A=a.useCallback(async()=>{var u,h;if(!(!s||f)){p(!0);try{const y=Us(s),l=async()=>e(y,"list_chats",{forceExpand:!0,...hs(s)});let j=await l(),P=(j==null?void 0:j.chats)||((u=j==null?void 0:j.result)==null?void 0:u.chats);Zr(P,s)&&(await new Promise(k=>setTimeout(k,450)),j=await l(),P=(j==null?void 0:j.chats)||((h=j==null?void 0:j.result)==null?void 0:h.chats)),j!=null&&j.success&&Array.isArray(P)&&(n(s.routeId,P),Zr(P,s)&&!Zr(r,s)&&As(o,"⚠️ History dialog did not fully open — try once more"))}catch(y){console.error("Refresh history failed",y)}finally{p(!1)}}},[s,r,f,e,n,o]);return{isCreatingChat:d,isRefreshingHistory:f,handleLaunchIde:x,handleSwitchSession:b,handleNewChat:S,handleRefreshHistory:A}}function Vu(e,s){if(e.size!==s.size)return!1;for(const[r,n]of e)if(s.get(r)!==n)return!1;return!0}function Gu(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function Ka(e,s){const r=Object.keys(e),n=Object.keys(s);return r.length!==n.length?!1:r.every(o=>s[Number(o)]===e[Number(o)])}function nr(e,s){const r=new Set(s),n=s.length>0?[0]:[];for(const[c,d]of e)!r.has(c)||d<=0||n.includes(d)||n.push(d);n.sort((c,d)=>c-d);const o={};n.forEach((c,d)=>{o[c]=d}),n.length===0&&(o[0]=0);const i=new Map;for(const[c,d]of e){if(!r.has(c)||d<=0)continue;const m=o[d];typeof m=="number"&&m>0&&i.set(c,m)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:o,usedGroups:n}}function Wa(e,s){const r={};for(const[n,o]of Object.entries(e)){const i=s[Number(n)];typeof i=="number"&&(r[i]=o)}return r}function qu(e,s,r){if(s.length===0)return 0;if(typeof r[e]=="number")return r[e];const n=[...s].reverse().find(o=>o<e)??s[0];return r[n]??0}function Yu(e,s,r){if(s.length<=1)return[];const n=s.map(c=>e[c]).filter(c=>Number.isFinite(c)),o=n.length===s.length?n:Array(r).fill(100/r),i=o.reduce((c,d)=>c+d,0);return i>0?o.map(c=>c/i*100):Array(r).fill(100/r)}function Oa(e,s){const r={};for(const[n,o]of Object.entries(e)){const i=Number(n);r[i>=s?i+1:i]=o}return r}function Ha(e){return Array(e).fill(100/e)}function Xu({groupAssignments:e,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:o,groupSizes:i,setGroupSizes:c,isMobile:d,visibleConversations:m,visibleTabKeys:f}){const p=a.useRef(null),x=a.useMemo(()=>nr(e,f),[e,f]),b=x.assignments,S=a.useMemo(()=>d?1:x.groupCount,[x.groupCount,d]),A=S>1,u=a.useCallback((k,g)=>{s(N=>{const v=new Map(nr(N,f).assignments);return g===0?v.delete(k):v.set(k,g),v}),n(N=>({...N,[g]:k})),r(g)},[s,f,n,r]),h=a.useCallback(k=>{s(g=>{const N=nr(g,f).assignments,v=new Map;for(const[w,M]of N)M!==k&&(M>k?v.set(w,M-1):v.set(w,M));return v}),c(g=>{if(g.length<=1)return[];const N=[...g];N.splice(k,1);const v=N.reduce((w,M)=>w+M,0);return v>0?N.map(w=>w/v*100):[]}),r(0)},[s,f,c,r]),y=a.useCallback((k,g)=>{g.preventDefault();const N=p.current;if(!N)return;const v=g.clientX,w=N.offsetWidth,M=i.length===S?[...i]:Ha(S),T=E=>{const D=(E.clientX-v)/w*100,C=[...M];C[k]=Math.max(15,M[k]+D),C[k+1]=Math.max(15,M[k+1]-D),c(C)},$=()=>{document.removeEventListener("mousemove",T),document.removeEventListener("mouseup",$),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",T),document.addEventListener("mouseup",$)},[i,S,c]),l=a.useCallback((k,g,N)=>{if(S>=4)return;const v=N==="left"?g:g+1;s(w=>{const M=nr(w,f).assignments,T=new Map;for(const $ of m){const E=M.get($.tabKey)??0,F=E>=v?E+1:E;F>0&&T.set($.tabKey,F)}return v>0&&T.set(k,v),T}),c(w=>{const M=w.length===S?[...w]:Ha(S),T=M[g]??100/S,$=Math.max(15,T/2),E=Math.max(15,T/2),F=[...M];F[g]=$,F.splice(v,0,E);const D=F.reduce((C,V)=>C+V,0);return F.map(C=>C/D*100)}),n(w=>{const M=Oa(w,v);return M[v]=k,M}),o(w=>{const M=Oa(w,v);return M[v]=[k],M}),r(v)},[S,s,f,m,c,n,o,r]);a.useEffect(()=>{Vu(e,b)||s(b)},[e,b,s]),a.useEffect(()=>{const{mapping:k,usedGroups:g}=x;n(N=>{const v=Wa(N,k);return Ka(N,v)?N:v}),o(N=>{const v=Wa(N,k);return Ka(N,v)?N:v}),r(N=>{const v=d?0:qu(N,g,k);return N===v?N:v}),c(N=>{const v=d?[]:Yu(N,g,x.groupCount);return Gu(N,v)?N:v})},[x,d,n,o,r,c]);const j=a.useMemo(()=>{const k=Array.from({length:S},()=>[]);for(const g of m){const N=b.get(g.tabKey)??0,v=Math.min(N,S-1);k[v].push(g)}return k},[m,b,S]),P=a.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:p,normalizedGroupAssignments:b,numGroups:S,isSplitMode:A,groupedConvs:j,moveTabToGroup:u,closeGroup:h,handleResizeStart:y,splitTabRelative:l,clearAllSplits:P}}function Ju({ides:e,sendDaemonCommand:s}){const r="0.8.54",n=a.useMemo(()=>e.filter(p=>p.type!=="adhdev-daemon"?!1:ai(p,r)).sort((p,x)=>Number(Ds(x,r))-Number(Ds(p,r))),[r,e]),o=a.useMemo(()=>n.some(p=>Ds(p,r)),[r,n]),[i,c]=a.useState(!1),[d,m]=a.useState({}),f=a.useCallback(async p=>{var x,b;m(S=>({...S,[p]:"upgrading"}));try{const S=await s(p,"daemon_upgrade",{});(x=S==null?void 0:S.result)!=null&&x.upgraded||(b=S==null?void 0:S.result)!=null&&b.success?m(A=>({...A,[p]:"done"})):m(A=>({...A,[p]:"error"}))}catch{m(S=>({...S,[p]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:o,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:f}}function Ua(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Vn(e){return e instanceof Error?e.message:String(e||"")}function za(e){const s=Vn(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Fa(e,s){const r=Vn(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function Lr({sendDaemonCommand:e,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:o}){const[i,c]=a.useState(!1),[d,m]=a.useState(!1),f=a.useRef(!1),p=a.useRef(null),x=a.useCallback(async u=>{if(!s)return;const h=u.trim();if(!h||f.current)return;const y=s.tabKey,l=Date.now(),j=p.current;if(j&&j.tabKey===y&&j.message===h&&l-j.timestamp<2e3)return;f.current=!0,m(!0),p.current={tabKey:y,message:h,timestamp:l};const P=`${l}-${Math.random().toString(36).slice(2,8)}`,k={role:"user",content:h,timestamp:l,_localId:P},g=!(Ye(s)||Ve(s));g&&r(N=>({...N,[y]:[...N[y]||[],k]}));try{const N=Us(s);if(!N)return;const v=await e(N,"send_chat",{message:h,...hs(s)}),w=Ua(v);if(g&&(w!=null&&w.deduplicated||(w==null?void 0:w.sent)===!1)){r(M=>({...M,[y]:(M[y]||[]).filter(T=>T._localId!==P)}));return}if((w==null?void 0:w.success)===!1)throw new Error((w==null?void 0:w.error)||"Send failed");setTimeout(()=>{const M=Date.now()-6e4;r(T=>{const $=T[y];if(!$)return T;const E=$.filter(F=>F.timestamp>M);return E.length===$.length?T:{...T,[y]:E}})},6e4)}catch(N){const v=Vn(N);v.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",v):console.error("Send failed",N),g&&r(w=>({...w,[y]:(w[y]||[]).filter(M=>M._localId!==P)}))}finally{f.current=!1,m(!1)}},[s,e,r]),b=a.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await e(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(u){console.error("Relaunch failed",u)}},[s,e]),S=a.useCallback(async u=>{if(s)try{const y=(s.modalButtons||[]).indexOf(u),l=u.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),j=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(l),P=Us(s);if(!P)return;const k=await e(P,"resolve_action",{button:u,action:j?"approve":"reject",...y>=0&&{buttonIndex:y},...hs(s)}),g=Ua(k);g.success||n(N=>[...N,{routeId:s.tabKey,text:Fa(u,g==null?void 0:g.error),timestamp:Date.now()}])}catch(h){za(h)||console.error("[ModalButton] Error:",h),n(y=>[...y,{routeId:s.tabKey,text:za(h)?Fa(u,h):`❌ **${u}** error`,timestamp:Date.now()}])}},[s,e,n]),A=a.useCallback(async()=>{if(!(!s||i)){c(!0);try{await e(s.routeId,"focus_session",{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(u){console.error("Focus agent failed",u)}finally{c(!1)}}},[s,i,e]);return{isSendingChat:d,isFocusingAgent:i,handleSendChat:x,handleRelaunch:b,handleModalButton:S,handleFocusAgent:A}}const Gn=a.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:o,terminalRef:i,handleModalButton:c,handleRelaunch:d,handleSendChat:m,isSendingChat:f,handleFocusAgent:p,isFocusingAgent:x,actionLogs:b,userName:S,scrollToBottomRequestNonce:A,isInputActive:u=!0}){const h=mi(s),y=h.status||h.modalMessage||h.modalButtons?{...s,...h.status?{status:h.status}:{},...h.modalMessage!==void 0?{modalMessage:h.modalMessage}:{},...h.modalButtons!==void 0?{modalButtons:h.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(Io,{activeConv:y,onModalButton:c}),y.transport!=="pty"&&y.transport!=="acp"&&y.cdpConnected===!1?t.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:t.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[t.jsx("span",{className:"text-sm",children:t.jsx(ns,{size:14})}),t.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),t.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:d,children:"Relaunch with CDP"})]})}):null,y.transport==="pty"?t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{display:n?"flex":"none",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(vd,{activeConv:y,clearToken:r,terminalRef:i,handleSendChat:m,isSendingChat:f,isVisible:n})}),!n&&t.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(bn,{activeConv:y,ideEntry:o,handleSendChat:m,isSendingChat:f,handleFocusAgent:p,isFocusingAgent:x,actionLogs:b,userName:S,scrollToBottomRequestNonce:A,isInputActive:u})})]}):t.jsx(bn,{activeConv:y,ideEntry:o,handleSendChat:m,isSendingChat:f,handleFocusAgent:p,isFocusingAgent:x,actionLogs:b,userName:S,scrollToBottomRequestNonce:A,isInputActive:u})]})},(e,s)=>e.activeConv===s.activeConv&&e.isCliTerminal===s.isCliTerminal&&e.ideEntry===s.ideEntry&&e.terminalRef===s.terminalRef&&e.handleModalButton===s.handleModalButton&&e.handleRelaunch===s.handleRelaunch&&e.handleSendChat===s.handleSendChat&&e.isSendingChat===s.isSendingChat&&e.handleFocusAgent===s.handleFocusAgent&&e.isFocusingAgent===s.isFocusingAgent&&e.actionLogs===s.actionLogs&&e.userName===s.userName&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&e.isInputActive===s.isInputActive);function Zu({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:o,userName:i,isSendingChat:c,isFocusingAgent:d,onBack:m,onOpenNativeConversation:f,onOpenMachine:p,onOpenHistory:x,onOpenRemote:b,onHideConversation:S,onStopCli:A,cliViewMode:u,onSetCliViewMode:h,handleSendChat:y,handleFocusAgent:l,handleModalButton:j,handleRelaunch:P}){const k=a.useRef(null),g=Ye(e)&&!s,N=g&&u==="terminal",v=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:`flex items-center justify-between gap-3 ${v} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":"Back",children:t.jsx(Tn,{size:18})}),t.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:st(e)}),t.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:t.jsx(Do,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>f(e),onOpenMachine:()=>p(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[g&&u&&t.jsx(Kn,{mode:u,onChange:h,compact:!0}),g&&A&&t.jsx("button",{onClick:()=>{A(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:t.jsx(vt,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(e),type:"button",children:t.jsx(Mn,{size:14})}),!s&&!g&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>b(e),type:"button",children:t.jsx(kt,{size:14})}),S&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(e),type:"button",title:"Close chat",children:t.jsx(vt,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(Gn,{activeConv:e,clearToken:0,isCliTerminal:N,ideEntry:n,terminalRef:k,handleModalButton:j,handleRelaunch:P,handleSendChat:y,isSendingChat:c,handleFocusAgent:l,isFocusingAgent:d,actionLogs:o,userName:i})})]})}const Qr={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 Qu(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function gi(){const[e,s]=a.useState("unix"),[r,n]=a.useState("powershell"),[o,i]=a.useState(!1),c=e==="unix"?"unix":r;a.useEffect(()=>{s(Qu())},[]);const d=a.useCallback(()=>{navigator.clipboard.writeText(Qr[c].cmd).catch(()=>{}),i(!0),setTimeout(()=>i(!1),2e3)},[c]);return t.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[t.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[t.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>s("unix"),children:"🍎🐧 macOS / Linux"}),t.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>s("windows"),children:"🪟 Windows"})]}),e==="windows"&&t.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[t.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("powershell"),children:"⚡ PowerShell"}),t.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("cmd"),children:">_ CMD"})]}),t.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:d,title:"Click to copy",children:[t.jsx("span",{className:"text-text-muted select-none",children:Qr[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:Qr[c].cmd}),t.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:o?"✓":"📋"})]}),t.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",t.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function yi({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:kt},{key:"chats",label:"Chats",icon:Kt}];return t.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:t.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:n,label:o,icon:i})=>{const c=e===n;return t.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${c?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>s(n),type:"button","aria-pressed":c,children:[t.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:t.jsx(i,{size:15})}),t.jsx("span",{children:o})]},n)})})})}function ar({title:e,className:s=""}){return t.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${s}`,children:t.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function us({children:e,className:s=""}){return t.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${s}`,children:e})}function Ms({icon:e,title:s,subtitle:r,children:n}){return t.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[t.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),t.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:s}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function or({item:e,type:s,getAvatarText:r,onOpenConversation:n}){const o=s==="needs_attention"||s==="task_complete",i=s==="working",c=s==="earlier",d=s==="task_complete",{isReconnecting:m,isConnecting:f}=ks(e.conversation),p=st(e.conversation),x=is(e.conversation),b=Ho(e.conversation,{requiresAction:s==="needs_attention"}),S=o?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":i?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",A=o?"bg-accent-primary shadow-glow":i?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":c?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",u=c?"text-text-secondary":"text-text-primary",h=c?"text-text-muted":"text-text-secondary",y=c?"text-text-secondary opacity-80":"text-text-muted",l=c?"text-text-muted opacity-80":"text-text-muted",j="text-[color:var(--status-warning)]";return t.jsxs("button",{className:`group flex items-start gap-3.5 px-4 py-3.5 w-full text-left relative overflow-hidden transition-colors active:scale-[0.995] ${S}`,onClick:()=>n(e.conversation),type:"button",children:[o||i?t.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,t.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${A}`,style:o?{color:"var(--accent-on-primary)"}:void 0,children:r(p)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${u}`,children:p}),!i&&t.jsx("span",{className:`text-[11px] font-medium shrink-0 ${l}`,children:Co(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${h}`,children:[x,m?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${j} animate-pulse`,children:"Reconnecting…"})]}):f?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):b==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:j,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${y}`,children:e.preview})]}),o&&!d&&t.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),d&&t.jsx("span",{className:"absolute top-4 right-4 rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Done"}),i&&t.jsx("span",{className:"absolute top-4 right-4 rounded-full bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Live"})]},e.conversation.tabKey)}function Va({size:e=32,label:s}){return t.jsxs("div",{className:"flex flex-col items-center gap-2.5",children:[t.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}}),s&&t.jsx("div",{className:"text-xs font-semibold text-accent-primary-light tracking-tight",children:s})]})}function em({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:o,hiddenConversations:i,machineCards:c,getAvatarText:d,onOpenConversation:m,onShowConversation:f,onShowAllHidden:p,onOpenNewSession:x,onOpenMachine:b,onOpenSettings:S,onSectionChange:A,wsStatus:u="connected",isStandalone:h=!1}){const y=u==="disconnected"||u==="reconnecting"||u==="offline"||u==="auth_failed",l=c.length>0,j=s.length>0||r.length>0||n.length>0||o.length>0,P=e==="machines"?"Machines":"Chats",k=h?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",g=h?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]";return t.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[t.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${k}`,children:t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:P}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(s.length>0||r.length>0)&&t.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[t.jsx(_r,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:S,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:t.jsx(Ar,{size:18})})]})]})}),t.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${g}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:y?t.jsx(Ms,{icon:t.jsx(Va,{label:"Reconnecting…"}),title:"Connecting to server",subtitle:u==="offline"?"Your device appears to be offline. Waiting for network…":u==="auth_failed"?"Session expired. Please log in again.":"Establishing connection to the server. This usually takes a moment."}):c.length===0?t.jsx(Ms,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:h?"Waiting for your daemon":"Connect your machines",subtitle:h?"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:!h&&t.jsx("div",{className:"w-full max-w-[360px] mt-4",children:t.jsx(gi,{})})}):t.jsx(us,{children:c.map((N,v)=>t.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>b(N.id),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:d(N.label)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:N.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:N.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[N.unread," new"]}):N.total>0?`${N.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:N.subtitle}),N.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[N.total," chat",N.total!==1?"s":"",N.unread>0?` · ${N.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},N.id))})}),e==="chats"&&s.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(ar,{title:"Needs attention",className:"mb-0"}),t.jsx(us,{children:s.map((N,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(or,{item:N,type:"needs_attention",getAvatarText:d,onOpenConversation:m})},N.conversation.tabKey))})]}),e==="chats"&&r.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(ar,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(us,{children:r.map((N,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(or,{item:N,type:"task_complete",getAvatarText:d,onOpenConversation:m})},N.conversation.tabKey))})]}),e==="chats"&&n.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(ar,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(us,{children:n.map((N,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(or,{item:N,type:"working",getAvatarText:d,onOpenConversation:m})},N.conversation.tabKey))})]}),e==="chats"&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[o.length>0&&t.jsx(ar,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),o.length>0?t.jsx(us,{children:o.map((N,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(or,{item:N,type:"earlier",getAvatarText:d,onOpenConversation:m})},N.conversation.tabKey))}):j?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):y?t.jsx(Ms,{icon:t.jsx(Va,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):l?t.jsx(Ms,{icon:t.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:t.jsx(Kt,{size:20})}),title:"No conversations yet",subtitle:"Your machines are available. Open a machine, wait for P2P to connect, then launch your first IDE, CLI, or ACP session."}):t.jsx(Ms,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),e==="chats"&&i.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsxs("div",{className:"mx-1 mt-4 mb-1 flex items-center justify-between gap-2 px-1 py-1 text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:[t.jsx("span",{children:"Hidden"}),t.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:p,children:"Restore all"})]}),t.jsx(us,{className:"bg-bg-secondary/25",children:i.map((N,v)=>t.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] opacity-50 saturate-0 ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(N),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-bg-primary border border-border-subtle text-text-secondary",children:d(st(N))}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:st(N)}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:is(N)}),t.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},N.tabKey))})]})]}),e==="chats"&&x&&t.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:x,"aria-label":"Start new session",children:t.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),t.jsx(yi,{section:e,onSectionChange:A})]})}function Dr(...e){const s=new Set,r=[],n=o=>{const i=typeof o=="string"?o.trim():"";if(!i)return;const c=i.toLowerCase();s.has(c)||(s.add(c),r.push(i))};for(const o of e){if(Array.isArray(o)){for(const i of o)n(i);continue}n(o)}return r}function tm(e){const s=e.trim();if(!s)return null;if(s.startsWith("~"))return s;if(/^[A-Za-z]:$/.test(s))return`${s[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(s))return`${s[0].toUpperCase()}:${s.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(s))return`${s[0].toUpperCase()}:\\${s.slice(2).replace(/[\\/]+/g,"\\")}`;const r=s.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),o=(r[2]||"").replace(/[\\/]+/g,"\\");return o?`${n}:\\${o}`:`${n}:\\`}return null}function Er(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=tm(r);if(n)return n}return"C:\\"}for(const r of s){const n=typeof r=="string"?r.trim():"";if(n)return n}return"~"}function sm(e){const s=e.replace(/[\\/]+$/,"");if(!s||s==="/"||/^[A-Za-z]:$/.test(s))return null;const r=s.includes("\\")?"\\":"/",n=s.split(/[\\/]/);return/^[A-Za-z]:$/.test(n[0]||"")?n.length<=2?`${n[0]}\\`:n.slice(0,-1).join("\\"):n.length<=2?r:n.slice(0,-1).join(r)||r}async function $r(e,s,r){const n=await e(s,"file_list_browse",{path:r});if(!(n!=null&&n.success))throw new Error((n==null?void 0:n.error)||"Could not browse folder");const o=typeof(n==null?void 0:n.path)=="string"?n.path:r,i=o.includes("\\")?"\\":"/",c=(m,f)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${f}`:m==="/"||m==="\\"?`${i}${f}`:`${m.replace(/[\\/]+$/,"")}${i}${f}`,d=Array.isArray(n==null?void 0:n.files)?n.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:c(o,m.name)})).sort((m,f)=>m.name.localeCompare(f.name)):[];return{path:o,directories:d}}function Br({title:e,description:s,currentPath:r,directories:n,busy:o=!1,error:i="",confirmLabel:c="Use this folder",onClose:d,onNavigate:m,onConfirm:f}){const[p,x]=a.useState(r);a.useEffect(()=>{x(r)},[r]);const b=sm(r),S=p.trim();return t.jsx("div",{className:"fixed inset-0 z-[110] flex items-center justify-center p-4 bg-black/60 backdrop-blur-[2px]",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:t.jsxs("div",{className:"w-full max-w-2xl max-h-[min(86vh,720px)] rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:d,"aria-label":"Close folder browser",children:t.jsx(vt,{size:16})})]}),t.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[t.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!b||o||m(b)},disabled:!b||o,children:[t.jsx(Tn,{size:15}),"Parent"]}),t.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"text",value:p,onChange:A=>x(A.target.value),onKeyDown:A=>{A.key!=="Enter"||!S||o||(A.preventDefault(),m(S))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!S||o||m(S)},disabled:!S||o,children:"Go"})]})]})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:o?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):i?t.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):n.length===0?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):t.jsx("div",{className:"p-3",children:n.map(A=>t.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>m(A.path),children:[t.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(gs,{size:17})}),t.jsxs("span",{className:"min-w-0 flex-1",children:[t.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:A.name}),t.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:A.path})]})]},A.path))})}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-4 border-t border-border-subtle bg-bg-secondary",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:d,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>f(S||r),disabled:!S&&!r||o,children:c})]})]})})}function qn({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:o,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:d="Launching…",busy:m=!1,showArgsInput:f,argsValue:p,onArgsChange:x,showModelInput:b,modelValue:S,onModelChange:A,historyProviderNode:u,onConfirm:h,onCancel:y}){const l=n==null?void 0:n.find(j=>j.key===o);return t.jsx("div",{className:"fixed inset-0 z-[110] flex items-center justify-center p-4 bg-black/60 backdrop-blur-[2px]",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:t.jsxs("div",{className:"w-full max-w-lg rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:y,"aria-label":"Close launch confirmation",children:t.jsx(vt,{size:16})})]}),t.jsxs("div",{className:"px-5 py-4 flex flex-col gap-3",children:[n&&n.length>0&&i&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),t.jsx("select",{value:o||"",onChange:j=>i(j.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:m,children:n.map(j=>t.jsx("option",{value:j.key,children:j.label},j.key))}),(l==null?void 0:l.description)&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:l.description})]}),u,r.map(j=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:j.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:j.value})]},`${j.label}:${j.value}`)),b&&A&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),t.jsx("input",{type:"text",value:S||"",onChange:j=>A(j.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:m})]}),f&&x&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),t.jsx("input",{type:"text",value:p||"",onChange:j=>x(j.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:m})]})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-4 border-t border-border-subtle bg-bg-secondary",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:y,disabled:m,children:"Cancel"}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:h,disabled:m,children:[t.jsx(_n,{size:14}),m?d:c]})]})]})})}function Ga(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function ts(e){const{machine:s,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:o=!0}=e,i=[];o&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const m of s.workspaces||[])i.push({key:`saved:${m.id}`,label:`${m.id===s.defaultWorkspaceId?"⭐ ":""}${Ga(m.path,m.label)}`,description:m.path,workspaceId:m.id,workspacePath:m.path});const c=(r==null?void 0:r.trim())||"",d=c?(s.workspaces||[]).find(m=>m.path===c):null;if(c&&!d&&i.push({key:`custom:${c}`,label:Ga(c),description:c,workspaceId:null,workspacePath:c}),n){const m=`saved:${n}`;if(i.some(f=>f.key===m))return{options:i,selectedKey:m}}return d?{options:i,selectedKey:`saved:${d.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function en(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function rm({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:o,onListSavedSessions:i}){var X,ce,Ce,Re;const c=Gs(),[d,m]=a.useState(!1),f=(((X=e.detectedIdes)==null?void 0:X.length)||0)>0,p=a.useMemo(()=>(e.workspaces||[]).map(me=>({id:me.id,path:me.path,label:me.label})),[e]),x=e.defaultWorkspaceId||null,[b,S]=a.useState(x||((ce=p[0])==null?void 0:ce.id)||""),[A,u]=a.useState(""),[h,y]=a.useState(""),[l,j]=a.useState([]),[P,k]=a.useState(!1),[g,N]=a.useState(""),[v,w]=a.useState(!1),[M,T]=a.useState(en(f,s.length,r.length)),$=a.useRef(null),[E,F]=a.useState(null),D=a.useRef("__home__"),[C,V]=a.useState("__home__"),[J,I]=a.useState(""),[R,B]=a.useState(""),[z,Z]=a.useState(""),[fe,Pe]=a.useState([]),[ke,ve]=a.useState(!1),[Q,xe]=a.useState(!1),W=a.useRef(null);a.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const ee=b==="__custom__"?A.trim():((Ce=p.find(me=>me.id===b))==null?void 0:Ce.path)||"",ne=b==="__custom__"&&!!ee&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),oe=b!=="__custom__"&&((Re=p.find(me=>me.id===b))==null?void 0:Re.path)||"",he=a.useMemo(()=>(e.recentLaunches||[]).map(me=>me.workspace),[e]),te=a.useCallback(async me=>{k(!0),N("");try{const We=await o(me);y(We.path),u(We.path),j(We.directories)}catch(We){N(We instanceof Error?We.message:"Could not load folder")}finally{k(!1)}},[o]),de=a.useCallback(()=>{var We;S("__custom__"),w(!0);const me=Er(e.platform,Dr(A.trim(),oe,he,e.defaultWorkspacePath,(We=p.find(Be=>Be.id===x))==null?void 0:We.path,p.map(Be=>Be.path)));te(me)},[A,x,te,he,oe,e.platform,p]),se=a.useCallback(me=>{if(me!=null&&me.workspaceId){S(me.workspaceId),u("");return}if(me!=null&&me.workspacePath){S("__custom__"),u(me.workspacePath);return}S(""),u("")},[]),pe=a.useCallback(me=>{if(S(me),me==="__custom__"){de();return}u("")},[de]),ae=a.useCallback(me=>{S("__custom__"),u(me)},[]),Ne=a.useCallback((me,We)=>{$.current=We,D.current=me.selectedWorkspaceKey||"__home__",V(me.selectedWorkspaceKey||"__home__"),I(me.initialArgs||""),B(me.initialModel||""),Z(""),Pe([]),F(me),me.providerType&&i&&(ve(!0),i(me.providerType).then(Be=>Pe(Be||[])).catch(Be=>console.warn("Failed to load saved sessions",Be)).finally(()=>ve(!1)))},[i]),ge=a.useCallback(()=>{$.current&&(xe(!0),$.current().finally(()=>{$.current=null,xe(!1),F(null)}))},[]),_=a.useCallback(()=>{$.current=null,F(null)},[]),ue=a.useCallback(me=>{D.current=me,V(me)},[]);return a.useEffect(()=>{var me;W.current!==e.id&&(W.current=e.id,S(x||((me=p[0])==null?void 0:me.id)||"__custom__"),u(""),y(""),j([]),N(""),w(!1),T(en(f,s.length,r.length)))},[r.length,s.length,x,f,e.id,p]),a.useEffect(()=>{var me;b!=="__custom__"&&(b&&p.some(We=>We.id===b)||S(x||((me=p[0])==null?void 0:me.id)||"__custom__"))},[x,b,p]),a.useEffect(()=>{M==="ide"&&f||M==="cli"&&s.length>0||M==="acp"&&r.length>0||T(en(f,s.length,r.length))},[M,r.length,s.length,f]),{showAllRecent:d,setShowAllRecent:m,hasIdeOptions:f,workspaceRows:p,defaultWorkspaceId:x,workspaceChoice:b,customWorkspacePath:A,browseCurrentPath:h,browseDirectories:l,browseBusy:P,browseError:g,browseDialogOpen:v,activeLauncherKind:M,launchConfirm:E,launchConfirmWorkspaceKeyRef:D,launchConfirmWorkspaceKey:C,launchConfirmArgs:J,launchConfirmModel:R,launchConfirmResumeId:z,launchConfirmSavedSessions:fe,launchConfirmSessionsLoading:ke,launchConfirmBusy:Q,resolvedWorkspacePath:ee,canCreateMissingWorkspace:ne,openBrowseDialog:de,loadBrowsePath:te,handleWorkspaceChoiceChange:pe,chooseCustomWorkspacePath:ae,setCustomWorkspacePath:u,setBrowseDialogOpen:w,setActiveLauncherKind:T,openLaunchConfirm:Ne,handleConfirmLaunch:ge,closeLaunchConfirm:_,setWorkspaceSelectionFromOption:se,setLaunchConfirmWorkspaceKeyAndSync:ue,setLaunchConfirmArgs:I,setLaunchConfirmModel:B,setLaunchConfirmResumeId:Z}}function nm({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:o,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:d,isStandalone:m,section:f,showBottomNav:p,onBack:x,onSectionChange:b,onOpenConversation:S,onOpenRecent:A,onOpenMachineDetails:u,onMachineUpgrade:h,onLaunchDetectedIde:y,onAddWorkspace:l,onBrowseDirectory:j,onLaunchWorkspaceProvider:P,onListSavedSessions:k}){const g=C=>C==="ide"?"IDE":C==="cli"?"CLI":"ACP",N=r.slice(0,4),v=s.slice(0,3),w=rm({selectedMachineEntry:e,cliProviders:n,acpProviders:o,machineAction:d,onBrowseDirectory:j,onListSavedSessions:k}),M=a.useMemo(()=>N.map(C=>({key:`recent-launch:${C.id}`,primary:C.label,secondary:`${g(C.kind)}${C.subtitle?` · ${C.subtitle}`:""}`,onClick:()=>{const{options:V,selectedKey:J}=ts({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspacePath:C.workspace});w.openLaunchConfirm({title:C.kind==="ide"?Yt("restart-ide",C.label):C.providerSessionId?qo(C.label):Yt("start-fresh",C.label),description:C.kind==="ide"?Xt("restart-ide"):C.providerSessionId?Yo():Xt("start-fresh"),confirmLabel:C.kind==="ide"?Jt("restart-ide"):C.providerSessionId?Nr(!0):Jt("start-fresh"),busyLabel:C.kind==="ide"?Zt("restart-ide"):C.providerSessionId?Wn(!0):Zt("start-fresh"),workspaceOptions:V,selectedWorkspaceKey:J,details:[{label:"Mode",value:g(C.kind)},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]},async()=>{const I=V.find(R=>R.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(I),await A({...C,workspace:(I==null?void 0:I.workspacePath)??null})})}})),[w,A,N]),T=a.useMemo(()=>v.map(C=>({key:`recent-chat:${C.conversation.tabKey}`,primary:st(C.conversation),secondary:hd(C.conversation,{timestampLabel:C.timestamp?Co(C.timestamp):null}),unread:C.unread,onClick:()=>S(C.conversation)})),[S,v]),$=w.showAllRecent?M:M.slice(0,4),E=M.length>0,F=T.length>0,D=m?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:`flex items-center justify-between gap-3 ${D} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:x,type:"button","aria-label":"Back",children:t.jsx(Tn,{size:18})}),t.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:jt(e,{fallbackId:e.id})}),t.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[F&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:T.map(C=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${C.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:C.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))})]}),E&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:$.map(C=>t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:C.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))}),M.length>4&&t.jsx("div",{className:"flex justify-center px-4 pt-2",children:t.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>w.setShowAllRecent(C=>!C),children:w.showAllRecent?"Show fewer":`Show ${M.length-4} more`})})]}),(w.hasIdeOptions||n.length>0||o.length>0)&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:t.jsxs("div",{className:"flex flex-col gap-2.5 w-full p-3.5 rounded-2xl border border-border-default/80 bg-surface-primary/90",children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),t.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),t.jsx("select",{value:w.workspaceChoice,onChange:C=>w.handleWorkspaceChoiceChange(C.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:w.workspaceRows.length>0?t.jsxs(t.Fragment,{children:[w.workspaceRows.map(C=>t.jsxs("option",{value:C.id,children:[C.id===w.defaultWorkspaceId?"⭐ ":"",Pr(C.path,C.label)||C.path]},C.id)),t.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):t.jsx("option",{value:"__custom__",children:"Select workspace…"})}),w.workspaceChoice==="__custom__"&&t.jsxs("div",{className:"flex flex-col gap-2.5",children:[t.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start gap-3",children:[t.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(gs,{size:17})}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),t.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:w.resolvedWorkspacePath||w.browseCurrentPath||"No folder selected yet."})]})]})}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-secondary text-[12px] font-bold",onClick:w.openBrowseDialog,children:"Select workspace…"}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-accent-primary/30 bg-accent-primary/10 text-text-primary text-[12px] font-bold disabled:opacity-40",onClick:()=>{w.resolvedWorkspacePath&&l(w.resolvedWorkspacePath)},disabled:!w.resolvedWorkspacePath||w.browseBusy,children:"Save as workspace"})]})]}),w.resolvedWorkspacePath&&t.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:w.resolvedWorkspacePath})]})}),t.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[w.hasIdeOptions&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${w.activeLauncherKind==="ide"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>w.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${w.activeLauncherKind==="cli"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>w.setActiveLauncherKind("cli"),children:"CLI"}),o.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${w.activeLauncherKind==="acp"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>w.setActiveLauncherKind("acp"),children:"ACP"})]}),w.activeLauncherKind&&t.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[t.jsx("div",{className:"text-xs font-bold text-text-secondary",children:w.activeLauncherKind==="ide"?"Choose an IDE":w.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),t.jsx("div",{className:"grid grid-cols-1 gap-2",children:w.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(C=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const{options:V,selectedKey:J}=ts({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspaceId:w.workspaceChoice!=="__custom__"?w.workspaceChoice:null,currentWorkspacePath:w.resolvedWorkspacePath});w.openLaunchConfirm({title:`Launch ${C.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:V,selectedWorkspaceKey:J,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:C.name}]},async()=>{const I=V.find(R=>R.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(I),y(C.type,{workspacePath:(I==null?void 0:I.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:C.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:w.resolvedWorkspacePath||"Use selected workspace"})]},C.type)):(w.activeLauncherKind==="cli"?n:o).map(C=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const V=w.activeLauncherKind==="cli"?"cli":"acp",{options:J,selectedKey:I}=ts({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspaceId:w.workspaceChoice!=="__custom__"?w.workspaceChoice:null,currentWorkspacePath:w.resolvedWorkspacePath});w.openLaunchConfirm({title:`Launch ${C.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${V.toUpperCase()}`,workspaceOptions:J,selectedWorkspaceKey:I,details:[{label:"Mode",value:V.toUpperCase()},{label:"Provider",value:C.displayName}],showArgsInput:!0,showModelInput:V==="acp",initialArgs:"",initialModel:"",providerType:C.type},async()=>{const R=J.find(B=>B.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(R),P(V,C.type,{workspaceId:(R==null?void 0:R.workspaceId)??null,workspacePath:(R==null?void 0:R.workspacePath)??null,args:w.launchConfirmArgs,model:w.launchConfirmModel,resumeSessionId:w.launchConfirmResumeId||null})})},children:[t.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[C.icon?`${C.icon} `:"",C.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:w.resolvedWorkspacePath||"Use selected workspace"})]},C.type))})]}),d.message&&t.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${d.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[d.message,w.canCreateMissingWorkspace&&t.jsx("div",{className:"mt-2",children:t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[34px] px-4 rounded-lg bg-surface-primary text-text-primary font-bold text-xs",onClick:()=>l(w.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[i&&t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:h,children:[t.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:u,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),w.browseDialogOpen&&t.jsx(Br,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:w.browseCurrentPath,directories:w.browseDirectories,busy:w.browseBusy,error:w.browseError,confirmLabel:"Use this folder",onClose:()=>w.setBrowseDialogOpen(!1),onNavigate:C=>{w.loadBrowsePath(C)},onConfirm:C=>{w.chooseCustomWorkspacePath(C),w.setBrowseDialogOpen(!1)}}),w.launchConfirm&&t.jsx(qn,{title:w.launchConfirm.title,description:w.launchConfirm.description,details:w.launchConfirm.details,workspaceOptions:w.launchConfirm.workspaceOptions,selectedWorkspaceKey:w.launchConfirmWorkspaceKey,onWorkspaceChange:w.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:w.launchConfirm.providerType?Nr(!!w.launchConfirmResumeId):w.launchConfirm.confirmLabel,busyLabel:w.launchConfirm.providerType?void 0:w.launchConfirm.busyLabel,busy:w.launchConfirmBusy,showArgsInput:w.launchConfirm.showArgsInput,argsValue:w.launchConfirmArgs,onArgsChange:w.setLaunchConfirmArgs,showModelInput:w.launchConfirm.showModelInput,modelValue:w.launchConfirmModel,onModelChange:w.setLaunchConfirmModel,historyProviderNode:w.launchConfirm.providerType&&(w.launchConfirmSessionsLoading||w.launchConfirmSavedSessions.length>0)&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),w.launchConfirmSessionsLoading&&t.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),t.jsxs("select",{value:w.launchConfirmResumeId,onChange:C=>w.setLaunchConfirmResumeId(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"",children:Vo()}),w.launchConfirmSavedSessions.map(C=>t.jsxs("option",{value:C.providerSessionId,disabled:!C.canResume,children:[C.title||C.providerSessionId," ",C.canResume?"":"(workspace missing)"]},C.providerSessionId))]})]}),onConfirm:w.handleConfirmLaunch,onCancel:w.closeLaunchConfirm}),p&&t.jsx(yi,{section:f,onSectionChange:b})]})}function vi(e){var r;const s=((r=e.p2p)==null?void 0:r.state)||"";return s==="connected"?"Connected":s==="connecting"||s==="new"||s==="checking"?"Connecting":"Offline"}function am(e,s){if(!e)return[];const r=e.recentLaunches||[];return r.length>0?r.map(n=>({id:n.id,label:n.title||n.providerName||n.providerType,kind:n.kind,providerType:n.providerType,providerSessionId:n.providerSessionId,subtitle:n.currentModel||n.workspace||void 0,workspace:n.workspace,currentModel:n.currentModel})):s.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var i,c,d,m,f;const o=Hs(n)?"cli":xs(n)?"acp":"ide";return{id:`${o}:${n.type}:${n.workspace||""}`,label:((i=n.activeChat)==null?void 0:i.title)||(Hs(n)?n.cliName||n.type:xs(n)&&n.cliName||n.type),kind:o,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:xs(n)?n.currentModel||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,currentModel:n.currentModel,timestamp:((f=(m=(d=(c=n.activeChat)==null?void 0:c.messages)==null?void 0:d.at)==null?void 0:m.call(d,-1))==null?void 0:f.timestamp)||0}}).sort((n,o)=>o.timestamp-n.timestamp).map(({timestamp:n,...o})=>o)}function om(e,s){const r=new Map;for(const n of s){const o=Ut(n.conversation),i=r.get(o);i?i.push(n):r.set(o,[n])}return e.map(n=>{const o=r.get(n.id)||[],i=[...o].sort((x,b)=>b.timestamp-x.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,d=xn(n),m=o.filter(x=>x.unread||x.requiresAction).length,f=vi(n),p=[n.platform||"machine",f].filter(Boolean);return{id:n.id,label:jt(n,{fallbackId:n.id}),subtitle:p.join(" · "),unread:m,total:o.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:d,preview:c?bd(c):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((n,o)=>{const i=n.latestTimestamp||n.fallbackActivityAt||0,c=o.latestTimestamp||o.fallbackActivityAt||0;return c!==i?c-i:n.label.localeCompare(o.label)})}function ir(e,s){var r;if(!(typeof window>"u"))try{if(!(!!((r=import.meta.env)!=null&&r.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,s)}catch{}}function im({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:o,screen:i,liveSessionInboxState:c,sendDaemonCommand:d,requestedActiveTabKey:m,onRequestedActiveTabConsumed:f,requestedMachineId:p,onRequestedMachineConsumed:x,requestedMobileSection:b,onRequestedMobileSectionConsumed:S,setSelectedTabKey:A,setScreen:u,setSelectedMachineId:h,setSection:y,setMachineBackTarget:l,resetMachineAction:j}){const P=a.useRef(null),k=a.useCallback(g=>{if(!(g!=null&&g.sessionId))return;const N=Ws(g,c),v=Math.max(Date.now(),Ht(g),N.lastUpdated||0);ir("mark_read:start",{tabKey:g.tabKey,sessionId:g.sessionId,displayPrimary:st(g),inboxBucket:N.inboxBucket,unread:N.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:Ht(g),readAt:v}),d(Ut(g)||g.routeId,"mark_session_seen",{sessionId:g.sessionId,seenAt:v}).then(w=>{ir("mark_read:result",{tabKey:g.tabKey,sessionId:g.sessionId,result:w})}).catch(w=>{ir("mark_read:error",{tabKey:g.tabKey,sessionId:g.sessionId,error:w instanceof Error?w.message:String(w)})})},[c,d]);return a.useEffect(()=>{var N;if(!n){u("inbox"),A(((N=e[0])==null?void 0:N.tabKey)||null),P.current=null;return}if(i!=="chat"){P.current=null;return}const g=`${n.tabKey}:${n.sessionId||""}`;P.current!==g&&(P.current=g,k(n))},[e,k,i,n,u,A]),a.useEffect(()=>{if(!m)return;const g=e.find(N=>N.tabKey===m);g&&(A(g.tabKey),u("chat"),f==null||f())},[e,f,m,u,A]),a.useEffect(()=>{if(!p)return;const g=s.find(N=>N.id===p);g&&(h(g.id),j(),y("machines"),l("inbox"),u("machine"),x==null||x())},[s,x,p,j,l,u,y,h]),a.useEffect(()=>{b&&(y(b),u("inbox"),S==null||S())},[S,b,u,y]),a.useEffect(()=>{const g=r.filter(N=>N.inboxBucket==="task_complete"||N.unread);g.length!==0&&ir("inbox_state",{screen:i,selectedTabKey:o,items:g.map(N=>{const v=Ws(N.conversation,c);return{liveState:v,tabKey:N.conversation.tabKey,sessionId:N.conversation.sessionId,displayPrimary:st(N.conversation),serverBucket:v.inboxBucket,computedBucket:N.inboxBucket,serverUnread:v.unread,computedUnread:N.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,activityAt:Ht(N.conversation)}})})},[r,c,i,o]),{markConversationRead:k}}function cm(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function qa(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function lm(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function dm({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[o,i]=a.useState("idle"),[c,d]=a.useState(""),[m,f]=a.useState(null),p=a.useCallback(()=>{i("idle"),d(""),f(null)},[]),x=a.useCallback(async(l,j,P)=>{var k;try{i("loading"),d(`Launching ${j}…`);const g={ideType:j,enableCdp:!0};(k=P==null?void 0:P.workspacePath)!=null&&k.trim()&&(g.workspace=P.workspacePath.trim()),await e(l,"launch_ide",g),i("done"),d(`${j} launch requested`)}catch(g){i("error"),d(g instanceof Error?g.message:"Launch IDE failed"),console.error("Launch IDE failed",g)}},[e]),b=a.useCallback(async(l,j,P)=>{if(j.trim())try{i("loading"),d(P!=null&&P.createIfMissing?"Creating folder…":"Saving workspace…");const k=await e(l,"workspace_add",{path:j.trim(),createIfMissing:(P==null?void 0:P.createIfMissing)===!0});if(k!=null&&k.success){i("done"),d(P!=null&&P.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),d((k==null?void 0:k.error)||"Could not save workspace")}catch(k){i("error"),d(k instanceof Error?k.message:"Could not save workspace")}},[e]),S=a.useCallback(async l=>{var j,P,k,g,N,v;try{i("loading"),d("Starting daemon upgrade…");const w=await e(l,"daemon_upgrade",{});if((j=w==null?void 0:w.result)!=null&&j.alreadyLatest){i("done"),d(`Already on v${((P=w==null?void 0:w.result)==null?void 0:P.version)||"latest"}.`);return}if((k=w==null?void 0:w.result)!=null&&k.upgraded||(g=w==null?void 0:w.result)!=null&&g.success){i("done"),d(`Upgrade to v${((N=w==null?void 0:w.result)==null?void 0:N.version)||"latest"} started. Daemon is restarting…`);return}i("error"),d(((v=w==null?void 0:w.result)==null?void 0:v.error)||"Upgrade failed")}catch(w){i("error"),d(w instanceof Error?w.message:"Upgrade failed")}},[e]),A=a.useCallback(async(l,j,P,k)=>{var v,w,M;const g=Date.now(),N={machineId:l,kind:j,providerType:P,workspaceId:(k==null?void 0:k.workspaceId)||null,workspacePath:(k==null?void 0:k.workspacePath)||null,resumeSessionId:(k==null?void 0:k.resumeSessionId)||null,startedAt:g};try{i("loading"),d(`Launching ${P}…`),f(N);const T={cliType:P};(v=k==null?void 0:k.workspacePath)!=null&&v.trim()?T.dir=k.workspacePath.trim():k!=null&&k.workspaceId&&(T.workspaceId=k.workspaceId),k!=null&&k.resumeSessionId&&(T.resumeSessionId=k.resumeSessionId),(w=k==null?void 0:k.args)!=null&&w.trim()&&(T.cliArgs=k.args.trim().split(/\s+/).filter(Boolean)),(M=k==null?void 0:k.model)!=null&&M.trim()&&(T.initialModel=k.model.trim());const $=await e(l,"launch_cli",T),E=($==null?void 0:$.result)||$,F=(E==null?void 0:E.sessionId)||(E==null?void 0:E.id);if($!=null&&$.success&&F){f(null),i("done"),d(`${P} launched`),s(`/dashboard?activeTab=${encodeURIComponent(F)}`);return}if($!=null&&$.success){i("loading"),d(`${P} launch requested — waiting for session…`);return}f(null),i("error"),d(($==null?void 0:$.error)||(E==null?void 0:E.error)||`Could not launch ${j.toUpperCase()} workspace`)}catch(T){if(lm(T)){i("loading"),d(`${P} launch requested — waiting for session…`);return}f(null),i("error"),d(T instanceof Error?T.message:`Could not launch ${j.toUpperCase()} workspace`)}},[s,e]),u=a.useCallback(async(l,j)=>{try{const P=await e(l,"list_saved_sessions",{providerType:j,kind:"cli",limit:30}),k=(P==null?void 0:P.result)??P;return Array.isArray(k==null?void 0:k.sessions)?k.sessions:[]}catch(P){return console.error("Failed to list saved sessions on mobile:",P),[]}},[e]),h=a.useCallback(async(l,j)=>$r(e,l,j),[e]);a.useEffect(()=>{var k;if(!m)return;const l=qa(m.workspacePath),j=r.find(g=>{var $,E,F,D;if(!g||g.type==="adhdev-daemon"||cm(g.daemonId||g.id)!==m.machineId||(g.transport==="acp"?"acp":g.transport==="pty"?"cli":null)!==m.kind||String(g.agentType||g.type||"")!==m.providerType)return!1;const M=String(g.providerSessionId||"");if(m.resumeSessionId&&M)return M===m.resumeSessionId;if(l){const C=qa(g.workspace||g.runtimeWorkspaceLabel);return C?C===l:!1}return Number(g.lastUpdated||g._lastUpdate||g.timestamp||((D=(F=(E=($=g.activeChat)==null?void 0:$.messages)==null?void 0:E.at)==null?void 0:F.call(E,-1))==null?void 0:D.timestamp)||0)>=m.startedAt-5e3});if(!j)return;const P=typeof j.sessionId=="string"&&j.sessionId?j.sessionId:typeof j.instanceId=="string"&&j.instanceId?j.instanceId:(k=n.find(g=>g.routeId===j.id))==null?void 0:k.sessionId;P&&(f(null),i("done"),d(`${m.providerType} launched`),s(`/dashboard?activeTab=${encodeURIComponent(P)}`))},[n,r,s,m]),a.useEffect(()=>{if(!m)return;const l=window.setTimeout(()=>{f(j=>!j||j.startedAt!==m.startedAt?j:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(l)},[m]);const y=a.useCallback(async(l,j)=>{if(j.kind==="ide"&&j.providerType){await x(l,j.providerType,{workspacePath:j.workspace||null});return}(j.kind==="cli"||j.kind==="acp")&&j.providerType&&await A(l,j.kind,j.providerType,{workspacePath:j.workspace||null,resumeSessionId:j.providerSessionId||null})},[x,A]);return{machineAction:{state:o,message:c},resetMachineAction:p,handleLaunchDetectedIde:x,handleAddWorkspace:b,handleMachineUpgrade:S,handleLaunchWorkspaceProvider:A,handleListSavedSessions:u,handleBrowseDirectory:h,handleOpenRecent:y}}function um({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:o,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:d,setSection:m,setMachineBackTarget:f}){const p=a.useCallback(y=>{i(y.tabKey),c("chat"),n(y)},[n,c,i]),x=a.useCallback(y=>{const l=e.find(j=>j.routeId===y.routeId&&j.streamSource==="native");l&&(i(l.tabKey),c("chat"),n(l))},[e,n,c,i]),b=a.useCallback(()=>{n(s),c("inbox")},[n,s,c]),S=a.useCallback((y,l="inbox")=>{d(y),o(),m("machines"),f(l),c("machine")},[o,f,c,m,d]),A=a.useCallback(y=>{const l=Ut(y);l&&S(l,"chat")},[S]),u=a.useCallback(()=>{o(),c(r)},[r,o,c]),h=a.useCallback(y=>{m(y),c("inbox")},[c,m]);return{openConversation:p,openNativeConversation:x,backFromConversation:b,openMachine:S,openConversationMachine:A,backFromMachine:u,changeMachineSection:h}}function mm(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function pm(e){const s=e instanceof Error?e.message:String(e||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function cr(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function fm({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:d,userName:m,requestedActiveTabKey:f,onRequestedActiveTabConsumed:p,requestedMachineId:x,onRequestedMachineConsumed:b,requestedMobileSection:S,onRequestedMobileSectionConsumed:A,onOpenHistory:u,onOpenRemote:h,onStopCli:y,wsStatus:l,isConnected:j,onShowHiddenConversation:P,onShowAllHiddenConversations:k,onHideConversation:g,onOpenNewSession:N}){const[v,w]=a.useState(()=>{var X;return((X=e[0])==null?void 0:X.tabKey)||null}),[M,T]=a.useState(()=>e[0]?"chat":"inbox"),[$,E]=a.useState("chats"),[F,D]=a.useState(null),[C,V]=a.useState("inbox"),J=ws(),I="0.8.54",R=a.useMemo(()=>e.find(X=>X.tabKey===v)||e[0]||null,[e,v]),B=a.useMemo(()=>R?r.find(X=>X.id===R.routeId):void 0,[r,R]),z=a.useMemo(()=>!R||Ve(R)||!Ye(R)?null:vs(R),[R]),Z=a.useMemo(()=>r.filter(X=>X.type==="adhdev-daemon").sort(Ln),[r]),fe=a.useMemo(()=>Z.find(X=>X.id===F)||null,[Z,F]),Pe=a.useMemo(()=>Fs(r),[r]),ke=Lr({sendDaemonCommand:o,activeConv:R||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:d}),ve=dm({sendDaemonCommand:o,navigate:J,ides:r,conversations:e}),Q=a.useMemo(()=>e.map(X=>{const ce=M==="chat"&&(R==null?void 0:R.tabKey)===X.tabKey,Ce=Os(X,Pe,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ce}),Re=Ht(X),me=Oo(X);return{conversation:X,timestamp:Re,preview:me,unread:Ce.unread,requiresAction:Ce.requiresAction,isWorking:Ce.isWorking,inboxBucket:Ce.inboxBucket}}),[e,Pe,M,R]),{markConversationRead:xe}=im({conversations:e,machineEntries:Z,items:Q,selectedConversation:R,selectedTabKey:v,screen:M,liveSessionInboxState:Pe,sendDaemonCommand:o,requestedActiveTabKey:f,onRequestedActiveTabConsumed:p,requestedMachineId:x,onRequestedMachineConsumed:b,requestedMobileSection:S,onRequestedMobileSectionConsumed:A,setSelectedTabKey:w,setScreen:T,setSelectedMachineId:D,setSection:E,setMachineBackTarget:V,resetMachineAction:ve.resetMachineAction}),W=um({conversations:e,selectedConversation:R,machineBackTarget:C,markConversationRead:xe,resetMachineAction:ve.resetMachineAction,setSelectedTabKey:w,setScreen:T,setSelectedMachineId:D,setSection:E,setMachineBackTarget:V}),ee=a.useMemo(()=>cr(Q.filter(X=>X.requiresAction)),[Q]),ne=a.useMemo(()=>cr(Q.filter(X=>X.unread&&!X.requiresAction)),[Q]),oe=a.useMemo(()=>cr(Q.filter(X=>!X.unread&&!X.requiresAction&&X.isWorking)),[Q]),he=a.useMemo(()=>cr(Q.filter(X=>!X.unread&&!X.requiresAction&&!X.isWorking)),[Q]),te=a.useMemo(()=>fe?Q.filter(X=>Ut(X.conversation)===fe.id):[],[Q,fe]),de=a.useMemo(()=>am(fe,r),[r,fe]),se=(fe==null?void 0:fe.version)||null,pe=!!fe&&!!se&&!0&&se!==I,ae=a.useMemo(()=>(fe==null?void 0:fe.availableProviders)||[],[fe]),Ne=a.useMemo(()=>ae.filter(X=>X.category==="cli"&&X.installed!==!1).map(X=>({type:X.type,displayName:X.displayName||X.type,icon:X.icon})),[ae]),ge=a.useMemo(()=>ae.filter(X=>X.category==="acp"&&X.installed!==!1).map(X=>({type:X.type,displayName:X.displayName||X.type,icon:X.icon})),[ae]),_=a.useMemo(()=>om(Z,Q),[Q,Z]),ue=a.useCallback(async X=>{fe&&await ve.handleOpenRecent(fe.id,X)},[ve,fe]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:M==="chat"&&R?t.jsx(Zu,{selectedConversation:R,isAcp:Ve(R),isStandalone:d,selectedIdeEntry:B,actionLogs:n,userName:m,isSendingChat:ke.isSendingChat,isFocusingAgent:ke.isFocusingAgent,handleModalButton:ke.handleModalButton,handleRelaunch:ke.handleRelaunch,onBack:W.backFromConversation,onOpenNativeConversation:W.openNativeConversation,onOpenMachine:W.openConversationMachine,onHideConversation:g,onOpenHistory:u,onOpenRemote:h,onStopCli:y,cliViewMode:z,onSetCliViewMode:async X=>{if(R&&z!==X)try{await o(Ut(R)||R.routeId,"set_cli_view_mode",{targetSessionId:R.sessionId,cliType:wt(R),mode:X})}catch(ce){pm(ce)?console.warn("Skipped CLI view mode switch:",ce instanceof Error?ce.message:String(ce)):console.error("Failed to switch CLI view mode:",ce)}},handleSendChat:ke.handleSendChat,handleFocusAgent:ke.handleFocusAgent}):M==="machine"&&fe?t.jsx(nm,{selectedMachineEntry:fe,selectedMachineConversations:te,selectedMachineRecentLaunches:de,cliProviders:Ne,acpProviders:ge,selectedMachineNeedsUpgrade:pe,appVersion:I,machineAction:ve.machineAction,isStandalone:d,section:$,showBottomNav:C==="inbox",onBack:W.backFromMachine,onSectionChange:W.changeMachineSection,onOpenConversation:W.openConversation,onOpenRecent:ue,onOpenMachineDetails:()=>J(`/machines/${fe.id}`),onMachineUpgrade:()=>ve.handleMachineUpgrade(fe.id),onLaunchDetectedIde:(X,ce)=>ve.handleLaunchDetectedIde(fe.id,X,ce),onAddWorkspace:(X,ce)=>ve.handleAddWorkspace(fe.id,X,ce),onBrowseDirectory:X=>ve.handleBrowseDirectory(fe.id,X),onLaunchWorkspaceProvider:(X,ce,Ce)=>ve.handleLaunchWorkspaceProvider(fe.id,X,ce,Ce),onListSavedSessions:X=>ve.handleListSavedSessions(fe.id,X)}):t.jsx(em,{section:$,attentionItems:ee,unreadItems:ne,workingItems:oe,completedItems:he,hiddenConversations:s,machineCards:_,getAvatarText:mm,onOpenConversation:W.openConversation,onShowConversation:P,onShowAllHidden:k,onOpenNewSession:N,onOpenMachine:W.openMachine,onOpenSettings:()=>J("/settings"),onSectionChange:E,wsStatus:l,isConnected:j,isStandalone:d})})}function tn(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function xm({conversations:e,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:o,onClearPreviewOrder:i}){const c=a.useRef(0),[d,m]=a.useState(!1),[f,p]=a.useState(null),x=a.useCallback(()=>{c.current=0,m(!1),p(null)},[]);a.useEffect(()=>(window.addEventListener("dragend",x),window.addEventListener("drop",x),()=>{window.removeEventListener("dragend",x),window.removeEventListener("drop",x)}),[x]);const b=a.useCallback(h=>{h.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,m(!0))},[]),S=a.useCallback(h=>{if(!h.dataTransfer.types.includes("text/tab-key"))return;if(h.preventDefault(),!tn(s,r)){p("merge");return}const y=h.currentTarget.getBoundingClientRect(),l=h.clientX-y.left,j=y.width/3;l<j?p("split-left"):l>j*2?p("split-right"):p("merge")},[s,r]),A=a.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,m(!1),p(null))},[]),u=a.useCallback(h=>{c.current=0,m(!1);const y=h.dataTransfer.getData("text/tab-key"),l=y?e.some(P=>P.tabKey===y):!1,j=f;if(p(null),i(),!!y){if(h.preventDefault(),j==="split-left"&&tn(s,r)){r==null||r(y,"split-left");return}if(j==="split-right"&&tn(s,r)){r==null||r(y,"split-right");return}if(l){o(y);return}n==null||n(y)}},[e,f,s,r,n,o,i]);return{dragOver:d,dropAction:f,resetDragState:x,handleDragEnter:b,handleDragOver:S,handleDragLeave:A,handleDrop:u}}function hm(e,s){const r=new Set(s.map(i=>i.tabKey)),n=e.filter(i=>r.has(i)),o=s.filter(i=>!e.includes(i.tabKey)).map(i=>i.tabKey);return[...n,...o]}function bm({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:o}){const[i,c]=a.useState(s??null),[d,m]=a.useState(r??[]),[f,p]=a.useState(null),x=a.useRef(null),b=a.useRef(null),S=a.useRef(n),A=a.useRef(o);a.useEffect(()=>{S.current=n},[n]),a.useEffect(()=>{A.current=o},[o]),a.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),a.useEffect(()=>{m(N=>{const v=hm(N,e);return v.length===N.length&&v.every((w,M)=>w===N[M])?N:v})},[e]);const u=a.useMemo(()=>{const N=f??d;if(N.length===0)return e;const v=new Map(N.map((w,M)=>[w,M]));return[...e].sort((w,M)=>{const T=v.get(w.tabKey)??999,$=v.get(M.tabKey)??999;return T-$})},[e,f,d]);a.useEffect(()=>{var v,w;if(u.length===0){i!==null&&(c(null),(v=S.current)==null||v.call(S,null));return}if(i&&u.some(M=>M.tabKey===i))return;const N=u[0].tabKey;N!==i&&(c(N),(w=S.current)==null||w.call(S,N))},[u,i]);const h=a.useMemo(()=>u.find(N=>N.tabKey===i),[u,i]),y=a.useCallback(N=>{var v;c(N),(v=S.current)==null||v.call(S,N)},[]),l=a.useCallback((N,v,w)=>{m(M=>{var F;const T=M.filter(D=>D!==N),$=T.indexOf(v);if($<0)return M;const E=w==="left"?$:$+1;return T.splice(E,0,N),(F=A.current)==null||F.call(A,T),T}),p(null)},[]),j=a.useCallback((N,v,w)=>{const T=(d.length>0?d:e.map(F=>F.tabKey)).filter(F=>F!==N),$=T.indexOf(v);if($<0)return;const E=w==="left"?$:$+1;T.splice(E,0,N),x.current=T,p(T)},[d,e]),P=a.useCallback(()=>{var v;const N=x.current;N&&(m(N),(v=A.current)==null||v.call(A,N))},[]),k=a.useCallback(()=>{x.current=null,p(null)},[]),g=a.useCallback(N=>{m(v=>{var M;const w=v.filter(T=>T!==N);return w.push(N),(M=A.current)==null||M.call(A,w),w})},[]);return{activeTabId:i,activeConv:h,sortedConversations:u,previewOrderRef:x,draggingTabRef:b,selectTab:y,handleTabReorder:l,updatePreviewOrder:j,commitPreviewOrder:P,clearPreviewOrder:k,moveTabToEnd:g,setDraggingTabKey:N=>{b.current=N}}}function gm({dropAction:e,canSplit:s}){return t.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[t.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-left"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:s?1:.45},children:t.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Left"})}),t.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:t.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Move Here"})}),t.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-right"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:s?1:.45},children:t.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Right"})})]})}function Yn({conversationsCount:e,isSplitMode:s,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:o=!1}){if(o)return t.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const i=!r&&!n,c=r?"Waiting for your daemon":n?"No conversations yet":"Connect your machines",d=r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":n?"Your machines are connected. Open a machine, choose a workspace, then launch an IDE, CLI, or ACP session.":"Install ADHDev on a machine, sign in, and it will show up here.";return e===0&&!s?t.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[t.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),t.jsxs("div",{className:"text-center max-w-lg",children:[t.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:c}),t.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:d}),i&&t.jsx(gi,{}),i&&t.jsx("div",{className:"mt-8",children:t.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"📚 Read the documentation →"})})]})]}):t.jsx("div",{className:"text-sm text-text-muted opacity-50",children:s?"Move a tab here to view":"No active agent"})}const wi="adhdev-tab-shortcuts";function ji(){try{return JSON.parse(localStorage.getItem(wi)||"{}")}catch{return{}}}function ki({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const o=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=a.useState(()=>ji()),[d,m]=a.useState(null),f=a.useCallback(x=>{const b=[];return x.metaKey&&b.push(o?"⌘":"Meta"),x.ctrlKey&&b.push("Ctrl"),x.altKey&&b.push(o?"⌥":"Alt"),x.shiftKey&&b.push(o?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(x.key)?null:(b.push(x.key.length===1?x.key.toUpperCase():x.key),b.join("+"))},[o]),p=a.useCallback(x=>{c(x);try{localStorage.setItem(wi,JSON.stringify(x))}catch{}},[]);return a.useEffect(()=>{if(!e||!d)return;const x=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){m(null);return}const S=f(b);if(!S)return;const A={...i};for(const[u,h]of Object.entries(A))h===S&&delete A[u];A[d]=S,p(A),m(null)};return window.addEventListener("keydown",x,!0),()=>window.removeEventListener("keydown",x,!0)},[e,d,i,p,f]),a.useEffect(()=>{if(!e)return;const x=b=>{if(!(!b.ctrlKey&&!b.metaKey&&!b.altKey)){for(const[S,A]of Object.entries(i))if(s.includes(S)&&f(b)===A){b.preventDefault(),r(),n(S);return}}};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[e,i,s,r,n,f]),{isMac:o,tabShortcuts:i,shortcutListening:d,setShortcutListening:m,saveShortcuts:p}}const ym=a.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:o,shortcut:i,conversationKeys:c,draggingTabRef:d,onFocus:m,onSelectTab:f,onConversationActivated:p,onPreviewReorder:x,onReorderTab:b,onCommitPreviewOrder:S,onClearPreviewOrder:A,onDragStateReset:u,onDragTabKeyChange:h,onReceiveTab:y,onOpenContextMenu:l,longPressTimer:j,isGroupActive:P}){const k=ks(s),g=k.isGenerating?"agent-tab-generating":k.isWaiting?"agent-tab-waiting":"",N=k.isReconnecting,v=a.useCallback(V=>{d.current=s.tabKey,h(s.tabKey),V.dataTransfer.setData("text/tab-key",s.tabKey),V.dataTransfer.effectAllowed="move"},[s.tabKey,d,h]),w=a.useCallback(()=>{d.current=null,h(null),S(),A(),u()},[d,h,S,A,u]),M=a.useCallback(V=>{const J=d.current;if(!(!J||J===s.tabKey)&&V.dataTransfer.types.includes("text/tab-key")){V.preventDefault(),V.stopPropagation();const I=V.currentTarget.getBoundingClientRect(),R=V.clientX<I.left+I.width/2?"left":"right";x(J,s.tabKey,R)}},[s.tabKey,d,x]),T=a.useCallback(V=>{V.preventDefault(),V.stopPropagation();const J=V.dataTransfer.getData("text/tab-key");if(J&&J!==s.tabKey){const I=V.currentTarget.getBoundingClientRect(),R=V.clientX<I.left+I.width/2?"left":"right";c.includes(J)?b(J,s.tabKey,R):y&&y(J)}A()},[s.tabKey,c,b,y,A]),$=a.useCallback(V=>{V.stopPropagation(),m(),f(s.tabKey),p(s)},[s,p,m,f]),E=a.useCallback(V=>{V.preventDefault(),l(V.clientX,V.clientY,s.tabKey)},[s.tabKey,l]),F=a.useCallback(V=>{const J=V.touches[0];j.current=setTimeout(()=>{l(J.clientX,J.clientY,s.tabKey)},600)},[s.tabKey,j,l]),D=a.useCallback(()=>{j.current&&clearTimeout(j.current)},[j]),C=["adhdev-dockview-tab",g,r&&"is-active",P&&"is-group-active",N&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:C,draggable:!0,onDragStart:v,onDragEnd:w,onDragOver:M,onDrop:T,onClick:$,onContextMenu:E,onTouchStart:F,onTouchEnd:D,onTouchMove:D,style:{cursor:"pointer",opacity:n?.4:void 0},children:[o&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status",children:k.isGenerating?t.jsx("div",{className:"tab-spinner"}):k.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):N?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):k.isConnecting?t.jsx("div",{className:"tab-connecting-spinner"}):s.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("span",{className:"adhdev-dockview-tab-primary",title:st(s),children:st(s)}),t.jsx("span",{className:"adhdev-dockview-tab-meta",children:N?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:qt(s)}):k.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[qt(s),t.jsx("span",{className:"connecting-dots"})]}):qt(s)})]}),i&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${i}`,children:i})]})},(e,s)=>e.conv===s.conv&&e.isActive===s.isActive&&e.isDraggedTab===s.isDraggedTab&&e.isTaskCompleteUnread===s.isTaskCompleteUnread&&e.shortcut===s.shortcut&&e.conversationKeys===s.conversationKeys&&e.isGroupActive===s.isGroupActive);function vm({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:o,onFocus:i,onSelectTab:c,onConversationActivated:d,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:p,onClearPreviewOrder:x,onDragStateReset:b,onDragTabKeyChange:S,onReceiveTab:A,onHideTab:u,isGroupActive:h,allowTabShortcuts:y=!0}){const[l,j]=a.useState(null),P=a.useRef(null),k=a.useRef(null),g=a.useMemo(()=>e.map(E=>E.tabKey),[e]);zs("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(l==null?void 0:l.tabKey)||null});const{isMac:N,tabShortcuts:v,shortcutListening:w,setShortcutListening:M,saveShortcuts:T}=ki({enabled:y,sortedTabKeys:e.map(E=>E.tabKey),onFocus:i,onSelectTab:c});a.useEffect(()=>{if(!l)return;const E=F=>{const D=document.querySelector("[data-pane-context-menu]");D&&D.contains(F.target)||j(null)};return window.addEventListener("mousedown",E,!0),()=>window.removeEventListener("mousedown",E,!0)},[l]),a.useEffect(()=>{const E=k.current;if(!E)return;const F=D=>{Math.abs(D.deltaY)>Math.abs(D.deltaX)&&(D.preventDefault(),E.scrollLeft+=D.deltaY)};return E.addEventListener("wheel",F,{passive:!1}),()=>E.removeEventListener("wheel",F)},[]);const $=a.useCallback((E,F,D)=>{j({x:E,y:F,tabKey:D})},[]);return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:t.jsxs("div",{ref:k,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none"},children:[e.map(E=>t.jsx(ym,{conv:E,isActive:s===E.tabKey,isDraggedTab:o.current===E.tabKey,isTaskCompleteUnread:n.has(E.tabKey),shortcut:y?v[E.tabKey]:void 0,conversationKeys:g,draggingTabRef:o,onFocus:i,onSelectTab:c,onConversationActivated:d,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:p,onClearPreviewOrder:x,onDragStateReset:b,onDragTabKeyChange:S,onReceiveTab:A,onOpenContextMenu:$,longPressTimer:P,isGroupActive:h},E.tabKey)),e.length===0&&t.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),l&&t.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:l.x,top:l.y},children:[y&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:E=>{E.stopPropagation(),M(l.tabKey),j(null)},children:["⌨ ",v[l.tabKey]?`Change shortcut (${v[l.tabKey]})`:"Set shortcut"]}),v[l.tabKey]&&t.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onClick:()=>{const E={...v};delete E[l.tabKey],T(E),j(null)},children:"✕ Remove shortcut"})]}),u&&t.jsxs(t.Fragment,{children:[y&&t.jsx("div",{className:"border-t border-border-subtle my-1"}),t.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onClick:()=>{u(l.tabKey),j(null)},children:"🚫 Hide from Dashboard"})]})]}),y&&w&&t.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>M(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:E=>E.stopPropagation(),children:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",N?"⌘+1":"Ctrl+1",", ",N?"⌥+A":"Alt+A",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function wm({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:d,hasRegisteredMachines:m,userName:f,groupIndex:p,onFocus:x,isSplitMode:b,numGroups:S,onMoveTab:A,onReceiveTab:u,style:h,onActiveTabChange:y,initialActiveTabId:l,initialTabOrder:j,onTabOrderChange:P,onHideTab:k,isFocused:g,allowTabShortcuts:N=!0}){const{sendCommand:v}=Ct(),w=a.useRef(null),{activeTabId:M,activeConv:T,sortedConversations:$,draggingTabRef:E,selectTab:F,handleTabReorder:D,updatePreviewOrder:C,commitPreviewOrder:V,clearPreviewOrder:J,moveTabToEnd:I,setDraggingTabKey:R}=bm({conversations:e,initialActiveTabId:l,initialTabOrder:j,onActiveTabChange:y,onTabOrderChange:P}),B=Lr({sendDaemonCommand:o,activeConv:T,setLocalUserMessages:i,setActionLogs:c,isStandalone:d}),{dragOver:z,dropAction:Z,resetDragState:fe,handleDragEnter:Pe,handleDragOver:ke,handleDragLeave:ve,handleDrop:Q}=xm({conversations:e,numGroups:S,onMoveTab:A,onReceiveTab:u,onOwnTabDrop:I,onClearPreviewOrder:J}),xe=T&&!Ve(T)&&vs(T)==="terminal",W=a.useMemo(()=>T?s.find(te=>te.id===T.routeId):void 0,[s,T]),ee=a.useMemo(()=>T?n.filter(te=>te.routeId===T.tabKey):[],[n,T]),ne=a.useMemo(()=>Fs(s),[s]),oe=a.useMemo(()=>new Set($.filter(te=>ol(te,ne,{isOpenConversation:te.tabKey===M})).map(te=>te.tabKey)),[M,ne,$]);zs("PaneGroup",{groupIndex:p,conversationCount:e.length,activeTabId:M,dragOver:z});const he=a.useCallback(te=>{te.streamSource==="agent-stream"&&te.agentType&&v(te.routeId,"focus_session",{agentType:te.agentType,...te.sessionId&&{targetSessionId:te.sessionId}}).catch(()=>{})},[v]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:x,style:{...h,outline:z?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(vm,{conversations:$,activeTabId:M,groupIndex:p,numGroups:S,unreadTabKeys:oe,draggingTabRef:E,onFocus:x,onSelectTab:F,onConversationActivated:he,onPreviewReorder:C,onReorderTab:D,onCommitPreviewOrder:V,onClearPreviewOrder:J,onDragStateReset:fe,onDragTabKeyChange:R,onMoveTab:A,onReceiveTab:u,onHideTab:k,isGroupActive:g??!1,allowTabShortcuts:N}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:Pe,onDragOver:ke,onDragLeave:ve,onDrop:Q,children:[z&&t.jsx(gm,{dropAction:Z,canSplit:!!(S<4&&A)}),T?t.jsx(Gn,{activeConv:T,clearToken:r[T.tabKey]||0,isCliTerminal:!!xe,ideEntry:W,terminalRef:w,handleModalButton:B.handleModalButton,handleRelaunch:B.handleRelaunch,handleSendChat:B.handleSendChat,isSendingChat:B.isSendingChat,handleFocusAgent:B.handleFocusAgent,isFocusingAgent:B.isFocusingAgent,actionLogs:ee,userName:f,isInputActive:!b||!!g}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(Yn,{conversationsCount:e.length,isSplitMode:b,isStandalone:d,hasRegisteredMachines:m})})]})]})}function jm({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:o,clearedTabs:i,ides:c,actionLogs:d,sendDaemonCommand:m,setLocalUserMessages:f,setActionLogs:p,isStandalone:x,hasRegisteredMachines:b,userName:S,focusedGroup:A,setFocusedGroup:u,moveTabToGroup:h,splitTabRelative:y,closeGroup:l,handleResizeStart:j,groupActiveTabIds:P,setGroupActiveTabIds:k,groupTabOrders:g,setGroupTabOrders:N,toggleHiddenTab:v,allowTabShortcuts:w=!0}){return t.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:o.map((M,T)=>{const $=s&&n.length===r?`${n[T]}%`:void 0;return t.jsxs(rt.Fragment,{children:[s&&T>0&&t.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:E=>j(T-1,E),onDoubleClick:()=>l(T),title:"Drag to resize · Double-click to merge",children:t.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),t.jsx(wm,{style:s?{flexBasis:$??`${100/r}%`,flexGrow:$?0:1,flexShrink:$?0:1}:void 0,conversations:M,clearedTabs:i,ides:c,actionLogs:d,sendDaemonCommand:m,setLocalUserMessages:f,setActionLogs:p,isStandalone:x,hasRegisteredMachines:b,userName:S,groupIndex:T,isFocused:s&&A===T,onFocus:()=>u(T),isSplitMode:s,numGroups:r,onMoveTab:(E,F)=>{F==="left"&&T>0?h(E,T-1):F==="right"&&T<r-1?h(E,T+1):F==="split-left"&&r<4?y(E,T,"left"):F==="split-right"&&r<4&&y(E,T,"right")},onReceiveTab:E=>h(E,T),onActiveTabChange:E=>k(F=>(F[T]??null)===(E??null)?F:{...F,[T]:E}),initialActiveTabId:P[T],initialTabOrder:g[T],onTabOrderChange:E=>N(F=>{const D=F[T]||[];return D.length===E.length&&D.every((C,V)=>C===E[V])?F:{...F,[T]:E}}),onHideTab:v,allowTabShortcuts:w})]},T)})})}function Ni({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[o,i]=a.useState(null),[c,d]=a.useState(null);a.useEffect(()=>e?at.onScreenshot("ide-page",(p,x)=>{if(p!==e)return;const b=new FileReader;b.onload=()=>i(b.result),b.readAsDataURL(x)}):void 0,[e]),a.useEffect(()=>{r!=="connected"&&i(null)},[r]),a.useEffect(()=>{var p;return e?((p=at.onStatus)==null?void 0:p.call(at,(x,b)=>{x===e&&b!=null&&b.screenshotUsage&&d(b.screenshotUsage)}))||(()=>{}):void 0},[e]),a.useEffect(()=>{i(null)},[e,s]),a.useEffect(()=>{const f=e?at.get(e):null;if(!(!f||r!=="connected"))return n!=="chat"&&s?f.startScreenshots(s):f.stopScreenshots(s),()=>{f.stopScreenshots(s)}},[n,r,s,e]);const m=a.useCallback(async(f,p)=>{const x=e?at.get(e):null;return!x||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):x.sendInput(f,p,s)},[e,r,s]);return{connScreenshot:o,screenshotUsage:c,handleRemoteAction:m}}const Si="adhdev-dashboard-action-shortcuts",km=1200,Nm={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Sm(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function Je(e,s){switch(e){case"openShortcutHelp":return"?";case"hideCurrentTab":return s?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return s?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return s?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return s?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return s?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return s?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return s?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return s?"⌘+⌥+=":"Ctrl+Alt+\\";case"splitActiveTabDown":return s?"⌘+⌥+-":"Ctrl+Alt+-";case"focusLeftPane":return s?"⌘+⌥+[":"Ctrl+Alt+←";case"focusRightPane":return s?"⌘+⌥+]":"Ctrl+Alt+→";case"focusUpPane":return s?"⌘+⌥+U":"Ctrl+Alt+↑";case"focusDownPane":return s?"⌘+⌥+J":"Ctrl+Alt+↓";case"moveActiveTabToLeftPane":return s?"⌘+⌥+,":"Ctrl+Alt+Shift+←";case"moveActiveTabToRightPane":return s?"⌘+⌥+.":"Ctrl+Alt+Shift+→";case"moveActiveTabToUpPane":return s?"⌘+⌥+I":"Ctrl+Alt+Shift+↑";case"moveActiveTabToDownPane":return s?"⌘+⌥+K":"Ctrl+Alt+Shift+↓";case"triggerPrimaryApprovalAction":return s?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return s?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return s?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return s?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return s?"⌥+[":"Ctrl+Alt+[";case"selectNextGroupTab":return s?"⌥+]":"Ctrl+Alt+]";case"toggleCliView":return s?"⌥+T":"Ctrl+Alt+T"}}function Ci(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:Je("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:Je("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:Je("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:Je("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:Je("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:Je("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:Je("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:Je("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:Je("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:Je("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:Je("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:Je("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:Je("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:Je("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:Je("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:Je("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:Je("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:Je("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:Je("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:Je("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:Je("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:Je("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:Je("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:Je("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:Je("toggleCliView",e)}]}function kn(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function Ir(e){const s=Object.fromEntries(Ci(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Si)||"{}"),n={...s,...r};for(const[o,i]of Object.entries(Nm))n[o]===i&&(n[o]=s[o]);return n}catch{return s}}function Ii(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Cm({enabled:e=!0,onTrigger:s}){const r=Sm(),[n,o]=a.useState(()=>Ir(r)),[i,c]=a.useState(null),[d,m]=a.useState([]),f=a.useRef({parts:[],timer:null}),p=a.useCallback(u=>{const h=[];return u.metaKey&&h.push(r?"⌘":"Meta"),u.ctrlKey&&h.push("Ctrl"),u.altKey&&h.push(r?"⌥":"Alt"),u.shiftKey&&u.key.length!==1&&h.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(u.key)?null:(h.push(Ii(u.key)),h.join("+"))},[r]),x=a.useCallback(u=>{o(u);try{localStorage.setItem(Si,JSON.stringify(u))}catch{}},[]);a.useEffect(()=>{const u=Ir(r),h=Object.entries(n),y=Object.entries(u);h.length===y.length&&h.every(([l,j])=>u[l]===j)||x(u)},[n,r,x]);const b=a.useCallback(()=>{typeof window<"u"&&f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current={parts:[],timer:null}},[]),S=a.useCallback(()=>{typeof window>"u"||(f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current.timer=window.setTimeout(()=>{f.current={parts:[],timer:null}},km))},[]);a.useEffect(()=>{if(!i)return;const u=h=>{if(h.preventDefault(),h.stopPropagation(),h.key==="Escape"){c(null),m([]);return}const y=p(h);if(!y)return;const j=!(h.metaKey||h.ctrlKey||h.altKey)&&/^[A-Z0-9]$/.test(y);if(d.length===0&&j){m([y]);return}const k=[...d,y].slice(0,2).join(" "),g={...n};for(const[N,v]of Object.entries(g))v===k&&delete g[N];g[i]=k,x(g),c(null),m([])};return window.addEventListener("keydown",u,!0),()=>window.removeEventListener("keydown",u,!0)},[n,p,x,i,d]),a.useEffect(()=>{if(!e||i)return;const u=h=>{if(h.defaultPrevented)return;const y=p(h);if(!y)return;const l=h.metaKey||h.ctrlKey||h.altKey;if(kn(h.target)&&!l)return;const j=f.current.parts,P=l?[y]:[...j.slice(-1),y].slice(-2),k=P.join(" "),g=P[P.length-1],N=Object.entries(n).filter(([,$])=>!!$),v=N.find(([,$])=>$===k);if(v){h.preventDefault(),b(),s(v[0]);return}if(N.some(([,$])=>$.startsWith(`${k} `))){h.preventDefault(),f.current.parts=P,S();return}const M=N.find(([,$])=>$===g);if(M){h.preventDefault(),b(),s(M[0]);return}if(N.some(([,$])=>$.startsWith(`${g} `))){h.preventDefault(),f.current.parts=[g],S();return}b()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[n,S,e,p,s,b,i]),a.useEffect(()=>()=>b(),[b]);const A=a.useMemo(()=>Ci(r),[r]);return{isMac:r,actionDefinitions:A,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:d,setShortcutListening:c,setShortcutListeningDraft:m,saveShortcuts:x}}const Ti=a.createContext(null);function Kr(){const e=a.useContext(Ti);if(!e)throw new Error("DashboardDockviewContext missing");return e}function br(e){return st(e)||e.tabKey}function Im(e){return`remote:${e}`}function Wt(e){return e.startsWith("remote:")}function Ya(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function sn(e){var r,n,o,i,c;const s=e==null?void 0:e.defaultView;if(s)try{s.focus(),(n=(r=e==null?void 0:e.body)==null?void 0:r.focus)==null||n.call(r),(i=(o=e==null?void 0:e.documentElement)==null?void 0:o.focus)==null||i.call(o),(c=s.requestAnimationFrame)==null||c.call(s,()=>{var d,m;try{s.focus(),(m=(d=e==null?void 0:e.body)==null?void 0:d.focus)==null||m.call(d)}catch{}})}catch{}}function lr(e,s){e.classList.remove(mn.className,pn.className),e.classList.add(s==="light"?mn.className:pn.className)}function Xa(e){return e?Array.from(new Set(e.groups.map(s=>{var r,n;return(n=(r=s.element)==null?void 0:r.ownerDocument)==null?void 0:n.defaultView}).filter(s=>!!s&&s!==window))):[]}function Tm(e){const[,s]=a.useState(0);a.useEffect(()=>{const r=()=>s(o=>o+1),n=[e.api.onDidActiveGroupChange(r),e.api.onDidTitleChange(r),e.api.onDidGroupChange(r),e.containerApi.onDidActivePanelChange(r)];return()=>{for(const o of n)o.dispose()}},[e.api,e.containerApi])}function Am(e,s,r){var d;const n=[s];let o;for(const m of n){let f;for(const p of m){const x=e.addPanel({id:p.tabKey,component:"conversation",title:br(p),params:{kind:"conversation",tabKey:p.tabKey},...f?{position:{referencePanel:f,direction:"within"},inactive:!0}:o?{position:{referencePanel:o,direction:"right"},inactive:!0}:{}});f||(f=x.id)}o=f??o}const i=r??((d=s[0])==null?void 0:d.tabKey)??null;if(!i)return;const c=e.getPanel(i);c&&c.group.model.openPanel(c)}function Ja(e,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...e.panels])Wt(n.id)||r.has(n.id)||e.removePanel(n);for(const n of s){const o=e.getPanel(n.tabKey);if(o){o.update({params:{tabKey:n.tabKey}}),o.title!==br(n)&&o.api.setTitle(br(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:br(n),params:{kind:"conversation",tabKey:n.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function Za(e,s,r){var m,f;const n=r?Im(r):null;for(const p of[...e.panels])Wt(p.id)&&(!n||p.id!==n)&&e.removePanel(p);if(!r||!n)return;const o=Lt(s,r);if(!o&&e.totalPanels===0)return;const i=e.getPanel(n),c=zo(o);if(i){i.title!==c&&i.api.setTitle(c);return}const d=(o==null?void 0:o.tabKey)??((m=e.activePanel)==null?void 0:m.id)??((f=e.panels.find(p=>!Wt(p.id)))==null?void 0:f.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...d?{position:{referencePanel:d,direction:"right"},inactive:!0}:{}})}function Mm({params:e,api:s}){var x;const r=Kr(),n=a.useRef(null),[o,i]=a.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),d=Lr({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});a.useEffect(()=>{i(s.isActive);const b=[s.onDidActiveChange(S=>i(S.isActive)),s.onDidActiveGroupChange(S=>{if(!s.isActive&&!S.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const S of b)S.dispose()}},[s]);const m=a.useMemo(()=>c?r.ides.find(b=>b.id===c.routeId):void 0,[r.ides,c]),f=a.useMemo(()=>c?r.actionLogs.filter(b=>b.routeId===c.tabKey):[],[r.actionLogs,c]);if(!c)return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:t.jsx(Yn,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,suppressGuide:r.hasDetachedConversationPanels})});const p=!Ve(c)&&vs(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(Gn,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:p,ideEntry:m,terminalRef:n,handleModalButton:d.handleModalButton,handleRelaunch:d.handleRelaunch,handleSendChat:d.handleSendChat,isSendingChat:d.isSendingChat,handleFocusAgent:d.handleFocusAgent,isFocusingAgent:d.isFocusingAgent,actionLogs:f,userName:r.userName,scrollToBottomRequestNonce:((x=r.scrollToBottomRequest)==null?void 0:x.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:o})})}function _m({params:e}){var m;const s=Kr(),r=a.useMemo(()=>Lt([...s.conversationsByTabKey.values()],e.routeId),[s.conversationsByTabKey,e.routeId]),n=a.useMemo(()=>s.ides.find(f=>f.id===e.routeId),[s.ides,e.routeId]),o=(r==null?void 0:r.daemonId)||((m=r==null?void 0:r.routeId)==null?void 0:m.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:d}=Ni({doId:o,targetSessionId:r?Bn(r):(n==null?void 0:n.sessionId)||(n==null?void 0:n.instanceId),connState:(r==null?void 0:r.connectionState)||"new",viewMode:"remote"});return r?t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:t.jsx(So,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:c,transportType:r.transport,onAction:d})}):t.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:"Remote view unavailable"})}function Pm(){const e=Kr();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(Yn,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,suppressGuide:e.hasDetachedConversationPanels})})}function Rm(e){var S,A;Tm(e);const s=Kr(),r=a.useCallback(u=>{"button"in u&&u.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const u=Lt([...s.conversationsByTabKey.values()],e.params.routeId),h=((S=e.api.group.activePanel)==null?void 0:S.id)===e.api.id,y=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${h?" is-active":""}${y?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(u==null?void 0:u.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:u!=null&&u.machineName?t.jsxs(t.Fragment,{children:[t.jsx("span",{children:"Live remote view"}),t.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),t.jsx("span",{className:"adhdev-dockview-tab-machine",children:u.machineName})]}):t.jsx("span",{children:"Live remote view"})})]})]})}const n=s.conversationsByTabKey.get(e.params.tabKey);if(!n)return t.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:t.jsx("div",{className:"adhdev-dockview-tab-copy",children:t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const o=((A=e.api.group.activePanel)==null?void 0:A.id)===e.api.id,i=e.api.isGroupActive,c=Os(n,s.liveSessionInboxState,{isOpenConversation:o}),d=c.isReconnecting,m=c.isConnecting,f=c.isGenerating,p=c.isWaiting,x=c.unread,b=s.tabShortcuts[n.tabKey];return t.jsxs("div",{className:`adhdev-dockview-tab${o?" is-active":""}${i?" is-group-active":""}${d?" is-reconnecting":""}`,title:st(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:u=>{var h;u.preventDefault(),r(u),s.openTabContextMenu({x:u.clientX,y:u.clientY,tabKey:n.tabKey,sourceDocument:((h=u.target)==null?void 0:h.ownerDocument)??document})},children:[x&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:f?t.jsx("div",{className:"tab-spinner"}):p?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):d?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):m?t.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:st(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:d?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:qt(n)}):m?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:qt(n)}):t.jsx("span",{children:qt(n)})})]}),b&&t.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 Lm({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:d,hasRegisteredMachines:m,initialDataLoaded:f,userName:p,toggleHiddenTab:x,actionShortcuts:b,registerActionHandlers:S,onActiveTabChange:A,requestedActiveTabKey:u,requestedRemoteIdeId:h,onRequestedActiveTabConsumed:y,scrollToBottomRequest:l}){var Te,Ae,Qe;const{theme:j}=Un(),{sendCommand:P}=Ct(),k=a.useRef(null),g=a.useRef(null),N=a.useRef(!1),v=a.useRef(!1),w=a.useRef(!1),M=a.useRef(null),T=a.useRef([]),[$,E]=a.useState(null),[F,D]=a.useState(!1),[C,V]=a.useState(!1),[J,I]=a.useState(0),R=a.useRef(null),B=a.useMemo(()=>fi(typeof window<"u"?window.innerWidth:1280),[]),z=a.useRef(typeof window>"u"?{}:Ku(B)),Z=a.useMemo(()=>new Map(e.map(K=>[K.tabKey,K])),[e]),fe=a.useMemo(()=>Fs(r),[r]),Pe=a.useMemo(()=>{const K=k.current;return K?K.groups.some(O=>{try{const G=O.model.location.type;return G!=="floating"&&G!=="popout"?!1:O.panels.some(H=>Z.has(H.id))}catch{return!1}}):!1},[Z,J,e]),ke=a.useCallback(()=>{var K;(K=k.current)==null||K.focus()},[]),ve=a.useCallback(K=>{const O=document,G=K.document;for(const le of O.querySelectorAll('link[rel="stylesheet"]')){const $e=G.createElement("link");$e.rel="stylesheet",$e.href=le.href,le.crossOrigin&&($e.crossOrigin=le.crossOrigin),G.head.appendChild($e)}for(const le of O.querySelectorAll("style")){const $e=G.createElement("style");$e.textContent=le.textContent,G.head.appendChild($e)}const H=[];for(const le of O.styleSheets)try{for(const $e of le.cssRules)$e instanceof CSSStyleRule&&($e.selectorText===":root"||$e.selectorText==="html")&&H.push($e.cssText)}catch{}if(H.length>0){const le=G.createElement("style");le.textContent=H.join(`
42
+ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:w,onCancel:()=>p(null)})]})}const nu=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function au(){const{preference:e,setPreference:s}=Un();return t.jsx("div",{className:"flex gap-2",children:nu.map(r=>t.jsxs("button",{onClick:()=>s(r.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===r.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===r.id?{color:"var(--accent-on-primary)"}:void 0,children:[t.jsx("span",{children:r.icon}),r.label]},r.id))})}function ou(e){const s=e.trim();return/^#[0-9a-fA-F]{6}$/.test(s)?s:/^#[0-9a-fA-F]{3}$/.test(s)?`#${s[1]}${s[1]}${s[2]}${s[2]}${s[3]}${s[3]}`:null}function iu(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Jr(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function Ea(e){const{r:s,g:r,b:n}=iu(e);return .2126*Jr(s)+.7152*Jr(r)+.0722*Jr(n)}function $a(e,s){const r=Ea(e),n=Ea(s),o=Math.max(r,n),i=Math.min(r,n);return(o+.05)/(i+.05)}function oi(e){const s=ou(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return $a(s,r)>=$a(s,n)?r:n}const wn={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},jn={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},cu=[{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"}}}],ii="adhdev-chat-theme",ci="adhdev-chat-theme-custom";function hr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(ii)||"ember"}catch{return"ember"}}function _t(e){try{const s=localStorage.getItem(ci);if(s){const r=JSON.parse(s);return{...e==="dark"?wn:jn,...r[e]}}}catch{}return e==="dark"?wn:jn}function sr(e,s){try{localStorage.setItem(ci,JSON.stringify({dark:e,light:s}))}catch{}}function Nt(e,s){const r=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16);return`rgba(${r}, ${n}, ${o}, ${s})`}function Cr(e,s){const r=Math.min(255,parseInt(e.slice(1,3),16)+s),n=Math.min(255,parseInt(e.slice(3,5),16)+s),o=Math.min(255,parseInt(e.slice(5,7),16)+s);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`}const lu={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Es(e,s){var o;const r=(o=lu[e])==null?void 0:o[s];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",Cr(r,24)),n.style.setProperty("--accent-on-primary",oi(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Cr(r,18)})`),n.style.setProperty("--border-accent",Nt(r,.35)),n.style.setProperty("--nav-active-bg",Nt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Nt(r,.06)}`)}function Qt(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",Nt(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",Nt(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",Nt(e.borderSubtle,.25)),s.style.setProperty("--text-primary",e.textPrimary),s.style.setProperty("--text-secondary",e.textSecondary),s.style.setProperty("--text-muted",e.textMuted),s.style.setProperty("--border-subtle",Nt(e.borderSubtle,.5)),s.style.setProperty("--border-default",Nt(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",Cr(e.accentColor,30)),s.style.setProperty("--accent-on-primary",oi(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Cr(e.accentColor,40)})`),s.style.setProperty("--border-accent",Nt(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",Nt(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Nt(e.accentColor,.06)}`),s.style.setProperty("--chat-user-bg",e.userBubble),s.style.setProperty("--chat-user-color",e.userText),s.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),s.style.setProperty("--chat-assistant-bg",e.assistantBubble),s.style.setProperty("--chat-assistant-color",e.assistantText),s.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),s.style.setProperty("--chat-assistant-border",`1px solid ${Nt(e.accentColor,.12)}`),s.style.setProperty("--chat-container-bg",e.containerBg),s.style.setProperty("--dashboard-pane-bg",e.containerBg),s.style.setProperty("--chat-thought-accent",e.accentColor),s.style.setProperty("--chat-tool-accent",e.accentColor),s.style.setProperty("--chat-action-color",e.accentColor),s.style.setProperty("--chat-send-bg",e.sendButton),s.style.setProperty("--chat-input-border",e.inputBorder)}function zn(){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 du(e){try{localStorage.setItem(ii,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=es()?"dark":"light";Qt(_t(s))}else zn(),Es(e,es()?"dark":"light")}function uu(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=hr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=es()?"dark":"light";Qt(_t(s))}else zn(),Es(e,es()?"dark":"light")}function es(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function ht({label:e,value:s,onChange:r}){return t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[t.jsx("input",{type:"color",value:s,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),t.jsx("input",{type:"text",value:s,onChange:n=>{/^#[0-9a-fA-F]{0,6}$/.test(n.target.value)&&r(n.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function Is({title:e,children:s}){return t.jsxs("div",{style:{marginBottom:14},children:[t.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s})]})}function mu({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,o]=a.useState(()=>_t(r));a.useEffect(()=>{o(_t(r))},[r]);const i=a.useCallback((c,d)=>{o(m=>{const f={...m,[c]:d},x=_t(r==="dark"?"light":"dark");return r==="dark"?sr(f,x):sr(x,f),Qt(f),s(f),f})},[r,s]);return t.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[t.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",t.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsxs(Is,{title:"App Background",children:[t.jsx(ht,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),t.jsx(ht,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),t.jsx(ht,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),t.jsxs(Is,{title:"App Text",children:[t.jsx(ht,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),t.jsx(ht,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),t.jsx(ht,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),t.jsxs(Is,{title:"Borders & Accent",children:[t.jsx(ht,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),t.jsx(ht,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),t.jsx(ht,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),t.jsxs("div",{children:[t.jsxs(Is,{title:"Chat Bubbles",children:[t.jsx(ht,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),t.jsx(ht,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),t.jsx(ht,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),t.jsx(ht,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),t.jsxs(Is,{title:"Chat Layout",children:[t.jsx(ht,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),t.jsx(ht,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),t.jsx(ht,{label:"Input border",value:n.inputBorder,onChange:c=>i("inputBorder",c)}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[t.jsx("input",{type:"range",min:4,max:24,value:n.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),t.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),t.jsx("button",{onClick:()=>{const c=e?wn:jn,m=_t(e?"light":"dark");e?sr(c,m):sr(m,c),o(c),Qt(c),s(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:"Reset to defaults"})]})}function pu(){const[e,s]=a.useState(hr),[r,n]=a.useState(!0),[o,i]=a.useState(()=>_t("dark"));a.useEffect(()=>{n(es());const m=new MutationObserver(()=>{const x=es();n(x);const b=hr();b==="custom"?Qt(_t(x?"dark":"light")):Es(b,x?"dark":"light")});m.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const f=window.matchMedia("(prefers-color-scheme: dark)"),p=()=>{const x=es();n(x);const b=hr();b==="custom"?Qt(_t(x?"dark":"light")):Es(b,x?"dark":"light")};return f.addEventListener("change",p),()=>{m.disconnect(),f.removeEventListener("change",p)}},[]),a.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?Qt(_t(r?"dark":"light")):(zn(),Es(e,r?"dark":"light"))},[e,r]),a.useEffect(()=>{i(_t(r?"dark":"light"))},[r]);const c=m=>{s(m),du(m)},d=[...cu,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText},light:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText}}}];return t.jsxs("div",{children:[t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:d.map(m=>{const f=e===m.id,p=r?m.preview.dark:m.preview.light,x=m.id==="honey"||m.id==="ember"?"#1a1a1a":m.id==="custom"?o.userText:"#fff";return t.jsxs("button",{onClick:()=>c(m.id),className:"text-left rounded-xl p-3 transition-all",style:{background:f?"var(--bg-glass-hover)":"var(--bg-glass)",border:f?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:f?1:.75},children:[t.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:p.containerBg},children:[t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:p.assistantBubble,border:p.assistantBorder,color:p.textColor},children:"Hello! How can I help?"}),t.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:p.userBubble,color:x},children:"Fix the bug please"}),t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:p.assistantBubble,border:p.assistantBorder,color:p.textColor},children:"On it! ✨"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[f&&t.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:m.id==="custom"?"🎨 Custom":m.name}),t.jsx("div",{className:"text-[10px] text-text-muted",children:m.description})]})]})]},m.id)})}),e==="custom"&&t.jsx(mu,{dark:r,onColorsChange:m=>i(m)})]})}const li="adhdev_mobileDashboardMode_v1";function di(){try{return localStorage.getItem(li)==="workspace"?"workspace":"chat"}catch{return"chat"}}function fu(e){try{localStorage.setItem(li,e)}catch{}}function xu(){const[e,s]=a.useState(!0);return a.useEffect(()=>{s(di()==="chat")},[]),t.jsx(Gt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Kt,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:r=>{s(r),fu(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}function hu(e,s,r){return{...e||{},id:s,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:r.timestamp,platform:r.machine.platform,machine:{...(e==null?void 0:e.machine)||{},...r.machine}}}function bu(e,s){const{sendData:r}=Ct(),{injectEntries:n,getIdes:o}=vr(),i=Array.from(new Set(e.filter(Boolean))).join("|");a.useEffect(()=>{if(!(s!=null&&s.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const d=c.map(m=>Ot.subscribe({sendData:r},m,{type:"subscribe",topic:"machine.runtime",key:`machine:${m}`,params:{intervalMs:s==null?void 0:s.intervalMs}},f=>{const p=o().find(b=>b.id===m),x=hu(p,m,f);n([x])}));return()=>{d.forEach(m=>m())}},[i,o,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}const gu=4e3;function ui(e,s){const{sendData:r}=Ct(),[n,o]=a.useState(null),[i,c]=a.useState(!1);return a.useEffect(()=>{if(!e){o(null),c(!1);return}if(!(s!=null&&s.enabled)||!r){c(!1);return}o(null),c(!0);let d=null;const m=Ot.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(s==null?void 0:s.includeSessions)!==!1,...typeof(s==null?void 0:s.limit)=="number"?{limit:s.limit}:{},...typeof(s==null?void 0:s.intervalMs)=="number"?{intervalMs:s.intervalMs}:{}}},f=>{d&&(clearTimeout(d),d=null),o(f.diagnostics),c(!1)});return m.initialSendAccepted?d=setTimeout(()=>{c(!1)},gu):c(!1),()=>{d&&clearTimeout(d),m()}},[e,s==null?void 0:s.enabled,s==null?void 0:s.includeSessions,s==null?void 0:s.intervalMs,s==null?void 0:s.limit,r]),{diagnostics:n,loading:i,applyDiagnostics:o}}function yu(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function mi(e){const{sendData:s}=Ct(),[r,n]=a.useState({});return a.useEffect(()=>{const o=yu(e);if(!o||!e.sessionId||!s){n({});return}const i=Ot.subscribe({sendData:s},o,{type:"subscribe",topic:"session.modal",key:`daemon:${o}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),ss.record({interactionId:c.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:c.status,modalButtonCount:Array.isArray(c.modalButtons)?c.modalButtons.length:0}})});return()=>{i()}},[e.daemonId,e.routeId,e.sessionId,s]),r}const pi="adhdev_hiddenTabs";function vu(){try{const e=localStorage.getItem(pi);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ds(e){try{localStorage.setItem(pi,JSON.stringify([...e]))}catch{}}function wu(){const[e,s]=a.useState(vu),r=a.useCallback(f=>{s(p=>{const x=new Set(p);return x.has(f)?x.delete(f):x.add(f),ds(x),x})},[]),n=a.useCallback(f=>{s(p=>{if(p.has(f))return p;const x=new Set(p);return x.add(f),ds(x),x})},[]),o=a.useCallback(f=>{s(p=>{if(!p.has(f))return p;const x=new Set(p);return x.delete(f),ds(x),x})},[]),i=a.useCallback(()=>{s(f=>{if(f.size===0)return f;const p=new Set;return ds(p),p})},[]),c=a.useCallback((f,p)=>{s(x=>{const b=new Set(x);for(const S of p)b.add(S);return ds(b),b})},[]),d=a.useCallback((f,p)=>{s(x=>{const b=new Set(x);for(const S of p)b.delete(S);return ds(b),b})},[]),m=a.useCallback(f=>e.has(f),[e]);return{hiddenTabs:e,toggleTab:r,hideTab:n,showTab:o,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:d,isHidden:m}}function ju({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){a.useEffect(()=>{Il()},[]);const o=a.useMemo(()=>e.map(i=>({id:i.tabKey,name:Uo(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Al(o),a.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(d=>{const m=Date.now(),f={};for(const[p,x]of Object.entries(d))m-x<5e3&&(f[p]=x);return Object.keys(f).length===Object.keys(d).length?d:f})},5500);return()=>clearTimeout(c)},[s,r]),a.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(d=>{const m=d.filter(f=>f.timestamp>c).slice(-100);return m.length===d.length?d:m})},6e4);return()=>clearInterval(i)},[n]),null}function ku(e){const s=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of s){const o=r.get(n.id);if(!o){r.set(n.id,n);continue}const i=(o.workspace?1:0)+(o.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>i||(n.timestamp||0)>(o.timestamp||0))&&r.set(n.id,n)}return Array.from(r.values())}function rr(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==s[r])return!1;return!0}function Nu(e,s){const r=Date.now();return e.map(n=>{const o=s[n.tabKey];return o&&r-o<5e3?{...n,messages:[],title:""}:n})}function Su(e,s){const r=[],n=e.sessionId||e.instanceId;r.push({key:e.id,ref:s[e.id]}),n&&r.push({key:n,ref:s[n]});for(const o of e.childSessions||[]){const i=o.id||o.providerType,c=`${e.id}:${i}`;r.push({key:c,ref:s[c]}),r.push({key:o.id,ref:s[o.id]})}return r}function Cu(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r].key!==s[r].key||e[r].ref!==s[r].ref)return!1;return!0}function Iu(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function Tu(e){const s=Iu(e);if(!s)return`empty:${e.messages.length}`;if(s.id)return`id:${String(s.id)}`;if(s._localId)return`local:${String(s._localId)}`;const r=String(s.role||""),n=as(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Au({ides:e,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:o}){const i=a.useRef([]),c=a.useRef([]),d=a.useRef([]),m=a.useRef([]),f=a.useMemo(()=>{const g=ku(e);return rr(i.current,g)?i.current:(i.current=g,g)},[e]),p=a.useMemo(()=>Jo(e),[e]),x=a.useRef(new Map),b=a.useRef(new Map),S=a.useMemo(()=>{const g=new Map,N=[];for(const T of f){const{connectionState:$="new",machineName:E}=Zo(T,{machineNames:p,connectionStates:s,defaultConnectionState:"new"}),F=Su(T,r),D=x.current.get(T.id);if(D&&D.ide===T&&D.connectionState===$&&D.machineName===E&&Cu(D.localRefs,F)){g.set(T.id,D),N.push(...D.conversations);continue}const C=Hn(T,r,{machineNames:p,connectionStates:s,defaultConnectionState:"new"}),V={ide:T,connectionState:$,machineName:E,localRefs:F,conversations:C};g.set(T.id,V),N.push(...C)}x.current=g;const v=new Map,w=T=>{const $=Tu(T),E=b.current.get(T.tabKey);if(E&&E.signature===$)return v.set(T.tabKey,E),E.timestamp;const F={signature:$,timestamp:Fo(T)||(E==null?void 0:E.timestamp)||0};return v.set(T.tabKey,F),F.timestamp},M=[...N].sort((T,$)=>kr(T,$,w));return b.current=v,M},[f,r,s,p]),A=a.useMemo(()=>{const g=Nu(S,n);return rr(c.current,g)?c.current:(c.current=g,g)},[S,n]),u=a.useMemo(()=>{const g=new Map,N=Array.from(new Set(A.map(v=>v.routeId)));for(const v of N){const w=Lt(A,v);w&&g.set(v,w)}return g},[A]),h=a.useMemo(()=>{const g=new Map;for(const N of A)if(N.sessionId&&g.set(N.sessionId,N),N.streamSource==="native"&&N.sessionId){const v=u.get(N.routeId);v&&g.set(N.sessionId,v)}return g},[A,u]),y=a.useMemo(()=>{const g=new Map;for(const N of A)N.sessionId&&g.set(N.sessionId,N),g.set(N.routeId,u.get(N.routeId)||N),g.set(N.tabKey,N);return g},[A,u]),l=a.useCallback(g=>{if(g)return h.get(g)},[h]),j=a.useCallback(g=>{if(g)return y.get(g)},[y]),P=a.useMemo(()=>{const g=A.filter(N=>!o.has(N.tabKey));return rr(d.current,g)?d.current:(d.current=g,g)},[A,o]),k=a.useMemo(()=>{const g=P.map(N=>N.tabKey);return rr(m.current,g)?m.current:(m.current=g,g)},[P]);return{chatIdes:f,conversations:A,visibleConversations:P,visibleTabKeys:k,resolveConversationBySessionId:l,resolveConversationByTarget:j}}function Mu({isMobile:e,urlActiveTab:s,resolveConversationBySessionId:r,setSearchParams:n}){const o=a.useMemo(()=>{var d;return e||!s?null:((d=r(s))==null?void 0:d.tabKey)??null},[e,r,s]),i=a.useMemo(()=>{var d;return!e||!s?null:((d=r(s))==null?void 0:d.tabKey)??null},[e,r,s]),c=a.useCallback(()=>{s&&n(d=>{const m=new URLSearchParams(d);return m.delete("activeTab"),m},{replace:!0})},[n,s]);return{requestedDesktopTabKey:o,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function _u({ides:e,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:o}){a.useEffect(()=>{tt.setIdes(e)},[e]),a.useEffect(()=>{tt.setResolveAction((i,c,d)=>{s(i,c,d).catch(()=>{})})},[s]),a.useEffect(()=>{const i=tt.onToast(m=>{r(p=>p.some(b=>b.message===m.message&&m.timestamp-b.timestamp<3e3)?p:[...p.slice(-4),{id:m.id,message:m.message,type:m.type,timestamp:m.timestamp,targetKey:m.targetKey,actions:m.actions}]);const f=m.duration||5e3;setTimeout(()=>r(p=>p.filter(x=>x.id!==m.id)),f)}),c=tt.onSystemMessage((m,f)=>{var S,A;const p=o(m),x=(S=f._localId)==null?void 0:S.startsWith("sys_approval_"),b=!!(p&&(p.status==="waiting_approval"||(A=p.modalButtons)!=null&&A.length||p.modalMessage));x&&b||n(u=>({...u,[m]:[...u[m]||[],f]}))}),d=tt.onClearSystemMessage((m,f)=>{n(p=>{var x;return(x=p[m])!=null&&x.length?{...p,[m]:p[m].filter(b=>{var S;return!(b.role==="system"&&((S=b._localId)!=null&&S.startsWith(f)))})}:p})});return()=>{i(),c(),d()}},[r,n]),a.useEffect(()=>{const i=Wo.on("status_event",c=>{tt.handleRawEvent(c,"ws")});return()=>{i()}},[]),a.useEffect(()=>{var c;const i=d=>{var h;const m=d.data;if((m==null?void 0:m.type)!=="notification_action"||typeof m.action!="string"||!m.action.startsWith("approval_")||!(m.daemonId||m.targetSessionId||m.targetKey))return;const f=m.targetSessionId||m.targetKey||m.daemonId,p=o(f),x=(p==null?void 0:p.routeId)||m.daemonId;if(!x)return;const b=Number(m.buttonIndex),S=m.button||((h=p==null?void 0:p.modalButtons)==null?void 0:h[b])||"Approve",A=String(S).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),u=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(A);s(x,"resolve_action",{action:u?"approve":"reject",button:S,...Number.isFinite(b)&&{buttonIndex:b},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...m.targetSessionId&&{targetSessionId:m.targetSessionId}}).catch(y=>console.error("[SW Action] approval failed:",y))};return(c=navigator.serviceWorker)==null||c.addEventListener("message",i),()=>{var d;return(d=navigator.serviceWorker)==null?void 0:d.removeEventListener("message",i)}},[o,s])}const Pu="adhdev_dashboardLayout_v1",Ru="adhdev_dashboardDockview_v1",Lu="adhdev_dashboardDockviewHiddenRestore_v1",Ts={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Fn(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function fi(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function xi(e){return`${Pu}:${e}`}function Du(e){const s=xi(e);return Fn(s,null)}function Eu(e,s){try{const r=s.groupAssignments.length===0&&s.focusedGroup===0&&Object.keys(s.groupActiveTabIds).length===0&&Object.keys(s.groupTabOrders).length===0&&s.groupSizes.length===0,n=xi(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function hi(e){return`${Ru}:${e}`}function $u(e){const s=hi(e);return Fn(s,null)}function Bu(e,s){try{const r=hi(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function bi(e){return`${Lu}:${e}`}function Ku(e){const s=bi(e);return Fn(s,{})}function Wu(e,s){try{const r=bi(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Ou(){return{groupAssignments:[...Ts.groupAssignments],focusedGroup:Ts.focusedGroup,groupActiveTabIds:{...Ts.groupActiveTabIds},groupTabOrders:{...Ts.groupTabOrders},groupSizes:[...Ts.groupSizes]}}function Hu(){const[e]=a.useState(()=>fi(typeof window<"u"?window.innerWidth:1280)),[s,r]=a.useState(()=>new Map),[n,o]=a.useState(0),[i,c]=a.useState({}),[d,m]=a.useState({}),[f,p]=a.useState([]),[x,b]=a.useState(()=>typeof window<"u"&&window.innerWidth<768),[S,A]=a.useState(!1),u=a.useCallback(()=>{if(S)return;const h=Du(e)??Ou();r(new Map(h.groupAssignments)),o(h.focusedGroup),c(h.groupActiveTabIds),m(h.groupTabOrders),p(h.groupSizes),A(!0)},[S,e]);return a.useEffect(()=>{S&&Eu(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:d,groupSizes:f})},[S,e,s,n,i,d,f]),a.useEffect(()=>{const h=window.matchMedia("(max-width: 767px)"),y=l=>b(l.matches);return h.addEventListener("change",y),()=>h.removeEventListener("change",y)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:o,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:d,setGroupTabOrders:m,groupSizes:f,setGroupSizes:p,isMobile:x,hasHydratedStoredLayout:S,hydrateStoredLayout:u}}function Uu(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=[s.providerSessionId,s.sessionId].filter(o=>typeof o=="string"&&o.length>0);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function zu({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:o,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:d,setSearchParams:m,historyModalOpen:f,activeConv:p,isRefreshingHistory:x,ides:b,handleRefreshHistory:S}){const A=a.useRef(!1),u=a.useRef(!1),h=a.useRef(null),y=a.useRef(!1);a.useEffect(()=>{if(!e||A.current||s.length===0)return;if(!o){i();return}const l=r(e);if(!l)return;const j=n.get(l.tabKey)??0;c(P=>({...P,[j]:l.tabKey})),d(j),A.current=!0,u.current=!0,h.current!=null&&(window.clearTimeout(h.current),h.current=null),m(P=>{const k=new URLSearchParams(P);return k.delete("activeTab"),k},{replace:!0})},[e,s,r,n,o,i,c,d,m]),a.useEffect(()=>{if(!(u.current||o)&&s.length!==0){if(!e){i(),u.current=!0;return}if(A.current){u.current=!0;return}if(h.current==null)return h.current=window.setTimeout(()=>{h.current=null,!(u.current||o)&&(i(),u.current=!0)},1500),()=>{h.current!=null&&(window.clearTimeout(h.current),h.current=null)}}},[e,s.length,o,i]),a.useEffect(()=>{if(!f){y.current=!1;return}if(!p||y.current||x)return;const l=b.find(j=>j.id===p.routeId);l&&(!l.chats||l.chats.length===0||Uu(l.chats,p))&&(y.current=!0,S())},[f,p,x,b,S]),a.useEffect(()=>{if(!p)return;let l=null,j=0,P=-1,k=0;const g=()=>{l=null;const N=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(w=>w.offsetParent!==null);if(N.length===0){j<18&&(j+=1,l=requestAnimationFrame(g));return}let v=0;for(const w of N)w.scrollTop=w.scrollHeight,v+=w.scrollHeight;v===P?k+=1:(k=0,P=v),j+=1,!(k>=2||j>=18)&&(l=requestAnimationFrame(g))};return l=requestAnimationFrame(g),()=>{l!=null&&cancelAnimationFrame(l)}},[p==null?void 0:p.tabKey])}function Fu({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:o,conversations:i,ides:c,resolveConversationByTarget:d}){const[m,f]=a.useState(null),[p,x]=a.useState(null),b=a.useMemo(()=>{if(e||!n)return null;const y=d(n);return y&&!Ye(y)&&!Ve(y)?y:null},[e,n,d]),S=a.useMemo(()=>{const y=m==null?void 0:m.routeId;if(!y)return null;const l=m!=null&&m.tabKey?i.find(j=>j.tabKey===m.tabKey):o?i.find(j=>j.tabKey===o):null;return(l==null?void 0:l.routeId)===y?l:Lt(i,y)},[i,m,o]),A=a.useMemo(()=>{if(S)return c.find(y=>y.id===S.routeId)},[c,S]);a.useEffect(()=>{b&&(f({routeId:b.routeId,tabKey:wa(b)}),x(b),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,b]);const u=a.useCallback(y=>{y&&(f({routeId:y.routeId,tabKey:wa(y)}),x(y))},[]),h=a.useCallback(()=>{f(null),x(null)},[]);return{remoteDialogConv:S,remoteDialogIdeEntry:A,remoteDialogActiveConv:p,setRemoteDialogActiveConv:x,openRemoteDialog:u,closeRemoteDialog:h}}function hs(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:Ye(e)||Ve(e)?{agentType:wt(e)}:e.streamSource==="agent-stream"?{agentType:wt(e)}:s}function Us(e){return e?wr(e):""}function As(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function Zr(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0];if((r==null?void 0:r.active)===!0)return!0;const n=[s.providerSessionId,s.sessionId].filter(o=>typeof o=="string"&&o.length>0);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Ba({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:o,setLocalUserMessages:i,setClearedTabs:c}){const[d,m]=a.useState(!1),[f,p]=a.useState(!1),x=a.useCallback(async u=>{try{await e("standalone","launch_ide",{ideType:u,enableCdp:!0})}catch(h){console.error("Launch failed",h)}},[e]),b=a.useCallback(async(u,h)=>{try{const y=u||(s==null?void 0:s.daemonId)||"",l=await e(y,"switch_chat",{id:h,sessionId:h,...hs(s)}),j=l==null?void 0:l.result;if((l==null?void 0:l.success)===!0||j==="switched"||j==="switched-by-title")return;j===!1||j==="not_found"?As(o,"⚠️ Session tab not found — try refreshing history"):typeof j=="string"&&j.startsWith("error:")?As(o,`⚠️ Switch error: ${j}`):As(o,"⚠️ Session switch failed")}catch(y){console.error("Switch failed",y),As(o,`❌ Switch failed: ${y.message||"connection error"}`)}},[s,e,o]),S=a.useCallback(async()=>{if(!(!s||d)){m(!0);try{const u=Us(s);await e(u,"new_chat",{...hs(s)}),c(h=>({...h,[s.tabKey]:Date.now()})),i(h=>({...h,[s.tabKey]:[]}))}catch(u){console.error("New chat failed",u)}finally{m(!1)}}},[s,d,e,c,i]),A=a.useCallback(async()=>{var u,h;if(!(!s||f)){p(!0);try{const y=Us(s),l=async()=>e(y,"list_chats",{forceExpand:!0,...hs(s)});let j=await l(),P=(j==null?void 0:j.chats)||((u=j==null?void 0:j.result)==null?void 0:u.chats);Zr(P,s)&&(await new Promise(k=>setTimeout(k,450)),j=await l(),P=(j==null?void 0:j.chats)||((h=j==null?void 0:j.result)==null?void 0:h.chats)),j!=null&&j.success&&Array.isArray(P)&&(n(s.routeId,P),Zr(P,s)&&!Zr(r,s)&&As(o,"⚠️ History dialog did not fully open — try once more"))}catch(y){console.error("Refresh history failed",y)}finally{p(!1)}}},[s,r,f,e,n,o]);return{isCreatingChat:d,isRefreshingHistory:f,handleLaunchIde:x,handleSwitchSession:b,handleNewChat:S,handleRefreshHistory:A}}function Vu(e,s){if(e.size!==s.size)return!1;for(const[r,n]of e)if(s.get(r)!==n)return!1;return!0}function Gu(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function Ka(e,s){const r=Object.keys(e),n=Object.keys(s);return r.length!==n.length?!1:r.every(o=>s[Number(o)]===e[Number(o)])}function nr(e,s){const r=new Set(s),n=s.length>0?[0]:[];for(const[c,d]of e)!r.has(c)||d<=0||n.includes(d)||n.push(d);n.sort((c,d)=>c-d);const o={};n.forEach((c,d)=>{o[c]=d}),n.length===0&&(o[0]=0);const i=new Map;for(const[c,d]of e){if(!r.has(c)||d<=0)continue;const m=o[d];typeof m=="number"&&m>0&&i.set(c,m)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:o,usedGroups:n}}function Wa(e,s){const r={};for(const[n,o]of Object.entries(e)){const i=s[Number(n)];typeof i=="number"&&(r[i]=o)}return r}function qu(e,s,r){if(s.length===0)return 0;if(typeof r[e]=="number")return r[e];const n=[...s].reverse().find(o=>o<e)??s[0];return r[n]??0}function Yu(e,s,r){if(s.length<=1)return[];const n=s.map(c=>e[c]).filter(c=>Number.isFinite(c)),o=n.length===s.length?n:Array(r).fill(100/r),i=o.reduce((c,d)=>c+d,0);return i>0?o.map(c=>c/i*100):Array(r).fill(100/r)}function Oa(e,s){const r={};for(const[n,o]of Object.entries(e)){const i=Number(n);r[i>=s?i+1:i]=o}return r}function Ha(e){return Array(e).fill(100/e)}function Xu({groupAssignments:e,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:o,groupSizes:i,setGroupSizes:c,isMobile:d,visibleConversations:m,visibleTabKeys:f}){const p=a.useRef(null),x=a.useMemo(()=>nr(e,f),[e,f]),b=x.assignments,S=a.useMemo(()=>d?1:x.groupCount,[x.groupCount,d]),A=S>1,u=a.useCallback((k,g)=>{s(N=>{const v=new Map(nr(N,f).assignments);return g===0?v.delete(k):v.set(k,g),v}),n(N=>({...N,[g]:k})),r(g)},[s,f,n,r]),h=a.useCallback(k=>{s(g=>{const N=nr(g,f).assignments,v=new Map;for(const[w,M]of N)M!==k&&(M>k?v.set(w,M-1):v.set(w,M));return v}),c(g=>{if(g.length<=1)return[];const N=[...g];N.splice(k,1);const v=N.reduce((w,M)=>w+M,0);return v>0?N.map(w=>w/v*100):[]}),r(0)},[s,f,c,r]),y=a.useCallback((k,g)=>{g.preventDefault();const N=p.current;if(!N)return;const v=g.clientX,w=N.offsetWidth,M=i.length===S?[...i]:Ha(S),T=E=>{const D=(E.clientX-v)/w*100,C=[...M];C[k]=Math.max(15,M[k]+D),C[k+1]=Math.max(15,M[k+1]-D),c(C)},$=()=>{document.removeEventListener("mousemove",T),document.removeEventListener("mouseup",$),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",T),document.addEventListener("mouseup",$)},[i,S,c]),l=a.useCallback((k,g,N)=>{if(S>=4)return;const v=N==="left"?g:g+1;s(w=>{const M=nr(w,f).assignments,T=new Map;for(const $ of m){const E=M.get($.tabKey)??0,F=E>=v?E+1:E;F>0&&T.set($.tabKey,F)}return v>0&&T.set(k,v),T}),c(w=>{const M=w.length===S?[...w]:Ha(S),T=M[g]??100/S,$=Math.max(15,T/2),E=Math.max(15,T/2),F=[...M];F[g]=$,F.splice(v,0,E);const D=F.reduce((C,V)=>C+V,0);return F.map(C=>C/D*100)}),n(w=>{const M=Oa(w,v);return M[v]=k,M}),o(w=>{const M=Oa(w,v);return M[v]=[k],M}),r(v)},[S,s,f,m,c,n,o,r]);a.useEffect(()=>{Vu(e,b)||s(b)},[e,b,s]),a.useEffect(()=>{const{mapping:k,usedGroups:g}=x;n(N=>{const v=Wa(N,k);return Ka(N,v)?N:v}),o(N=>{const v=Wa(N,k);return Ka(N,v)?N:v}),r(N=>{const v=d?0:qu(N,g,k);return N===v?N:v}),c(N=>{const v=d?[]:Yu(N,g,x.groupCount);return Gu(N,v)?N:v})},[x,d,n,o,r,c]);const j=a.useMemo(()=>{const k=Array.from({length:S},()=>[]);for(const g of m){const N=b.get(g.tabKey)??0,v=Math.min(N,S-1);k[v].push(g)}return k},[m,b,S]),P=a.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:p,normalizedGroupAssignments:b,numGroups:S,isSplitMode:A,groupedConvs:j,moveTabToGroup:u,closeGroup:h,handleResizeStart:y,splitTabRelative:l,clearAllSplits:P}}function Ju({ides:e,sendDaemonCommand:s}){const r="0.8.56",n=a.useMemo(()=>e.filter(p=>p.type!=="adhdev-daemon"?!1:ai(p,r)).sort((p,x)=>Number(Ds(x,r))-Number(Ds(p,r))),[r,e]),o=a.useMemo(()=>n.some(p=>Ds(p,r)),[r,n]),[i,c]=a.useState(!1),[d,m]=a.useState({}),f=a.useCallback(async p=>{var x,b;m(S=>({...S,[p]:"upgrading"}));try{const S=await s(p,"daemon_upgrade",{});(x=S==null?void 0:S.result)!=null&&x.upgraded||(b=S==null?void 0:S.result)!=null&&b.success?m(A=>({...A,[p]:"done"})):m(A=>({...A,[p]:"error"}))}catch{m(S=>({...S,[p]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:o,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:f}}function Ua(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Vn(e){return e instanceof Error?e.message:String(e||"")}function za(e){const s=Vn(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Fa(e,s){const r=Vn(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function Lr({sendDaemonCommand:e,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:o}){const[i,c]=a.useState(!1),[d,m]=a.useState(!1),f=a.useRef(!1),p=a.useRef(null),x=a.useCallback(async u=>{if(!s)return;const h=u.trim();if(!h||f.current)return;const y=s.tabKey,l=Date.now(),j=p.current;if(j&&j.tabKey===y&&j.message===h&&l-j.timestamp<2e3)return;f.current=!0,m(!0),p.current={tabKey:y,message:h,timestamp:l};const P=`${l}-${Math.random().toString(36).slice(2,8)}`,k={role:"user",content:h,timestamp:l,_localId:P},g=!(Ye(s)||Ve(s));g&&r(N=>({...N,[y]:[...N[y]||[],k]}));try{const N=Us(s);if(!N)return;const v=await e(N,"send_chat",{message:h,...hs(s)}),w=Ua(v);if(g&&(w!=null&&w.deduplicated||(w==null?void 0:w.sent)===!1)){r(M=>({...M,[y]:(M[y]||[]).filter(T=>T._localId!==P)}));return}if((w==null?void 0:w.success)===!1)throw new Error((w==null?void 0:w.error)||"Send failed");setTimeout(()=>{const M=Date.now()-6e4;r(T=>{const $=T[y];if(!$)return T;const E=$.filter(F=>F.timestamp>M);return E.length===$.length?T:{...T,[y]:E}})},6e4)}catch(N){const v=Vn(N);v.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",v):console.error("Send failed",N),g&&r(w=>({...w,[y]:(w[y]||[]).filter(M=>M._localId!==P)}))}finally{f.current=!1,m(!1)}},[s,e,r]),b=a.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await e(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(u){console.error("Relaunch failed",u)}},[s,e]),S=a.useCallback(async u=>{if(s)try{const y=(s.modalButtons||[]).indexOf(u),l=u.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),j=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(l),P=Us(s);if(!P)return;const k=await e(P,"resolve_action",{button:u,action:j?"approve":"reject",...y>=0&&{buttonIndex:y},...hs(s)}),g=Ua(k);g.success||n(N=>[...N,{routeId:s.tabKey,text:Fa(u,g==null?void 0:g.error),timestamp:Date.now()}])}catch(h){za(h)||console.error("[ModalButton] Error:",h),n(y=>[...y,{routeId:s.tabKey,text:za(h)?Fa(u,h):`❌ **${u}** error`,timestamp:Date.now()}])}},[s,e,n]),A=a.useCallback(async()=>{if(!(!s||i)){c(!0);try{await e(s.routeId,"focus_session",{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(u){console.error("Focus agent failed",u)}finally{c(!1)}}},[s,i,e]);return{isSendingChat:d,isFocusingAgent:i,handleSendChat:x,handleRelaunch:b,handleModalButton:S,handleFocusAgent:A}}const Gn=a.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:o,terminalRef:i,handleModalButton:c,handleRelaunch:d,handleSendChat:m,isSendingChat:f,handleFocusAgent:p,isFocusingAgent:x,actionLogs:b,userName:S,scrollToBottomRequestNonce:A,isInputActive:u=!0}){const h=mi(s),y=h.status||h.modalMessage||h.modalButtons?{...s,...h.status?{status:h.status}:{},...h.modalMessage!==void 0?{modalMessage:h.modalMessage}:{},...h.modalButtons!==void 0?{modalButtons:h.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(Io,{activeConv:y,onModalButton:c}),y.transport!=="pty"&&y.transport!=="acp"&&y.cdpConnected===!1?t.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:t.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[t.jsx("span",{className:"text-sm",children:t.jsx(ns,{size:14})}),t.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),t.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:d,children:"Relaunch with CDP"})]})}):null,y.transport==="pty"?t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{display:n?"flex":"none",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(vd,{activeConv:y,clearToken:r,terminalRef:i,handleSendChat:m,isSendingChat:f,isVisible:n})}),!n&&t.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(bn,{activeConv:y,ideEntry:o,handleSendChat:m,isSendingChat:f,handleFocusAgent:p,isFocusingAgent:x,actionLogs:b,userName:S,scrollToBottomRequestNonce:A,isInputActive:u})})]}):t.jsx(bn,{activeConv:y,ideEntry:o,handleSendChat:m,isSendingChat:f,handleFocusAgent:p,isFocusingAgent:x,actionLogs:b,userName:S,scrollToBottomRequestNonce:A,isInputActive:u})]})},(e,s)=>e.activeConv===s.activeConv&&e.isCliTerminal===s.isCliTerminal&&e.ideEntry===s.ideEntry&&e.terminalRef===s.terminalRef&&e.handleModalButton===s.handleModalButton&&e.handleRelaunch===s.handleRelaunch&&e.handleSendChat===s.handleSendChat&&e.isSendingChat===s.isSendingChat&&e.handleFocusAgent===s.handleFocusAgent&&e.isFocusingAgent===s.isFocusingAgent&&e.actionLogs===s.actionLogs&&e.userName===s.userName&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&e.isInputActive===s.isInputActive);function Zu({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:o,userName:i,isSendingChat:c,isFocusingAgent:d,onBack:m,onOpenNativeConversation:f,onOpenMachine:p,onOpenHistory:x,onOpenRemote:b,onHideConversation:S,onStopCli:A,cliViewMode:u,onSetCliViewMode:h,handleSendChat:y,handleFocusAgent:l,handleModalButton:j,handleRelaunch:P}){const k=a.useRef(null),g=Ye(e)&&!s,N=g&&u==="terminal",v=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:`flex items-center justify-between gap-3 ${v} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":"Back",children:t.jsx(Tn,{size:18})}),t.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:st(e)}),t.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:t.jsx(Do,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>f(e),onOpenMachine:()=>p(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[g&&u&&t.jsx(Kn,{mode:u,onChange:h,compact:!0}),g&&A&&t.jsx("button",{onClick:()=>{A(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:t.jsx(vt,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(e),type:"button",children:t.jsx(Mn,{size:14})}),!s&&!g&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>b(e),type:"button",children:t.jsx(kt,{size:14})}),S&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(e),type:"button",title:"Close chat",children:t.jsx(vt,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(Gn,{activeConv:e,clearToken:0,isCliTerminal:N,ideEntry:n,terminalRef:k,handleModalButton:j,handleRelaunch:P,handleSendChat:y,isSendingChat:c,handleFocusAgent:l,isFocusingAgent:d,actionLogs:o,userName:i})})]})}const Qr={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 Qu(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function gi(){const[e,s]=a.useState("unix"),[r,n]=a.useState("powershell"),[o,i]=a.useState(!1),c=e==="unix"?"unix":r;a.useEffect(()=>{s(Qu())},[]);const d=a.useCallback(()=>{navigator.clipboard.writeText(Qr[c].cmd).catch(()=>{}),i(!0),setTimeout(()=>i(!1),2e3)},[c]);return t.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[t.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[t.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>s("unix"),children:"🍎🐧 macOS / Linux"}),t.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>s("windows"),children:"🪟 Windows"})]}),e==="windows"&&t.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[t.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("powershell"),children:"⚡ PowerShell"}),t.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("cmd"),children:">_ CMD"})]}),t.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:d,title:"Click to copy",children:[t.jsx("span",{className:"text-text-muted select-none",children:Qr[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:Qr[c].cmd}),t.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:o?"✓":"📋"})]}),t.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",t.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function yi({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:kt},{key:"chats",label:"Chats",icon:Kt}];return t.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:t.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:n,label:o,icon:i})=>{const c=e===n;return t.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${c?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>s(n),type:"button","aria-pressed":c,children:[t.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:t.jsx(i,{size:15})}),t.jsx("span",{children:o})]},n)})})})}function ar({title:e,className:s=""}){return t.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${s}`,children:t.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function us({children:e,className:s=""}){return t.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${s}`,children:e})}function Ms({icon:e,title:s,subtitle:r,children:n}){return t.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[t.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),t.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:s}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function or({item:e,type:s,getAvatarText:r,onOpenConversation:n}){const o=s==="needs_attention"||s==="task_complete",i=s==="working",c=s==="earlier",d=s==="task_complete",{isReconnecting:m,isConnecting:f}=ks(e.conversation),p=st(e.conversation),x=is(e.conversation),b=Ho(e.conversation,{requiresAction:s==="needs_attention"}),S=o?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":i?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",A=o?"bg-accent-primary shadow-glow":i?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":c?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",u=c?"text-text-secondary":"text-text-primary",h=c?"text-text-muted":"text-text-secondary",y=c?"text-text-secondary opacity-80":"text-text-muted",l=c?"text-text-muted opacity-80":"text-text-muted",j="text-[color:var(--status-warning)]";return t.jsxs("button",{className:`group flex items-start gap-3.5 px-4 py-3.5 w-full text-left relative overflow-hidden transition-colors active:scale-[0.995] ${S}`,onClick:()=>n(e.conversation),type:"button",children:[o||i?t.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,t.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${A}`,style:o?{color:"var(--accent-on-primary)"}:void 0,children:r(p)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${u}`,children:p}),!i&&t.jsx("span",{className:`text-[11px] font-medium shrink-0 ${l}`,children:Co(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${h}`,children:[x,m?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${j} animate-pulse`,children:"Reconnecting…"})]}):f?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):b==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:j,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${y}`,children:e.preview})]}),o&&!d&&t.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),d&&t.jsx("span",{className:"absolute top-4 right-4 rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Done"}),i&&t.jsx("span",{className:"absolute top-4 right-4 rounded-full bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Live"})]},e.conversation.tabKey)}function Va({size:e=32,label:s}){return t.jsxs("div",{className:"flex flex-col items-center gap-2.5",children:[t.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}}),s&&t.jsx("div",{className:"text-xs font-semibold text-accent-primary-light tracking-tight",children:s})]})}function em({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:o,hiddenConversations:i,machineCards:c,getAvatarText:d,onOpenConversation:m,onShowConversation:f,onShowAllHidden:p,onOpenNewSession:x,onOpenMachine:b,onOpenSettings:S,onSectionChange:A,wsStatus:u="connected",isStandalone:h=!1}){const y=u==="disconnected"||u==="reconnecting"||u==="offline"||u==="auth_failed",l=c.length>0,j=s.length>0||r.length>0||n.length>0||o.length>0,P=e==="machines"?"Machines":"Chats",k=h?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",g=h?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]";return t.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[t.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${k}`,children:t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:P}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(s.length>0||r.length>0)&&t.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[t.jsx(_r,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:S,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:t.jsx(Ar,{size:18})})]})]})}),t.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${g}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:y?t.jsx(Ms,{icon:t.jsx(Va,{label:"Reconnecting…"}),title:"Connecting to server",subtitle:u==="offline"?"Your device appears to be offline. Waiting for network…":u==="auth_failed"?"Session expired. Please log in again.":"Establishing connection to the server. This usually takes a moment."}):c.length===0?t.jsx(Ms,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:h?"Waiting for your daemon":"Connect your machines",subtitle:h?"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:!h&&t.jsx("div",{className:"w-full max-w-[360px] mt-4",children:t.jsx(gi,{})})}):t.jsx(us,{children:c.map((N,v)=>t.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>b(N.id),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:d(N.label)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:N.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:N.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[N.unread," new"]}):N.total>0?`${N.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:N.subtitle}),N.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[N.total," chat",N.total!==1?"s":"",N.unread>0?` · ${N.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},N.id))})}),e==="chats"&&s.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(ar,{title:"Needs attention",className:"mb-0"}),t.jsx(us,{children:s.map((N,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(or,{item:N,type:"needs_attention",getAvatarText:d,onOpenConversation:m})},N.conversation.tabKey))})]}),e==="chats"&&r.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(ar,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(us,{children:r.map((N,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(or,{item:N,type:"task_complete",getAvatarText:d,onOpenConversation:m})},N.conversation.tabKey))})]}),e==="chats"&&n.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(ar,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(us,{children:n.map((N,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(or,{item:N,type:"working",getAvatarText:d,onOpenConversation:m})},N.conversation.tabKey))})]}),e==="chats"&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[o.length>0&&t.jsx(ar,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),o.length>0?t.jsx(us,{children:o.map((N,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(or,{item:N,type:"earlier",getAvatarText:d,onOpenConversation:m})},N.conversation.tabKey))}):j?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):y?t.jsx(Ms,{icon:t.jsx(Va,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):l?t.jsx(Ms,{icon:t.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:t.jsx(Kt,{size:20})}),title:"No conversations yet",subtitle:"Your machines are available. Open a machine, wait for P2P to connect, then launch your first IDE, CLI, or ACP session."}):t.jsx(Ms,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),e==="chats"&&i.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsxs("div",{className:"mx-1 mt-4 mb-1 flex items-center justify-between gap-2 px-1 py-1 text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:[t.jsx("span",{children:"Hidden"}),t.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:p,children:"Restore all"})]}),t.jsx(us,{className:"bg-bg-secondary/25",children:i.map((N,v)=>t.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] opacity-50 saturate-0 ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(N),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-bg-primary border border-border-subtle text-text-secondary",children:d(st(N))}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:st(N)}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:is(N)}),t.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},N.tabKey))})]})]}),e==="chats"&&x&&t.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:x,"aria-label":"Start new session",children:t.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),t.jsx(yi,{section:e,onSectionChange:A})]})}function Dr(...e){const s=new Set,r=[],n=o=>{const i=typeof o=="string"?o.trim():"";if(!i)return;const c=i.toLowerCase();s.has(c)||(s.add(c),r.push(i))};for(const o of e){if(Array.isArray(o)){for(const i of o)n(i);continue}n(o)}return r}function tm(e){const s=e.trim();if(!s)return null;if(s.startsWith("~"))return s;if(/^[A-Za-z]:$/.test(s))return`${s[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(s))return`${s[0].toUpperCase()}:${s.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(s))return`${s[0].toUpperCase()}:\\${s.slice(2).replace(/[\\/]+/g,"\\")}`;const r=s.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),o=(r[2]||"").replace(/[\\/]+/g,"\\");return o?`${n}:\\${o}`:`${n}:\\`}return null}function Er(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=tm(r);if(n)return n}return"C:\\"}for(const r of s){const n=typeof r=="string"?r.trim():"";if(n)return n}return"~"}function sm(e){const s=e.replace(/[\\/]+$/,"");if(!s||s==="/"||/^[A-Za-z]:$/.test(s))return null;const r=s.includes("\\")?"\\":"/",n=s.split(/[\\/]/);return/^[A-Za-z]:$/.test(n[0]||"")?n.length<=2?`${n[0]}\\`:n.slice(0,-1).join("\\"):n.length<=2?r:n.slice(0,-1).join(r)||r}async function $r(e,s,r){const n=await e(s,"file_list_browse",{path:r});if(!(n!=null&&n.success))throw new Error((n==null?void 0:n.error)||"Could not browse folder");const o=typeof(n==null?void 0:n.path)=="string"?n.path:r,i=o.includes("\\")?"\\":"/",c=(m,f)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${f}`:m==="/"||m==="\\"?`${i}${f}`:`${m.replace(/[\\/]+$/,"")}${i}${f}`,d=Array.isArray(n==null?void 0:n.files)?n.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:c(o,m.name)})).sort((m,f)=>m.name.localeCompare(f.name)):[];return{path:o,directories:d}}function Br({title:e,description:s,currentPath:r,directories:n,busy:o=!1,error:i="",confirmLabel:c="Use this folder",onClose:d,onNavigate:m,onConfirm:f}){const[p,x]=a.useState(r);a.useEffect(()=>{x(r)},[r]);const b=sm(r),S=p.trim();return t.jsx("div",{className:"fixed inset-0 z-[110] flex items-center justify-center p-4 bg-black/60 backdrop-blur-[2px]",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:t.jsxs("div",{className:"w-full max-w-2xl max-h-[min(86vh,720px)] rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:d,"aria-label":"Close folder browser",children:t.jsx(vt,{size:16})})]}),t.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[t.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!b||o||m(b)},disabled:!b||o,children:[t.jsx(Tn,{size:15}),"Parent"]}),t.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"text",value:p,onChange:A=>x(A.target.value),onKeyDown:A=>{A.key!=="Enter"||!S||o||(A.preventDefault(),m(S))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!S||o||m(S)},disabled:!S||o,children:"Go"})]})]})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:o?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):i?t.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):n.length===0?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):t.jsx("div",{className:"p-3",children:n.map(A=>t.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>m(A.path),children:[t.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(gs,{size:17})}),t.jsxs("span",{className:"min-w-0 flex-1",children:[t.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:A.name}),t.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:A.path})]})]},A.path))})}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-4 border-t border-border-subtle bg-bg-secondary",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:d,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>f(S||r),disabled:!S&&!r||o,children:c})]})]})})}function qn({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:o,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:d="Launching…",busy:m=!1,showArgsInput:f,argsValue:p,onArgsChange:x,showModelInput:b,modelValue:S,onModelChange:A,historyProviderNode:u,onConfirm:h,onCancel:y}){const l=n==null?void 0:n.find(j=>j.key===o);return t.jsx("div",{className:"fixed inset-0 z-[110] flex items-center justify-center p-4 bg-black/60 backdrop-blur-[2px]",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:t.jsxs("div",{className:"w-full max-w-lg rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:y,"aria-label":"Close launch confirmation",children:t.jsx(vt,{size:16})})]}),t.jsxs("div",{className:"px-5 py-4 flex flex-col gap-3",children:[n&&n.length>0&&i&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),t.jsx("select",{value:o||"",onChange:j=>i(j.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:m,children:n.map(j=>t.jsx("option",{value:j.key,children:j.label},j.key))}),(l==null?void 0:l.description)&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:l.description})]}),u,r.map(j=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:j.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:j.value})]},`${j.label}:${j.value}`)),b&&A&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),t.jsx("input",{type:"text",value:S||"",onChange:j=>A(j.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:m})]}),f&&x&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),t.jsx("input",{type:"text",value:p||"",onChange:j=>x(j.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:m})]})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-4 border-t border-border-subtle bg-bg-secondary",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:y,disabled:m,children:"Cancel"}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:h,disabled:m,children:[t.jsx(_n,{size:14}),m?d:c]})]})]})})}function Ga(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function ts(e){const{machine:s,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:o=!0}=e,i=[];o&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const m of s.workspaces||[])i.push({key:`saved:${m.id}`,label:`${m.id===s.defaultWorkspaceId?"⭐ ":""}${Ga(m.path,m.label)}`,description:m.path,workspaceId:m.id,workspacePath:m.path});const c=(r==null?void 0:r.trim())||"",d=c?(s.workspaces||[]).find(m=>m.path===c):null;if(c&&!d&&i.push({key:`custom:${c}`,label:Ga(c),description:c,workspaceId:null,workspacePath:c}),n){const m=`saved:${n}`;if(i.some(f=>f.key===m))return{options:i,selectedKey:m}}return d?{options:i,selectedKey:`saved:${d.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function en(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function rm({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:o,onListSavedSessions:i}){var X,ce,Ce,Re;const c=Gs(),[d,m]=a.useState(!1),f=(((X=e.detectedIdes)==null?void 0:X.length)||0)>0,p=a.useMemo(()=>(e.workspaces||[]).map(me=>({id:me.id,path:me.path,label:me.label})),[e]),x=e.defaultWorkspaceId||null,[b,S]=a.useState(x||((ce=p[0])==null?void 0:ce.id)||""),[A,u]=a.useState(""),[h,y]=a.useState(""),[l,j]=a.useState([]),[P,k]=a.useState(!1),[g,N]=a.useState(""),[v,w]=a.useState(!1),[M,T]=a.useState(en(f,s.length,r.length)),$=a.useRef(null),[E,F]=a.useState(null),D=a.useRef("__home__"),[C,V]=a.useState("__home__"),[J,I]=a.useState(""),[R,B]=a.useState(""),[z,Z]=a.useState(""),[fe,Pe]=a.useState([]),[ke,ve]=a.useState(!1),[Q,xe]=a.useState(!1),W=a.useRef(null);a.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const ee=b==="__custom__"?A.trim():((Ce=p.find(me=>me.id===b))==null?void 0:Ce.path)||"",ne=b==="__custom__"&&!!ee&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),oe=b!=="__custom__"&&((Re=p.find(me=>me.id===b))==null?void 0:Re.path)||"",he=a.useMemo(()=>(e.recentLaunches||[]).map(me=>me.workspace),[e]),te=a.useCallback(async me=>{k(!0),N("");try{const We=await o(me);y(We.path),u(We.path),j(We.directories)}catch(We){N(We instanceof Error?We.message:"Could not load folder")}finally{k(!1)}},[o]),de=a.useCallback(()=>{var We;S("__custom__"),w(!0);const me=Er(e.platform,Dr(A.trim(),oe,he,e.defaultWorkspacePath,(We=p.find(Be=>Be.id===x))==null?void 0:We.path,p.map(Be=>Be.path)));te(me)},[A,x,te,he,oe,e.platform,p]),se=a.useCallback(me=>{if(me!=null&&me.workspaceId){S(me.workspaceId),u("");return}if(me!=null&&me.workspacePath){S("__custom__"),u(me.workspacePath);return}S(""),u("")},[]),pe=a.useCallback(me=>{if(S(me),me==="__custom__"){de();return}u("")},[de]),ae=a.useCallback(me=>{S("__custom__"),u(me)},[]),Ne=a.useCallback((me,We)=>{$.current=We,D.current=me.selectedWorkspaceKey||"__home__",V(me.selectedWorkspaceKey||"__home__"),I(me.initialArgs||""),B(me.initialModel||""),Z(""),Pe([]),F(me),me.providerType&&i&&(ve(!0),i(me.providerType).then(Be=>Pe(Be||[])).catch(Be=>console.warn("Failed to load saved sessions",Be)).finally(()=>ve(!1)))},[i]),ge=a.useCallback(()=>{$.current&&(xe(!0),$.current().finally(()=>{$.current=null,xe(!1),F(null)}))},[]),_=a.useCallback(()=>{$.current=null,F(null)},[]),ue=a.useCallback(me=>{D.current=me,V(me)},[]);return a.useEffect(()=>{var me;W.current!==e.id&&(W.current=e.id,S(x||((me=p[0])==null?void 0:me.id)||"__custom__"),u(""),y(""),j([]),N(""),w(!1),T(en(f,s.length,r.length)))},[r.length,s.length,x,f,e.id,p]),a.useEffect(()=>{var me;b!=="__custom__"&&(b&&p.some(We=>We.id===b)||S(x||((me=p[0])==null?void 0:me.id)||"__custom__"))},[x,b,p]),a.useEffect(()=>{M==="ide"&&f||M==="cli"&&s.length>0||M==="acp"&&r.length>0||T(en(f,s.length,r.length))},[M,r.length,s.length,f]),{showAllRecent:d,setShowAllRecent:m,hasIdeOptions:f,workspaceRows:p,defaultWorkspaceId:x,workspaceChoice:b,customWorkspacePath:A,browseCurrentPath:h,browseDirectories:l,browseBusy:P,browseError:g,browseDialogOpen:v,activeLauncherKind:M,launchConfirm:E,launchConfirmWorkspaceKeyRef:D,launchConfirmWorkspaceKey:C,launchConfirmArgs:J,launchConfirmModel:R,launchConfirmResumeId:z,launchConfirmSavedSessions:fe,launchConfirmSessionsLoading:ke,launchConfirmBusy:Q,resolvedWorkspacePath:ee,canCreateMissingWorkspace:ne,openBrowseDialog:de,loadBrowsePath:te,handleWorkspaceChoiceChange:pe,chooseCustomWorkspacePath:ae,setCustomWorkspacePath:u,setBrowseDialogOpen:w,setActiveLauncherKind:T,openLaunchConfirm:Ne,handleConfirmLaunch:ge,closeLaunchConfirm:_,setWorkspaceSelectionFromOption:se,setLaunchConfirmWorkspaceKeyAndSync:ue,setLaunchConfirmArgs:I,setLaunchConfirmModel:B,setLaunchConfirmResumeId:Z}}function nm({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:o,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:d,isStandalone:m,section:f,showBottomNav:p,onBack:x,onSectionChange:b,onOpenConversation:S,onOpenRecent:A,onOpenMachineDetails:u,onMachineUpgrade:h,onLaunchDetectedIde:y,onAddWorkspace:l,onBrowseDirectory:j,onLaunchWorkspaceProvider:P,onListSavedSessions:k}){const g=C=>C==="ide"?"IDE":C==="cli"?"CLI":"ACP",N=r.slice(0,4),v=s.slice(0,3),w=rm({selectedMachineEntry:e,cliProviders:n,acpProviders:o,machineAction:d,onBrowseDirectory:j,onListSavedSessions:k}),M=a.useMemo(()=>N.map(C=>({key:`recent-launch:${C.id}`,primary:C.label,secondary:`${g(C.kind)}${C.subtitle?` · ${C.subtitle}`:""}`,onClick:()=>{const{options:V,selectedKey:J}=ts({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspacePath:C.workspace});w.openLaunchConfirm({title:C.kind==="ide"?Yt("restart-ide",C.label):C.providerSessionId?qo(C.label):Yt("start-fresh",C.label),description:C.kind==="ide"?Xt("restart-ide"):C.providerSessionId?Yo():Xt("start-fresh"),confirmLabel:C.kind==="ide"?Jt("restart-ide"):C.providerSessionId?Nr(!0):Jt("start-fresh"),busyLabel:C.kind==="ide"?Zt("restart-ide"):C.providerSessionId?Wn(!0):Zt("start-fresh"),workspaceOptions:V,selectedWorkspaceKey:J,details:[{label:"Mode",value:g(C.kind)},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]},async()=>{const I=V.find(R=>R.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(I),await A({...C,workspace:(I==null?void 0:I.workspacePath)??null})})}})),[w,A,N]),T=a.useMemo(()=>v.map(C=>({key:`recent-chat:${C.conversation.tabKey}`,primary:st(C.conversation),secondary:hd(C.conversation,{timestampLabel:C.timestamp?Co(C.timestamp):null}),unread:C.unread,onClick:()=>S(C.conversation)})),[S,v]),$=w.showAllRecent?M:M.slice(0,4),E=M.length>0,F=T.length>0,D=m?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:`flex items-center justify-between gap-3 ${D} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:x,type:"button","aria-label":"Back",children:t.jsx(Tn,{size:18})}),t.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:jt(e,{fallbackId:e.id})}),t.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[F&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:T.map(C=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${C.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:C.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))})]}),E&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:$.map(C=>t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:C.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))}),M.length>4&&t.jsx("div",{className:"flex justify-center px-4 pt-2",children:t.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>w.setShowAllRecent(C=>!C),children:w.showAllRecent?"Show fewer":`Show ${M.length-4} more`})})]}),(w.hasIdeOptions||n.length>0||o.length>0)&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:t.jsxs("div",{className:"flex flex-col gap-2.5 w-full p-3.5 rounded-2xl border border-border-default/80 bg-surface-primary/90",children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),t.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),t.jsx("select",{value:w.workspaceChoice,onChange:C=>w.handleWorkspaceChoiceChange(C.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:w.workspaceRows.length>0?t.jsxs(t.Fragment,{children:[w.workspaceRows.map(C=>t.jsxs("option",{value:C.id,children:[C.id===w.defaultWorkspaceId?"⭐ ":"",Pr(C.path,C.label)||C.path]},C.id)),t.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):t.jsx("option",{value:"__custom__",children:"Select workspace…"})}),w.workspaceChoice==="__custom__"&&t.jsxs("div",{className:"flex flex-col gap-2.5",children:[t.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start gap-3",children:[t.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(gs,{size:17})}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),t.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:w.resolvedWorkspacePath||w.browseCurrentPath||"No folder selected yet."})]})]})}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-secondary text-[12px] font-bold",onClick:w.openBrowseDialog,children:"Select workspace…"}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-accent-primary/30 bg-accent-primary/10 text-text-primary text-[12px] font-bold disabled:opacity-40",onClick:()=>{w.resolvedWorkspacePath&&l(w.resolvedWorkspacePath)},disabled:!w.resolvedWorkspacePath||w.browseBusy,children:"Save as workspace"})]})]}),w.resolvedWorkspacePath&&t.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:w.resolvedWorkspacePath})]})}),t.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[w.hasIdeOptions&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${w.activeLauncherKind==="ide"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>w.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${w.activeLauncherKind==="cli"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>w.setActiveLauncherKind("cli"),children:"CLI"}),o.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${w.activeLauncherKind==="acp"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>w.setActiveLauncherKind("acp"),children:"ACP"})]}),w.activeLauncherKind&&t.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[t.jsx("div",{className:"text-xs font-bold text-text-secondary",children:w.activeLauncherKind==="ide"?"Choose an IDE":w.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),t.jsx("div",{className:"grid grid-cols-1 gap-2",children:w.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(C=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const{options:V,selectedKey:J}=ts({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspaceId:w.workspaceChoice!=="__custom__"?w.workspaceChoice:null,currentWorkspacePath:w.resolvedWorkspacePath});w.openLaunchConfirm({title:`Launch ${C.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:V,selectedWorkspaceKey:J,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:C.name}]},async()=>{const I=V.find(R=>R.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(I),y(C.type,{workspacePath:(I==null?void 0:I.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:C.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:w.resolvedWorkspacePath||"Use selected workspace"})]},C.type)):(w.activeLauncherKind==="cli"?n:o).map(C=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const V=w.activeLauncherKind==="cli"?"cli":"acp",{options:J,selectedKey:I}=ts({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspaceId:w.workspaceChoice!=="__custom__"?w.workspaceChoice:null,currentWorkspacePath:w.resolvedWorkspacePath});w.openLaunchConfirm({title:`Launch ${C.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${V.toUpperCase()}`,workspaceOptions:J,selectedWorkspaceKey:I,details:[{label:"Mode",value:V.toUpperCase()},{label:"Provider",value:C.displayName}],showArgsInput:!0,showModelInput:V==="acp",initialArgs:"",initialModel:"",providerType:C.type},async()=>{const R=J.find(B=>B.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(R),P(V,C.type,{workspaceId:(R==null?void 0:R.workspaceId)??null,workspacePath:(R==null?void 0:R.workspacePath)??null,args:w.launchConfirmArgs,model:w.launchConfirmModel,resumeSessionId:w.launchConfirmResumeId||null})})},children:[t.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[C.icon?`${C.icon} `:"",C.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:w.resolvedWorkspacePath||"Use selected workspace"})]},C.type))})]}),d.message&&t.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${d.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[d.message,w.canCreateMissingWorkspace&&t.jsx("div",{className:"mt-2",children:t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[34px] px-4 rounded-lg bg-surface-primary text-text-primary font-bold text-xs",onClick:()=>l(w.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[i&&t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:h,children:[t.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:u,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),w.browseDialogOpen&&t.jsx(Br,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:w.browseCurrentPath,directories:w.browseDirectories,busy:w.browseBusy,error:w.browseError,confirmLabel:"Use this folder",onClose:()=>w.setBrowseDialogOpen(!1),onNavigate:C=>{w.loadBrowsePath(C)},onConfirm:C=>{w.chooseCustomWorkspacePath(C),w.setBrowseDialogOpen(!1)}}),w.launchConfirm&&t.jsx(qn,{title:w.launchConfirm.title,description:w.launchConfirm.description,details:w.launchConfirm.details,workspaceOptions:w.launchConfirm.workspaceOptions,selectedWorkspaceKey:w.launchConfirmWorkspaceKey,onWorkspaceChange:w.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:w.launchConfirm.providerType?Nr(!!w.launchConfirmResumeId):w.launchConfirm.confirmLabel,busyLabel:w.launchConfirm.providerType?void 0:w.launchConfirm.busyLabel,busy:w.launchConfirmBusy,showArgsInput:w.launchConfirm.showArgsInput,argsValue:w.launchConfirmArgs,onArgsChange:w.setLaunchConfirmArgs,showModelInput:w.launchConfirm.showModelInput,modelValue:w.launchConfirmModel,onModelChange:w.setLaunchConfirmModel,historyProviderNode:w.launchConfirm.providerType&&(w.launchConfirmSessionsLoading||w.launchConfirmSavedSessions.length>0)&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),w.launchConfirmSessionsLoading&&t.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),t.jsxs("select",{value:w.launchConfirmResumeId,onChange:C=>w.setLaunchConfirmResumeId(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"",children:Vo()}),w.launchConfirmSavedSessions.map(C=>t.jsxs("option",{value:C.providerSessionId,disabled:!C.canResume,children:[C.title||C.providerSessionId," ",C.canResume?"":"(workspace missing)"]},C.providerSessionId))]})]}),onConfirm:w.handleConfirmLaunch,onCancel:w.closeLaunchConfirm}),p&&t.jsx(yi,{section:f,onSectionChange:b})]})}function vi(e){var r;const s=((r=e.p2p)==null?void 0:r.state)||"";return s==="connected"?"Connected":s==="connecting"||s==="new"||s==="checking"?"Connecting":"Offline"}function am(e,s){if(!e)return[];const r=e.recentLaunches||[];return r.length>0?r.map(n=>({id:n.id,label:n.title||n.providerName||n.providerType,kind:n.kind,providerType:n.providerType,providerSessionId:n.providerSessionId,subtitle:n.currentModel||n.workspace||void 0,workspace:n.workspace,currentModel:n.currentModel})):s.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var i,c,d,m,f;const o=Hs(n)?"cli":xs(n)?"acp":"ide";return{id:`${o}:${n.type}:${n.workspace||""}`,label:((i=n.activeChat)==null?void 0:i.title)||(Hs(n)?n.cliName||n.type:xs(n)&&n.cliName||n.type),kind:o,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:xs(n)?n.currentModel||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,currentModel:n.currentModel,timestamp:((f=(m=(d=(c=n.activeChat)==null?void 0:c.messages)==null?void 0:d.at)==null?void 0:m.call(d,-1))==null?void 0:f.timestamp)||0}}).sort((n,o)=>o.timestamp-n.timestamp).map(({timestamp:n,...o})=>o)}function om(e,s){const r=new Map;for(const n of s){const o=Ut(n.conversation),i=r.get(o);i?i.push(n):r.set(o,[n])}return e.map(n=>{const o=r.get(n.id)||[],i=[...o].sort((x,b)=>b.timestamp-x.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,d=xn(n),m=o.filter(x=>x.unread||x.requiresAction).length,f=vi(n),p=[n.platform||"machine",f].filter(Boolean);return{id:n.id,label:jt(n,{fallbackId:n.id}),subtitle:p.join(" · "),unread:m,total:o.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:d,preview:c?bd(c):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((n,o)=>{const i=n.latestTimestamp||n.fallbackActivityAt||0,c=o.latestTimestamp||o.fallbackActivityAt||0;return c!==i?c-i:n.label.localeCompare(o.label)})}function ir(e,s){var r;if(!(typeof window>"u"))try{if(!(!!((r=import.meta.env)!=null&&r.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,s)}catch{}}function im({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:o,screen:i,liveSessionInboxState:c,sendDaemonCommand:d,requestedActiveTabKey:m,onRequestedActiveTabConsumed:f,requestedMachineId:p,onRequestedMachineConsumed:x,requestedMobileSection:b,onRequestedMobileSectionConsumed:S,setSelectedTabKey:A,setScreen:u,setSelectedMachineId:h,setSection:y,setMachineBackTarget:l,resetMachineAction:j}){const P=a.useRef(null),k=a.useCallback(g=>{if(!(g!=null&&g.sessionId))return;const N=Ws(g,c),v=Math.max(Date.now(),Ht(g),N.lastUpdated||0);ir("mark_read:start",{tabKey:g.tabKey,sessionId:g.sessionId,displayPrimary:st(g),inboxBucket:N.inboxBucket,unread:N.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:Ht(g),readAt:v}),d(Ut(g)||g.routeId,"mark_session_seen",{sessionId:g.sessionId,seenAt:v}).then(w=>{ir("mark_read:result",{tabKey:g.tabKey,sessionId:g.sessionId,result:w})}).catch(w=>{ir("mark_read:error",{tabKey:g.tabKey,sessionId:g.sessionId,error:w instanceof Error?w.message:String(w)})})},[c,d]);return a.useEffect(()=>{var N;if(!n){u("inbox"),A(((N=e[0])==null?void 0:N.tabKey)||null),P.current=null;return}if(i!=="chat"){P.current=null;return}const g=`${n.tabKey}:${n.sessionId||""}`;P.current!==g&&(P.current=g,k(n))},[e,k,i,n,u,A]),a.useEffect(()=>{if(!m)return;const g=e.find(N=>N.tabKey===m);g&&(A(g.tabKey),u("chat"),f==null||f())},[e,f,m,u,A]),a.useEffect(()=>{if(!p)return;const g=s.find(N=>N.id===p);g&&(h(g.id),j(),y("machines"),l("inbox"),u("machine"),x==null||x())},[s,x,p,j,l,u,y,h]),a.useEffect(()=>{b&&(y(b),u("inbox"),S==null||S())},[S,b,u,y]),a.useEffect(()=>{const g=r.filter(N=>N.inboxBucket==="task_complete"||N.unread);g.length!==0&&ir("inbox_state",{screen:i,selectedTabKey:o,items:g.map(N=>{const v=Ws(N.conversation,c);return{liveState:v,tabKey:N.conversation.tabKey,sessionId:N.conversation.sessionId,displayPrimary:st(N.conversation),serverBucket:v.inboxBucket,computedBucket:N.inboxBucket,serverUnread:v.unread,computedUnread:N.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,activityAt:Ht(N.conversation)}})})},[r,c,i,o]),{markConversationRead:k}}function cm(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function qa(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function lm(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function dm({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[o,i]=a.useState("idle"),[c,d]=a.useState(""),[m,f]=a.useState(null),p=a.useCallback(()=>{i("idle"),d(""),f(null)},[]),x=a.useCallback(async(l,j,P)=>{var k;try{i("loading"),d(`Launching ${j}…`);const g={ideType:j,enableCdp:!0};(k=P==null?void 0:P.workspacePath)!=null&&k.trim()&&(g.workspace=P.workspacePath.trim()),await e(l,"launch_ide",g),i("done"),d(`${j} launch requested`)}catch(g){i("error"),d(g instanceof Error?g.message:"Launch IDE failed"),console.error("Launch IDE failed",g)}},[e]),b=a.useCallback(async(l,j,P)=>{if(j.trim())try{i("loading"),d(P!=null&&P.createIfMissing?"Creating folder…":"Saving workspace…");const k=await e(l,"workspace_add",{path:j.trim(),createIfMissing:(P==null?void 0:P.createIfMissing)===!0});if(k!=null&&k.success){i("done"),d(P!=null&&P.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),d((k==null?void 0:k.error)||"Could not save workspace")}catch(k){i("error"),d(k instanceof Error?k.message:"Could not save workspace")}},[e]),S=a.useCallback(async l=>{var j,P,k,g,N,v;try{i("loading"),d("Starting daemon upgrade…");const w=await e(l,"daemon_upgrade",{});if((j=w==null?void 0:w.result)!=null&&j.alreadyLatest){i("done"),d(`Already on v${((P=w==null?void 0:w.result)==null?void 0:P.version)||"latest"}.`);return}if((k=w==null?void 0:w.result)!=null&&k.upgraded||(g=w==null?void 0:w.result)!=null&&g.success){i("done"),d(`Upgrade to v${((N=w==null?void 0:w.result)==null?void 0:N.version)||"latest"} started. Daemon is restarting…`);return}i("error"),d(((v=w==null?void 0:w.result)==null?void 0:v.error)||"Upgrade failed")}catch(w){i("error"),d(w instanceof Error?w.message:"Upgrade failed")}},[e]),A=a.useCallback(async(l,j,P,k)=>{var v,w,M;const g=Date.now(),N={machineId:l,kind:j,providerType:P,workspaceId:(k==null?void 0:k.workspaceId)||null,workspacePath:(k==null?void 0:k.workspacePath)||null,resumeSessionId:(k==null?void 0:k.resumeSessionId)||null,startedAt:g};try{i("loading"),d(`Launching ${P}…`),f(N);const T={cliType:P};(v=k==null?void 0:k.workspacePath)!=null&&v.trim()?T.dir=k.workspacePath.trim():k!=null&&k.workspaceId&&(T.workspaceId=k.workspaceId),k!=null&&k.resumeSessionId&&(T.resumeSessionId=k.resumeSessionId),(w=k==null?void 0:k.args)!=null&&w.trim()&&(T.cliArgs=k.args.trim().split(/\s+/).filter(Boolean)),(M=k==null?void 0:k.model)!=null&&M.trim()&&(T.initialModel=k.model.trim());const $=await e(l,"launch_cli",T),E=($==null?void 0:$.result)||$,F=(E==null?void 0:E.sessionId)||(E==null?void 0:E.id);if($!=null&&$.success&&F){f(null),i("done"),d(`${P} launched`),s(`/dashboard?activeTab=${encodeURIComponent(F)}`);return}if($!=null&&$.success){i("loading"),d(`${P} launch requested — waiting for session…`);return}f(null),i("error"),d(($==null?void 0:$.error)||(E==null?void 0:E.error)||`Could not launch ${j.toUpperCase()} workspace`)}catch(T){if(lm(T)){i("loading"),d(`${P} launch requested — waiting for session…`);return}f(null),i("error"),d(T instanceof Error?T.message:`Could not launch ${j.toUpperCase()} workspace`)}},[s,e]),u=a.useCallback(async(l,j)=>{try{const P=await e(l,"list_saved_sessions",{providerType:j,kind:"cli",limit:30}),k=(P==null?void 0:P.result)??P;return Array.isArray(k==null?void 0:k.sessions)?k.sessions:[]}catch(P){return console.error("Failed to list saved sessions on mobile:",P),[]}},[e]),h=a.useCallback(async(l,j)=>$r(e,l,j),[e]);a.useEffect(()=>{var k;if(!m)return;const l=qa(m.workspacePath),j=r.find(g=>{var $,E,F,D;if(!g||g.type==="adhdev-daemon"||cm(g.daemonId||g.id)!==m.machineId||(g.transport==="acp"?"acp":g.transport==="pty"?"cli":null)!==m.kind||String(g.agentType||g.type||"")!==m.providerType)return!1;const M=String(g.providerSessionId||"");if(m.resumeSessionId&&M)return M===m.resumeSessionId;if(l){const C=qa(g.workspace||g.runtimeWorkspaceLabel);return C?C===l:!1}return Number(g.lastUpdated||g._lastUpdate||g.timestamp||((D=(F=(E=($=g.activeChat)==null?void 0:$.messages)==null?void 0:E.at)==null?void 0:F.call(E,-1))==null?void 0:D.timestamp)||0)>=m.startedAt-5e3});if(!j)return;const P=typeof j.sessionId=="string"&&j.sessionId?j.sessionId:typeof j.instanceId=="string"&&j.instanceId?j.instanceId:(k=n.find(g=>g.routeId===j.id))==null?void 0:k.sessionId;P&&(f(null),i("done"),d(`${m.providerType} launched`),s(`/dashboard?activeTab=${encodeURIComponent(P)}`))},[n,r,s,m]),a.useEffect(()=>{if(!m)return;const l=window.setTimeout(()=>{f(j=>!j||j.startedAt!==m.startedAt?j:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(l)},[m]);const y=a.useCallback(async(l,j)=>{if(j.kind==="ide"&&j.providerType){await x(l,j.providerType,{workspacePath:j.workspace||null});return}(j.kind==="cli"||j.kind==="acp")&&j.providerType&&await A(l,j.kind,j.providerType,{workspacePath:j.workspace||null,resumeSessionId:j.providerSessionId||null})},[x,A]);return{machineAction:{state:o,message:c},resetMachineAction:p,handleLaunchDetectedIde:x,handleAddWorkspace:b,handleMachineUpgrade:S,handleLaunchWorkspaceProvider:A,handleListSavedSessions:u,handleBrowseDirectory:h,handleOpenRecent:y}}function um({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:o,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:d,setSection:m,setMachineBackTarget:f}){const p=a.useCallback(y=>{i(y.tabKey),c("chat"),n(y)},[n,c,i]),x=a.useCallback(y=>{const l=e.find(j=>j.routeId===y.routeId&&j.streamSource==="native");l&&(i(l.tabKey),c("chat"),n(l))},[e,n,c,i]),b=a.useCallback(()=>{n(s),c("inbox")},[n,s,c]),S=a.useCallback((y,l="inbox")=>{d(y),o(),m("machines"),f(l),c("machine")},[o,f,c,m,d]),A=a.useCallback(y=>{const l=Ut(y);l&&S(l,"chat")},[S]),u=a.useCallback(()=>{o(),c(r)},[r,o,c]),h=a.useCallback(y=>{m(y),c("inbox")},[c,m]);return{openConversation:p,openNativeConversation:x,backFromConversation:b,openMachine:S,openConversationMachine:A,backFromMachine:u,changeMachineSection:h}}function mm(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function pm(e){const s=e instanceof Error?e.message:String(e||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function cr(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function fm({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:d,userName:m,requestedActiveTabKey:f,onRequestedActiveTabConsumed:p,requestedMachineId:x,onRequestedMachineConsumed:b,requestedMobileSection:S,onRequestedMobileSectionConsumed:A,onOpenHistory:u,onOpenRemote:h,onStopCli:y,wsStatus:l,isConnected:j,onShowHiddenConversation:P,onShowAllHiddenConversations:k,onHideConversation:g,onOpenNewSession:N}){const[v,w]=a.useState(()=>{var X;return((X=e[0])==null?void 0:X.tabKey)||null}),[M,T]=a.useState(()=>e[0]?"chat":"inbox"),[$,E]=a.useState("chats"),[F,D]=a.useState(null),[C,V]=a.useState("inbox"),J=ws(),I="0.8.56",R=a.useMemo(()=>e.find(X=>X.tabKey===v)||e[0]||null,[e,v]),B=a.useMemo(()=>R?r.find(X=>X.id===R.routeId):void 0,[r,R]),z=a.useMemo(()=>!R||Ve(R)||!Ye(R)?null:vs(R),[R]),Z=a.useMemo(()=>r.filter(X=>X.type==="adhdev-daemon").sort(Ln),[r]),fe=a.useMemo(()=>Z.find(X=>X.id===F)||null,[Z,F]),Pe=a.useMemo(()=>Fs(r),[r]),ke=Lr({sendDaemonCommand:o,activeConv:R||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:d}),ve=dm({sendDaemonCommand:o,navigate:J,ides:r,conversations:e}),Q=a.useMemo(()=>e.map(X=>{const ce=M==="chat"&&(R==null?void 0:R.tabKey)===X.tabKey,Ce=Os(X,Pe,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ce}),Re=Ht(X),me=Oo(X);return{conversation:X,timestamp:Re,preview:me,unread:Ce.unread,requiresAction:Ce.requiresAction,isWorking:Ce.isWorking,inboxBucket:Ce.inboxBucket}}),[e,Pe,M,R]),{markConversationRead:xe}=im({conversations:e,machineEntries:Z,items:Q,selectedConversation:R,selectedTabKey:v,screen:M,liveSessionInboxState:Pe,sendDaemonCommand:o,requestedActiveTabKey:f,onRequestedActiveTabConsumed:p,requestedMachineId:x,onRequestedMachineConsumed:b,requestedMobileSection:S,onRequestedMobileSectionConsumed:A,setSelectedTabKey:w,setScreen:T,setSelectedMachineId:D,setSection:E,setMachineBackTarget:V,resetMachineAction:ve.resetMachineAction}),W=um({conversations:e,selectedConversation:R,machineBackTarget:C,markConversationRead:xe,resetMachineAction:ve.resetMachineAction,setSelectedTabKey:w,setScreen:T,setSelectedMachineId:D,setSection:E,setMachineBackTarget:V}),ee=a.useMemo(()=>cr(Q.filter(X=>X.requiresAction)),[Q]),ne=a.useMemo(()=>cr(Q.filter(X=>X.unread&&!X.requiresAction)),[Q]),oe=a.useMemo(()=>cr(Q.filter(X=>!X.unread&&!X.requiresAction&&X.isWorking)),[Q]),he=a.useMemo(()=>cr(Q.filter(X=>!X.unread&&!X.requiresAction&&!X.isWorking)),[Q]),te=a.useMemo(()=>fe?Q.filter(X=>Ut(X.conversation)===fe.id):[],[Q,fe]),de=a.useMemo(()=>am(fe,r),[r,fe]),se=(fe==null?void 0:fe.version)||null,pe=!!fe&&!!se&&!0&&se!==I,ae=a.useMemo(()=>(fe==null?void 0:fe.availableProviders)||[],[fe]),Ne=a.useMemo(()=>ae.filter(X=>X.category==="cli"&&X.installed!==!1).map(X=>({type:X.type,displayName:X.displayName||X.type,icon:X.icon})),[ae]),ge=a.useMemo(()=>ae.filter(X=>X.category==="acp"&&X.installed!==!1).map(X=>({type:X.type,displayName:X.displayName||X.type,icon:X.icon})),[ae]),_=a.useMemo(()=>om(Z,Q),[Q,Z]),ue=a.useCallback(async X=>{fe&&await ve.handleOpenRecent(fe.id,X)},[ve,fe]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:M==="chat"&&R?t.jsx(Zu,{selectedConversation:R,isAcp:Ve(R),isStandalone:d,selectedIdeEntry:B,actionLogs:n,userName:m,isSendingChat:ke.isSendingChat,isFocusingAgent:ke.isFocusingAgent,handleModalButton:ke.handleModalButton,handleRelaunch:ke.handleRelaunch,onBack:W.backFromConversation,onOpenNativeConversation:W.openNativeConversation,onOpenMachine:W.openConversationMachine,onHideConversation:g,onOpenHistory:u,onOpenRemote:h,onStopCli:y,cliViewMode:z,onSetCliViewMode:async X=>{if(R&&z!==X)try{await o(Ut(R)||R.routeId,"set_cli_view_mode",{targetSessionId:R.sessionId,cliType:wt(R),mode:X})}catch(ce){pm(ce)?console.warn("Skipped CLI view mode switch:",ce instanceof Error?ce.message:String(ce)):console.error("Failed to switch CLI view mode:",ce)}},handleSendChat:ke.handleSendChat,handleFocusAgent:ke.handleFocusAgent}):M==="machine"&&fe?t.jsx(nm,{selectedMachineEntry:fe,selectedMachineConversations:te,selectedMachineRecentLaunches:de,cliProviders:Ne,acpProviders:ge,selectedMachineNeedsUpgrade:pe,appVersion:I,machineAction:ve.machineAction,isStandalone:d,section:$,showBottomNav:C==="inbox",onBack:W.backFromMachine,onSectionChange:W.changeMachineSection,onOpenConversation:W.openConversation,onOpenRecent:ue,onOpenMachineDetails:()=>J(`/machines/${fe.id}`),onMachineUpgrade:()=>ve.handleMachineUpgrade(fe.id),onLaunchDetectedIde:(X,ce)=>ve.handleLaunchDetectedIde(fe.id,X,ce),onAddWorkspace:(X,ce)=>ve.handleAddWorkspace(fe.id,X,ce),onBrowseDirectory:X=>ve.handleBrowseDirectory(fe.id,X),onLaunchWorkspaceProvider:(X,ce,Ce)=>ve.handleLaunchWorkspaceProvider(fe.id,X,ce,Ce),onListSavedSessions:X=>ve.handleListSavedSessions(fe.id,X)}):t.jsx(em,{section:$,attentionItems:ee,unreadItems:ne,workingItems:oe,completedItems:he,hiddenConversations:s,machineCards:_,getAvatarText:mm,onOpenConversation:W.openConversation,onShowConversation:P,onShowAllHidden:k,onOpenNewSession:N,onOpenMachine:W.openMachine,onOpenSettings:()=>J("/settings"),onSectionChange:E,wsStatus:l,isConnected:j,isStandalone:d})})}function tn(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function xm({conversations:e,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:o,onClearPreviewOrder:i}){const c=a.useRef(0),[d,m]=a.useState(!1),[f,p]=a.useState(null),x=a.useCallback(()=>{c.current=0,m(!1),p(null)},[]);a.useEffect(()=>(window.addEventListener("dragend",x),window.addEventListener("drop",x),()=>{window.removeEventListener("dragend",x),window.removeEventListener("drop",x)}),[x]);const b=a.useCallback(h=>{h.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,m(!0))},[]),S=a.useCallback(h=>{if(!h.dataTransfer.types.includes("text/tab-key"))return;if(h.preventDefault(),!tn(s,r)){p("merge");return}const y=h.currentTarget.getBoundingClientRect(),l=h.clientX-y.left,j=y.width/3;l<j?p("split-left"):l>j*2?p("split-right"):p("merge")},[s,r]),A=a.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,m(!1),p(null))},[]),u=a.useCallback(h=>{c.current=0,m(!1);const y=h.dataTransfer.getData("text/tab-key"),l=y?e.some(P=>P.tabKey===y):!1,j=f;if(p(null),i(),!!y){if(h.preventDefault(),j==="split-left"&&tn(s,r)){r==null||r(y,"split-left");return}if(j==="split-right"&&tn(s,r)){r==null||r(y,"split-right");return}if(l){o(y);return}n==null||n(y)}},[e,f,s,r,n,o,i]);return{dragOver:d,dropAction:f,resetDragState:x,handleDragEnter:b,handleDragOver:S,handleDragLeave:A,handleDrop:u}}function hm(e,s){const r=new Set(s.map(i=>i.tabKey)),n=e.filter(i=>r.has(i)),o=s.filter(i=>!e.includes(i.tabKey)).map(i=>i.tabKey);return[...n,...o]}function bm({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:o}){const[i,c]=a.useState(s??null),[d,m]=a.useState(r??[]),[f,p]=a.useState(null),x=a.useRef(null),b=a.useRef(null),S=a.useRef(n),A=a.useRef(o);a.useEffect(()=>{S.current=n},[n]),a.useEffect(()=>{A.current=o},[o]),a.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),a.useEffect(()=>{m(N=>{const v=hm(N,e);return v.length===N.length&&v.every((w,M)=>w===N[M])?N:v})},[e]);const u=a.useMemo(()=>{const N=f??d;if(N.length===0)return e;const v=new Map(N.map((w,M)=>[w,M]));return[...e].sort((w,M)=>{const T=v.get(w.tabKey)??999,$=v.get(M.tabKey)??999;return T-$})},[e,f,d]);a.useEffect(()=>{var v,w;if(u.length===0){i!==null&&(c(null),(v=S.current)==null||v.call(S,null));return}if(i&&u.some(M=>M.tabKey===i))return;const N=u[0].tabKey;N!==i&&(c(N),(w=S.current)==null||w.call(S,N))},[u,i]);const h=a.useMemo(()=>u.find(N=>N.tabKey===i),[u,i]),y=a.useCallback(N=>{var v;c(N),(v=S.current)==null||v.call(S,N)},[]),l=a.useCallback((N,v,w)=>{m(M=>{var F;const T=M.filter(D=>D!==N),$=T.indexOf(v);if($<0)return M;const E=w==="left"?$:$+1;return T.splice(E,0,N),(F=A.current)==null||F.call(A,T),T}),p(null)},[]),j=a.useCallback((N,v,w)=>{const T=(d.length>0?d:e.map(F=>F.tabKey)).filter(F=>F!==N),$=T.indexOf(v);if($<0)return;const E=w==="left"?$:$+1;T.splice(E,0,N),x.current=T,p(T)},[d,e]),P=a.useCallback(()=>{var v;const N=x.current;N&&(m(N),(v=A.current)==null||v.call(A,N))},[]),k=a.useCallback(()=>{x.current=null,p(null)},[]),g=a.useCallback(N=>{m(v=>{var M;const w=v.filter(T=>T!==N);return w.push(N),(M=A.current)==null||M.call(A,w),w})},[]);return{activeTabId:i,activeConv:h,sortedConversations:u,previewOrderRef:x,draggingTabRef:b,selectTab:y,handleTabReorder:l,updatePreviewOrder:j,commitPreviewOrder:P,clearPreviewOrder:k,moveTabToEnd:g,setDraggingTabKey:N=>{b.current=N}}}function gm({dropAction:e,canSplit:s}){return t.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[t.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-left"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:s?1:.45},children:t.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Left"})}),t.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:t.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Move Here"})}),t.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-right"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:s?1:.45},children:t.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Right"})})]})}function Yn({conversationsCount:e,isSplitMode:s,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:o=!1}){if(o)return t.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const i=!r&&!n,c=r?"Waiting for your daemon":n?"No conversations yet":"Connect your machines",d=r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":n?"Your machines are connected. Open a machine, choose a workspace, then launch an IDE, CLI, or ACP session.":"Install ADHDev on a machine, sign in, and it will show up here.";return e===0&&!s?t.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[t.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),t.jsxs("div",{className:"text-center max-w-lg",children:[t.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:c}),t.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:d}),i&&t.jsx(gi,{}),i&&t.jsx("div",{className:"mt-8",children:t.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"📚 Read the documentation →"})})]})]}):t.jsx("div",{className:"text-sm text-text-muted opacity-50",children:s?"Move a tab here to view":"No active agent"})}const wi="adhdev-tab-shortcuts";function ji(){try{return JSON.parse(localStorage.getItem(wi)||"{}")}catch{return{}}}function ki({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const o=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=a.useState(()=>ji()),[d,m]=a.useState(null),f=a.useCallback(x=>{const b=[];return x.metaKey&&b.push(o?"⌘":"Meta"),x.ctrlKey&&b.push("Ctrl"),x.altKey&&b.push(o?"⌥":"Alt"),x.shiftKey&&b.push(o?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(x.key)?null:(b.push(x.key.length===1?x.key.toUpperCase():x.key),b.join("+"))},[o]),p=a.useCallback(x=>{c(x);try{localStorage.setItem(wi,JSON.stringify(x))}catch{}},[]);return a.useEffect(()=>{if(!e||!d)return;const x=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){m(null);return}const S=f(b);if(!S)return;const A={...i};for(const[u,h]of Object.entries(A))h===S&&delete A[u];A[d]=S,p(A),m(null)};return window.addEventListener("keydown",x,!0),()=>window.removeEventListener("keydown",x,!0)},[e,d,i,p,f]),a.useEffect(()=>{if(!e)return;const x=b=>{if(!(!b.ctrlKey&&!b.metaKey&&!b.altKey)){for(const[S,A]of Object.entries(i))if(s.includes(S)&&f(b)===A){b.preventDefault(),r(),n(S);return}}};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[e,i,s,r,n,f]),{isMac:o,tabShortcuts:i,shortcutListening:d,setShortcutListening:m,saveShortcuts:p}}const ym=a.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:o,shortcut:i,conversationKeys:c,draggingTabRef:d,onFocus:m,onSelectTab:f,onConversationActivated:p,onPreviewReorder:x,onReorderTab:b,onCommitPreviewOrder:S,onClearPreviewOrder:A,onDragStateReset:u,onDragTabKeyChange:h,onReceiveTab:y,onOpenContextMenu:l,longPressTimer:j,isGroupActive:P}){const k=ks(s),g=k.isGenerating?"agent-tab-generating":k.isWaiting?"agent-tab-waiting":"",N=k.isReconnecting,v=a.useCallback(V=>{d.current=s.tabKey,h(s.tabKey),V.dataTransfer.setData("text/tab-key",s.tabKey),V.dataTransfer.effectAllowed="move"},[s.tabKey,d,h]),w=a.useCallback(()=>{d.current=null,h(null),S(),A(),u()},[d,h,S,A,u]),M=a.useCallback(V=>{const J=d.current;if(!(!J||J===s.tabKey)&&V.dataTransfer.types.includes("text/tab-key")){V.preventDefault(),V.stopPropagation();const I=V.currentTarget.getBoundingClientRect(),R=V.clientX<I.left+I.width/2?"left":"right";x(J,s.tabKey,R)}},[s.tabKey,d,x]),T=a.useCallback(V=>{V.preventDefault(),V.stopPropagation();const J=V.dataTransfer.getData("text/tab-key");if(J&&J!==s.tabKey){const I=V.currentTarget.getBoundingClientRect(),R=V.clientX<I.left+I.width/2?"left":"right";c.includes(J)?b(J,s.tabKey,R):y&&y(J)}A()},[s.tabKey,c,b,y,A]),$=a.useCallback(V=>{V.stopPropagation(),m(),f(s.tabKey),p(s)},[s,p,m,f]),E=a.useCallback(V=>{V.preventDefault(),l(V.clientX,V.clientY,s.tabKey)},[s.tabKey,l]),F=a.useCallback(V=>{const J=V.touches[0];j.current=setTimeout(()=>{l(J.clientX,J.clientY,s.tabKey)},600)},[s.tabKey,j,l]),D=a.useCallback(()=>{j.current&&clearTimeout(j.current)},[j]),C=["adhdev-dockview-tab",g,r&&"is-active",P&&"is-group-active",N&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:C,draggable:!0,onDragStart:v,onDragEnd:w,onDragOver:M,onDrop:T,onClick:$,onContextMenu:E,onTouchStart:F,onTouchEnd:D,onTouchMove:D,style:{cursor:"pointer",opacity:n?.4:void 0},children:[o&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status",children:k.isGenerating?t.jsx("div",{className:"tab-spinner"}):k.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):N?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):k.isConnecting?t.jsx("div",{className:"tab-connecting-spinner"}):s.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("span",{className:"adhdev-dockview-tab-primary",title:st(s),children:st(s)}),t.jsx("span",{className:"adhdev-dockview-tab-meta",children:N?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:qt(s)}):k.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[qt(s),t.jsx("span",{className:"connecting-dots"})]}):qt(s)})]}),i&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${i}`,children:i})]})},(e,s)=>e.conv===s.conv&&e.isActive===s.isActive&&e.isDraggedTab===s.isDraggedTab&&e.isTaskCompleteUnread===s.isTaskCompleteUnread&&e.shortcut===s.shortcut&&e.conversationKeys===s.conversationKeys&&e.isGroupActive===s.isGroupActive);function vm({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:o,onFocus:i,onSelectTab:c,onConversationActivated:d,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:p,onClearPreviewOrder:x,onDragStateReset:b,onDragTabKeyChange:S,onReceiveTab:A,onHideTab:u,isGroupActive:h,allowTabShortcuts:y=!0}){const[l,j]=a.useState(null),P=a.useRef(null),k=a.useRef(null),g=a.useMemo(()=>e.map(E=>E.tabKey),[e]);zs("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(l==null?void 0:l.tabKey)||null});const{isMac:N,tabShortcuts:v,shortcutListening:w,setShortcutListening:M,saveShortcuts:T}=ki({enabled:y,sortedTabKeys:e.map(E=>E.tabKey),onFocus:i,onSelectTab:c});a.useEffect(()=>{if(!l)return;const E=F=>{const D=document.querySelector("[data-pane-context-menu]");D&&D.contains(F.target)||j(null)};return window.addEventListener("mousedown",E,!0),()=>window.removeEventListener("mousedown",E,!0)},[l]),a.useEffect(()=>{const E=k.current;if(!E)return;const F=D=>{Math.abs(D.deltaY)>Math.abs(D.deltaX)&&(D.preventDefault(),E.scrollLeft+=D.deltaY)};return E.addEventListener("wheel",F,{passive:!1}),()=>E.removeEventListener("wheel",F)},[]);const $=a.useCallback((E,F,D)=>{j({x:E,y:F,tabKey:D})},[]);return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:t.jsxs("div",{ref:k,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none"},children:[e.map(E=>t.jsx(ym,{conv:E,isActive:s===E.tabKey,isDraggedTab:o.current===E.tabKey,isTaskCompleteUnread:n.has(E.tabKey),shortcut:y?v[E.tabKey]:void 0,conversationKeys:g,draggingTabRef:o,onFocus:i,onSelectTab:c,onConversationActivated:d,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:p,onClearPreviewOrder:x,onDragStateReset:b,onDragTabKeyChange:S,onReceiveTab:A,onOpenContextMenu:$,longPressTimer:P,isGroupActive:h},E.tabKey)),e.length===0&&t.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),l&&t.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:l.x,top:l.y},children:[y&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:E=>{E.stopPropagation(),M(l.tabKey),j(null)},children:["⌨ ",v[l.tabKey]?`Change shortcut (${v[l.tabKey]})`:"Set shortcut"]}),v[l.tabKey]&&t.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onClick:()=>{const E={...v};delete E[l.tabKey],T(E),j(null)},children:"✕ Remove shortcut"})]}),u&&t.jsxs(t.Fragment,{children:[y&&t.jsx("div",{className:"border-t border-border-subtle my-1"}),t.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onClick:()=>{u(l.tabKey),j(null)},children:"🚫 Hide from Dashboard"})]})]}),y&&w&&t.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>M(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:E=>E.stopPropagation(),children:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",N?"⌘+1":"Ctrl+1",", ",N?"⌥+A":"Alt+A",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function wm({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:d,hasRegisteredMachines:m,userName:f,groupIndex:p,onFocus:x,isSplitMode:b,numGroups:S,onMoveTab:A,onReceiveTab:u,style:h,onActiveTabChange:y,initialActiveTabId:l,initialTabOrder:j,onTabOrderChange:P,onHideTab:k,isFocused:g,allowTabShortcuts:N=!0}){const{sendCommand:v}=Ct(),w=a.useRef(null),{activeTabId:M,activeConv:T,sortedConversations:$,draggingTabRef:E,selectTab:F,handleTabReorder:D,updatePreviewOrder:C,commitPreviewOrder:V,clearPreviewOrder:J,moveTabToEnd:I,setDraggingTabKey:R}=bm({conversations:e,initialActiveTabId:l,initialTabOrder:j,onActiveTabChange:y,onTabOrderChange:P}),B=Lr({sendDaemonCommand:o,activeConv:T,setLocalUserMessages:i,setActionLogs:c,isStandalone:d}),{dragOver:z,dropAction:Z,resetDragState:fe,handleDragEnter:Pe,handleDragOver:ke,handleDragLeave:ve,handleDrop:Q}=xm({conversations:e,numGroups:S,onMoveTab:A,onReceiveTab:u,onOwnTabDrop:I,onClearPreviewOrder:J}),xe=T&&!Ve(T)&&vs(T)==="terminal",W=a.useMemo(()=>T?s.find(te=>te.id===T.routeId):void 0,[s,T]),ee=a.useMemo(()=>T?n.filter(te=>te.routeId===T.tabKey):[],[n,T]),ne=a.useMemo(()=>Fs(s),[s]),oe=a.useMemo(()=>new Set($.filter(te=>ol(te,ne,{isOpenConversation:te.tabKey===M})).map(te=>te.tabKey)),[M,ne,$]);zs("PaneGroup",{groupIndex:p,conversationCount:e.length,activeTabId:M,dragOver:z});const he=a.useCallback(te=>{te.streamSource==="agent-stream"&&te.agentType&&v(te.routeId,"focus_session",{agentType:te.agentType,...te.sessionId&&{targetSessionId:te.sessionId}}).catch(()=>{})},[v]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:x,style:{...h,outline:z?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(vm,{conversations:$,activeTabId:M,groupIndex:p,numGroups:S,unreadTabKeys:oe,draggingTabRef:E,onFocus:x,onSelectTab:F,onConversationActivated:he,onPreviewReorder:C,onReorderTab:D,onCommitPreviewOrder:V,onClearPreviewOrder:J,onDragStateReset:fe,onDragTabKeyChange:R,onMoveTab:A,onReceiveTab:u,onHideTab:k,isGroupActive:g??!1,allowTabShortcuts:N}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:Pe,onDragOver:ke,onDragLeave:ve,onDrop:Q,children:[z&&t.jsx(gm,{dropAction:Z,canSplit:!!(S<4&&A)}),T?t.jsx(Gn,{activeConv:T,clearToken:r[T.tabKey]||0,isCliTerminal:!!xe,ideEntry:W,terminalRef:w,handleModalButton:B.handleModalButton,handleRelaunch:B.handleRelaunch,handleSendChat:B.handleSendChat,isSendingChat:B.isSendingChat,handleFocusAgent:B.handleFocusAgent,isFocusingAgent:B.isFocusingAgent,actionLogs:ee,userName:f,isInputActive:!b||!!g}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(Yn,{conversationsCount:e.length,isSplitMode:b,isStandalone:d,hasRegisteredMachines:m})})]})]})}function jm({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:o,clearedTabs:i,ides:c,actionLogs:d,sendDaemonCommand:m,setLocalUserMessages:f,setActionLogs:p,isStandalone:x,hasRegisteredMachines:b,userName:S,focusedGroup:A,setFocusedGroup:u,moveTabToGroup:h,splitTabRelative:y,closeGroup:l,handleResizeStart:j,groupActiveTabIds:P,setGroupActiveTabIds:k,groupTabOrders:g,setGroupTabOrders:N,toggleHiddenTab:v,allowTabShortcuts:w=!0}){return t.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:o.map((M,T)=>{const $=s&&n.length===r?`${n[T]}%`:void 0;return t.jsxs(rt.Fragment,{children:[s&&T>0&&t.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:E=>j(T-1,E),onDoubleClick:()=>l(T),title:"Drag to resize · Double-click to merge",children:t.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),t.jsx(wm,{style:s?{flexBasis:$??`${100/r}%`,flexGrow:$?0:1,flexShrink:$?0:1}:void 0,conversations:M,clearedTabs:i,ides:c,actionLogs:d,sendDaemonCommand:m,setLocalUserMessages:f,setActionLogs:p,isStandalone:x,hasRegisteredMachines:b,userName:S,groupIndex:T,isFocused:s&&A===T,onFocus:()=>u(T),isSplitMode:s,numGroups:r,onMoveTab:(E,F)=>{F==="left"&&T>0?h(E,T-1):F==="right"&&T<r-1?h(E,T+1):F==="split-left"&&r<4?y(E,T,"left"):F==="split-right"&&r<4&&y(E,T,"right")},onReceiveTab:E=>h(E,T),onActiveTabChange:E=>k(F=>(F[T]??null)===(E??null)?F:{...F,[T]:E}),initialActiveTabId:P[T],initialTabOrder:g[T],onTabOrderChange:E=>N(F=>{const D=F[T]||[];return D.length===E.length&&D.every((C,V)=>C===E[V])?F:{...F,[T]:E}}),onHideTab:v,allowTabShortcuts:w})]},T)})})}function Ni({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[o,i]=a.useState(null),[c,d]=a.useState(null);a.useEffect(()=>e?at.onScreenshot("ide-page",(p,x)=>{if(p!==e)return;const b=new FileReader;b.onload=()=>i(b.result),b.readAsDataURL(x)}):void 0,[e]),a.useEffect(()=>{r!=="connected"&&i(null)},[r]),a.useEffect(()=>{var p;return e?((p=at.onStatus)==null?void 0:p.call(at,(x,b)=>{x===e&&b!=null&&b.screenshotUsage&&d(b.screenshotUsage)}))||(()=>{}):void 0},[e]),a.useEffect(()=>{i(null)},[e,s]),a.useEffect(()=>{const f=e?at.get(e):null;if(!(!f||r!=="connected"))return n!=="chat"&&s?f.startScreenshots(s):f.stopScreenshots(s),()=>{f.stopScreenshots(s)}},[n,r,s,e]);const m=a.useCallback(async(f,p)=>{const x=e?at.get(e):null;return!x||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):x.sendInput(f,p,s)},[e,r,s]);return{connScreenshot:o,screenshotUsage:c,handleRemoteAction:m}}const Si="adhdev-dashboard-action-shortcuts",km=1200,Nm={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Sm(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function Je(e,s){switch(e){case"openShortcutHelp":return"?";case"hideCurrentTab":return s?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return s?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return s?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return s?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return s?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return s?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return s?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return s?"⌘+⌥+=":"Ctrl+Alt+\\";case"splitActiveTabDown":return s?"⌘+⌥+-":"Ctrl+Alt+-";case"focusLeftPane":return s?"⌘+⌥+[":"Ctrl+Alt+←";case"focusRightPane":return s?"⌘+⌥+]":"Ctrl+Alt+→";case"focusUpPane":return s?"⌘+⌥+U":"Ctrl+Alt+↑";case"focusDownPane":return s?"⌘+⌥+J":"Ctrl+Alt+↓";case"moveActiveTabToLeftPane":return s?"⌘+⌥+,":"Ctrl+Alt+Shift+←";case"moveActiveTabToRightPane":return s?"⌘+⌥+.":"Ctrl+Alt+Shift+→";case"moveActiveTabToUpPane":return s?"⌘+⌥+I":"Ctrl+Alt+Shift+↑";case"moveActiveTabToDownPane":return s?"⌘+⌥+K":"Ctrl+Alt+Shift+↓";case"triggerPrimaryApprovalAction":return s?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return s?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return s?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return s?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return s?"⌥+[":"Ctrl+Alt+[";case"selectNextGroupTab":return s?"⌥+]":"Ctrl+Alt+]";case"toggleCliView":return s?"⌥+T":"Ctrl+Alt+T"}}function Ci(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:Je("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:Je("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:Je("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:Je("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:Je("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:Je("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:Je("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:Je("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:Je("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:Je("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:Je("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:Je("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:Je("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:Je("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:Je("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:Je("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:Je("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:Je("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:Je("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:Je("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:Je("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:Je("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:Je("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:Je("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:Je("toggleCliView",e)}]}function kn(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function Ir(e){const s=Object.fromEntries(Ci(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Si)||"{}"),n={...s,...r};for(const[o,i]of Object.entries(Nm))n[o]===i&&(n[o]=s[o]);return n}catch{return s}}function Ii(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Cm({enabled:e=!0,onTrigger:s}){const r=Sm(),[n,o]=a.useState(()=>Ir(r)),[i,c]=a.useState(null),[d,m]=a.useState([]),f=a.useRef({parts:[],timer:null}),p=a.useCallback(u=>{const h=[];return u.metaKey&&h.push(r?"⌘":"Meta"),u.ctrlKey&&h.push("Ctrl"),u.altKey&&h.push(r?"⌥":"Alt"),u.shiftKey&&u.key.length!==1&&h.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(u.key)?null:(h.push(Ii(u.key)),h.join("+"))},[r]),x=a.useCallback(u=>{o(u);try{localStorage.setItem(Si,JSON.stringify(u))}catch{}},[]);a.useEffect(()=>{const u=Ir(r),h=Object.entries(n),y=Object.entries(u);h.length===y.length&&h.every(([l,j])=>u[l]===j)||x(u)},[n,r,x]);const b=a.useCallback(()=>{typeof window<"u"&&f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current={parts:[],timer:null}},[]),S=a.useCallback(()=>{typeof window>"u"||(f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current.timer=window.setTimeout(()=>{f.current={parts:[],timer:null}},km))},[]);a.useEffect(()=>{if(!i)return;const u=h=>{if(h.preventDefault(),h.stopPropagation(),h.key==="Escape"){c(null),m([]);return}const y=p(h);if(!y)return;const j=!(h.metaKey||h.ctrlKey||h.altKey)&&/^[A-Z0-9]$/.test(y);if(d.length===0&&j){m([y]);return}const k=[...d,y].slice(0,2).join(" "),g={...n};for(const[N,v]of Object.entries(g))v===k&&delete g[N];g[i]=k,x(g),c(null),m([])};return window.addEventListener("keydown",u,!0),()=>window.removeEventListener("keydown",u,!0)},[n,p,x,i,d]),a.useEffect(()=>{if(!e||i)return;const u=h=>{if(h.defaultPrevented)return;const y=p(h);if(!y)return;const l=h.metaKey||h.ctrlKey||h.altKey;if(kn(h.target)&&!l)return;const j=f.current.parts,P=l?[y]:[...j.slice(-1),y].slice(-2),k=P.join(" "),g=P[P.length-1],N=Object.entries(n).filter(([,$])=>!!$),v=N.find(([,$])=>$===k);if(v){h.preventDefault(),b(),s(v[0]);return}if(N.some(([,$])=>$.startsWith(`${k} `))){h.preventDefault(),f.current.parts=P,S();return}const M=N.find(([,$])=>$===g);if(M){h.preventDefault(),b(),s(M[0]);return}if(N.some(([,$])=>$.startsWith(`${g} `))){h.preventDefault(),f.current.parts=[g],S();return}b()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[n,S,e,p,s,b,i]),a.useEffect(()=>()=>b(),[b]);const A=a.useMemo(()=>Ci(r),[r]);return{isMac:r,actionDefinitions:A,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:d,setShortcutListening:c,setShortcutListeningDraft:m,saveShortcuts:x}}const Ti=a.createContext(null);function Kr(){const e=a.useContext(Ti);if(!e)throw new Error("DashboardDockviewContext missing");return e}function br(e){return st(e)||e.tabKey}function Im(e){return`remote:${e}`}function Wt(e){return e.startsWith("remote:")}function Ya(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function sn(e){var r,n,o,i,c;const s=e==null?void 0:e.defaultView;if(s)try{s.focus(),(n=(r=e==null?void 0:e.body)==null?void 0:r.focus)==null||n.call(r),(i=(o=e==null?void 0:e.documentElement)==null?void 0:o.focus)==null||i.call(o),(c=s.requestAnimationFrame)==null||c.call(s,()=>{var d,m;try{s.focus(),(m=(d=e==null?void 0:e.body)==null?void 0:d.focus)==null||m.call(d)}catch{}})}catch{}}function lr(e,s){e.classList.remove(mn.className,pn.className),e.classList.add(s==="light"?mn.className:pn.className)}function Xa(e){return e?Array.from(new Set(e.groups.map(s=>{var r,n;return(n=(r=s.element)==null?void 0:r.ownerDocument)==null?void 0:n.defaultView}).filter(s=>!!s&&s!==window))):[]}function Tm(e){const[,s]=a.useState(0);a.useEffect(()=>{const r=()=>s(o=>o+1),n=[e.api.onDidActiveGroupChange(r),e.api.onDidTitleChange(r),e.api.onDidGroupChange(r),e.containerApi.onDidActivePanelChange(r)];return()=>{for(const o of n)o.dispose()}},[e.api,e.containerApi])}function Am(e,s,r){var d;const n=[s];let o;for(const m of n){let f;for(const p of m){const x=e.addPanel({id:p.tabKey,component:"conversation",title:br(p),params:{kind:"conversation",tabKey:p.tabKey},...f?{position:{referencePanel:f,direction:"within"},inactive:!0}:o?{position:{referencePanel:o,direction:"right"},inactive:!0}:{}});f||(f=x.id)}o=f??o}const i=r??((d=s[0])==null?void 0:d.tabKey)??null;if(!i)return;const c=e.getPanel(i);c&&c.group.model.openPanel(c)}function Ja(e,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...e.panels])Wt(n.id)||r.has(n.id)||e.removePanel(n);for(const n of s){const o=e.getPanel(n.tabKey);if(o){o.update({params:{tabKey:n.tabKey}}),o.title!==br(n)&&o.api.setTitle(br(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:br(n),params:{kind:"conversation",tabKey:n.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function Za(e,s,r){var m,f;const n=r?Im(r):null;for(const p of[...e.panels])Wt(p.id)&&(!n||p.id!==n)&&e.removePanel(p);if(!r||!n)return;const o=Lt(s,r);if(!o&&e.totalPanels===0)return;const i=e.getPanel(n),c=zo(o);if(i){i.title!==c&&i.api.setTitle(c);return}const d=(o==null?void 0:o.tabKey)??((m=e.activePanel)==null?void 0:m.id)??((f=e.panels.find(p=>!Wt(p.id)))==null?void 0:f.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...d?{position:{referencePanel:d,direction:"right"},inactive:!0}:{}})}function Mm({params:e,api:s}){var x;const r=Kr(),n=a.useRef(null),[o,i]=a.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),d=Lr({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});a.useEffect(()=>{i(s.isActive);const b=[s.onDidActiveChange(S=>i(S.isActive)),s.onDidActiveGroupChange(S=>{if(!s.isActive&&!S.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const S of b)S.dispose()}},[s]);const m=a.useMemo(()=>c?r.ides.find(b=>b.id===c.routeId):void 0,[r.ides,c]),f=a.useMemo(()=>c?r.actionLogs.filter(b=>b.routeId===c.tabKey):[],[r.actionLogs,c]);if(!c)return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:t.jsx(Yn,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,suppressGuide:r.hasDetachedConversationPanels})});const p=!Ve(c)&&vs(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(Gn,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:p,ideEntry:m,terminalRef:n,handleModalButton:d.handleModalButton,handleRelaunch:d.handleRelaunch,handleSendChat:d.handleSendChat,isSendingChat:d.isSendingChat,handleFocusAgent:d.handleFocusAgent,isFocusingAgent:d.isFocusingAgent,actionLogs:f,userName:r.userName,scrollToBottomRequestNonce:((x=r.scrollToBottomRequest)==null?void 0:x.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:o})})}function _m({params:e}){var m;const s=Kr(),r=a.useMemo(()=>Lt([...s.conversationsByTabKey.values()],e.routeId),[s.conversationsByTabKey,e.routeId]),n=a.useMemo(()=>s.ides.find(f=>f.id===e.routeId),[s.ides,e.routeId]),o=(r==null?void 0:r.daemonId)||((m=r==null?void 0:r.routeId)==null?void 0:m.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:d}=Ni({doId:o,targetSessionId:r?Bn(r):(n==null?void 0:n.sessionId)||(n==null?void 0:n.instanceId),connState:(r==null?void 0:r.connectionState)||"new",viewMode:"remote"});return r?t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:t.jsx(So,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:c,transportType:r.transport,onAction:d})}):t.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:"Remote view unavailable"})}function Pm(){const e=Kr();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(Yn,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,suppressGuide:e.hasDetachedConversationPanels})})}function Rm(e){var S,A;Tm(e);const s=Kr(),r=a.useCallback(u=>{"button"in u&&u.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const u=Lt([...s.conversationsByTabKey.values()],e.params.routeId),h=((S=e.api.group.activePanel)==null?void 0:S.id)===e.api.id,y=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${h?" is-active":""}${y?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(u==null?void 0:u.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:u!=null&&u.machineName?t.jsxs(t.Fragment,{children:[t.jsx("span",{children:"Live remote view"}),t.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),t.jsx("span",{className:"adhdev-dockview-tab-machine",children:u.machineName})]}):t.jsx("span",{children:"Live remote view"})})]})]})}const n=s.conversationsByTabKey.get(e.params.tabKey);if(!n)return t.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:t.jsx("div",{className:"adhdev-dockview-tab-copy",children:t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const o=((A=e.api.group.activePanel)==null?void 0:A.id)===e.api.id,i=e.api.isGroupActive,c=Os(n,s.liveSessionInboxState,{isOpenConversation:o}),d=c.isReconnecting,m=c.isConnecting,f=c.isGenerating,p=c.isWaiting,x=c.unread,b=s.tabShortcuts[n.tabKey];return t.jsxs("div",{className:`adhdev-dockview-tab${o?" is-active":""}${i?" is-group-active":""}${d?" is-reconnecting":""}`,title:st(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:u=>{var h;u.preventDefault(),r(u),s.openTabContextMenu({x:u.clientX,y:u.clientY,tabKey:n.tabKey,sourceDocument:((h=u.target)==null?void 0:h.ownerDocument)??document})},children:[x&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:f?t.jsx("div",{className:"tab-spinner"}):p?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):d?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):m?t.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:st(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:d?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:qt(n)}):m?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:qt(n)}):t.jsx("span",{children:qt(n)})})]}),b&&t.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 Lm({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:d,hasRegisteredMachines:m,initialDataLoaded:f,userName:p,toggleHiddenTab:x,actionShortcuts:b,registerActionHandlers:S,onActiveTabChange:A,requestedActiveTabKey:u,requestedRemoteIdeId:h,onRequestedActiveTabConsumed:y,scrollToBottomRequest:l}){var Te,Ae,Qe;const{theme:j}=Un(),{sendCommand:P}=Ct(),k=a.useRef(null),g=a.useRef(null),N=a.useRef(!1),v=a.useRef(!1),w=a.useRef(!1),M=a.useRef(null),T=a.useRef([]),[$,E]=a.useState(null),[F,D]=a.useState(!1),[C,V]=a.useState(!1),[J,I]=a.useState(0),R=a.useRef(null),B=a.useMemo(()=>fi(typeof window<"u"?window.innerWidth:1280),[]),z=a.useRef(typeof window>"u"?{}:Ku(B)),Z=a.useMemo(()=>new Map(e.map(K=>[K.tabKey,K])),[e]),fe=a.useMemo(()=>Fs(r),[r]),Pe=a.useMemo(()=>{const K=k.current;return K?K.groups.some(O=>{try{const G=O.model.location.type;return G!=="floating"&&G!=="popout"?!1:O.panels.some(H=>Z.has(H.id))}catch{return!1}}):!1},[Z,J,e]),ke=a.useCallback(()=>{var K;(K=k.current)==null||K.focus()},[]),ve=a.useCallback(K=>{const O=document,G=K.document;for(const le of O.querySelectorAll('link[rel="stylesheet"]')){const $e=G.createElement("link");$e.rel="stylesheet",$e.href=le.href,le.crossOrigin&&($e.crossOrigin=le.crossOrigin),G.head.appendChild($e)}for(const le of O.querySelectorAll("style")){const $e=G.createElement("style");$e.textContent=le.textContent,G.head.appendChild($e)}const H=[];for(const le of O.styleSheets)try{for(const $e of le.cssRules)$e instanceof CSSStyleRule&&($e.selectorText===":root"||$e.selectorText==="html")&&H.push($e.cssText)}catch{}if(H.length>0){const le=G.createElement("style");le.textContent=H.join(`
43
43
  `),G.head.appendChild(le)}const ie=O.documentElement.getAttribute("data-theme");ie&&G.documentElement.setAttribute("data-theme",ie),G.documentElement.style.colorScheme=ie==="light"?"light":"dark",G.body.className=O.body.className;const Se=O.documentElement.getAttribute("style");Se&&G.documentElement.setAttribute("style",Se);const Y=G.getElementById("dv-popout-window");Y instanceof HTMLElement&&(Y.classList.add("adhdev-dockview"),lr(Y,j))},[j]),Q=a.useCallback(()=>{var O;const K=k.current;if(K)for(const G of K.groups)try{const H=(O=G.element)==null?void 0:O.ownerDocument;if(!H||H===document)continue;const ie=H.getElementById("dv-popout-window");ie instanceof HTMLElement&&(ie.classList.add("adhdev-dockview"),lr(ie,j));const Se=document.documentElement.getAttribute("data-theme");Se&&H.documentElement.setAttribute("data-theme",Se),H.documentElement.style.colorScheme=Se==="light"?"light":"dark",H.body.className=document.body.className;const Y=document.documentElement.getAttribute("style");Y?H.documentElement.setAttribute("style",Y):H.documentElement.removeAttribute("style")}catch{}},[j]),xe=a.useCallback(()=>{var O;const K=k.current;if(K)for(const G of K.groups)try{const H=(O=G.element)==null?void 0:O.ownerDocument;if(!H||H===document)continue;const ie=H.getElementById("dv-popout-window");if(!(ie instanceof HTMLElement))continue;ie.classList.add("adhdev-dockview"),lr(ie,j),ie.classList.toggle("is-showing-dockview-overlay",C),ie.classList.toggle("is-dragging-dockview",F)}catch{}},[F,C,j]),W=a.useCallback(K=>{const O=k.current;if(!O)return;const G=O.getPanel(K);G&&O.addPopoutGroup(G,{popoutUrl:"/popout.html",onDidOpen:({window:H})=>{ve(H),ae();const ie=Z.get(K);H.document.title=ie?`${st(ie)} — ADHDev`:"ADHDev — Popout"}})},[Z,ve]),ee=a.useCallback(K=>{const O=k.current,G=O==null?void 0:O.getPanel(K);if(!O||!G)return;const H=O.groups.filter(ie=>{var Se;try{return((Se=ie.element)==null?void 0:Se.ownerDocument)===document}catch{return!0}});H.length>0?G.api.moveTo({group:H[0],position:"center"}):G.api.moveTo({position:"center"}),G.api.setActive()},[]),ne=a.useCallback(K=>{var H;const O=k.current;if(!O)return!1;const G=O.getPanel(K);if(!G)return!1;try{return((H=G.group.element)==null?void 0:H.ownerDocument)!==document}catch{return!1}},[]),oe=a.useCallback(K=>{ne(K)&&ee(K),x(K)},[ne,ee,x]),he=a.useCallback(K=>{const O=k.current,G=O==null?void 0:O.getPanel(K);!O||!G||O.addFloatingGroup(G,{width:600,height:500})},[]),te=a.useCallback(K=>{var G;const O=(G=k.current)==null?void 0:G.getPanel(K);if(!O)return!1;try{return O.group.model.location.type==="floating"}catch{return!1}},[]),de=a.useCallback(()=>{var O,G;const K=(G=(O=k.current)==null?void 0:O.activePanel)==null?void 0:G.id;return!K||Wt(K)?null:Z.has(K)?K:null},[Z]),se=a.useCallback(K=>{const O=k.current,G=O==null?void 0:O.getPanel(K);if(!O||!G)return;const H=O.groups.filter(ie=>{try{return ie.model.location.type==="grid"}catch{return!0}});H.length>0?G.api.moveTo({group:H[0],position:"center"}):G.api.moveTo({position:"center"}),G.api.setActive()},[]),pe=a.useCallback(()=>{var Se;const K=k.current;if(!K)return;const G=K.groups.filter(Y=>{var le;try{return((le=Y.element)==null?void 0:le.ownerDocument)===document&&Y.model.location.type==="grid"}catch{return!1}})[0]||null,H=[...K.panels];for(const Y of H){const le=(Se=Y.group.element)==null?void 0:Se.ownerDocument,$e=Y.group.model.location.type;le===document&&$e==="grid"||(G&&G.id!==Y.group.id?Y.api.moveTo({group:G,position:"center"}):Y.api.moveTo({position:"center"}))}const ie=K.activePanel;ie&&(ie.group.model.openPanel(ie),ie.api.setActive()),sn(document)},[]),ae=a.useCallback(()=>{var O,G;const K=k.current;if(K)for(const H of K.groups){const ie=(O=H.element)==null?void 0:O.ownerDocument;if(!ie||ie===document)continue;const Se=ie.getElementById("dv-popout-window");if(!(Se instanceof HTMLElement))continue;let Y=null,le=ie.title||"ADHDev",$e="Popout workspace";const Le=H.activePanel;if(Le)if(Y=Le.id,Wt(Le.id)){const U=((G=Le.params)==null?void 0:G.routeId)||Le.id.slice(7),re=Lt([...Z.values()],U);le=zo(re),$e=re!=null&&re.machineName?`Remote view · ${re.machineName}`:"Remote view"}else{const U=Z.get(Le.id);le=U?st(U):Le.title||Le.id,$e=U?qt(U):"Dockview panel"}ie.title=`${le} — ADHDev`;let Oe=ie.getElementById("adhdev-popout-header");Oe instanceof HTMLElement||(Oe=ie.createElement("div"),Oe.id="adhdev-popout-header",ie.body.appendChild(Oe)),Oe.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(";")),Oe.innerHTML=`
44
44
  <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
45
45
  <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
@@ -63,9 +63,9 @@ This will disconnect CDP and optionally kill the process.`))try{const R=await r(
63
63
  ✅ Auto-fix completed!`]),y.current&&clearInterval(y.current))}catch{}},3e3)},[e,s.type,r,o]),g=async()=>{if(m.length!==0){i("running"),S(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${m.join(", ")}`,p?`💬 Comment: ${p}`:"",""]),u("");try{const v=await r(e,"provider_auto_fix",{providerType:s.type,functions:m,agent:c,...p?{comment:p}:{}});v!=null&&v.success&&(v!=null&&v.started||v!=null&&v.running)?(S(w=>[...w,"✅ Agent started. Monitoring progress..."]),k()):(i("error"),u((v==null?void 0:v.error)||"Failed to start auto-fix"))}catch(v){i("error"),u((v==null?void 0:v.message)||"Connection failed")}}},N=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:s.type}),S(v=>[...v,`
64
64
  ⚠️ Auto-fix cancelled.`]),i("done"),y.current&&clearInterval(y.current)}catch{}};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",onClick:n,children:t.jsxs("div",{className:"w-full max-w-[560px] max-h-[85vh] overflow-hidden rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:v=>v.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:s.icon||"🔧"}),t.jsxs("div",{children:[t.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",s.displayName]}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),t.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),t.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[o==="config"&&t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),t.jsx("div",{className:"flex gap-2",children:lp.map(v=>t.jsxs("button",{onClick:()=>d(v.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===v.value?v.color+"66":"var(--border-subtle)",background:c===v.value?v.color+"0d":"transparent"},children:[t.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===v.value?v.color:"var(--text-primary)"},children:v.label}),t.jsx("div",{className:"text-[10px] text-text-muted",children:v.desc})]},v.value))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:j,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),t.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),t.jsx("button",{onClick:P,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:so.map(v=>t.jsxs("button",{onClick:()=>l(v),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:m.includes(v)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:m.includes(v)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:m.includes(v)?"#a78bfa":"var(--text-secondary)"},children:[m.includes(v)?"☑ ":"☐ ",v]},v))})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",t.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),t.jsx("textarea",{value:p,onChange:v=>x(v.target.value),placeholder:"e.g. Also search buttons inside Shadow DOM, preserve code block formatting in readChat...",rows:2,className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] resize-none placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]})]}),(o==="running"||o==="done"||o==="error")&&t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),t.jsxs("div",{className:"rounded-lg border border-border-subtle bg-[#0d0d0d] p-3 font-mono text-[11px] leading-relaxed text-text-secondary overflow-y-auto",style:{maxHeight:320,minHeight:200},children:[b.map((v,w)=>t.jsx("div",{className:v.startsWith("✅")?"text-green-400":"",style:v.startsWith("❌")||v.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:v},w)),o==="running"&&t.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),t.jsx("div",{ref:h})]}),A&&t.jsx("div",{className:"mt-2 px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:A})]})]}),t.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[t.jsxs("div",{className:"text-[10px] text-text-muted",children:[o==="config"&&m.length>0&&`${m.length} script(s) selected`,o==="running"&&"Agent is generating...",o==="done"&&"Run `adhdev provider verify` to validate"]}),t.jsxs("div",{className:"flex gap-2",children:[o==="config"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:g,disabled:m.length===0,className:"machine-btn",style:{background:m.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:m.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:m.length>0?"#a78bfa":void 0,opacity:m.length===0?.4:1},children:"🚀 Start Fix"})]}),o==="running"&&t.jsx("button",{onClick:N,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(o==="done"||o==="error")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{i("config"),S([]),u("")},className:"machine-btn",children:"← Back"}),t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function up({machineId:e,providers:s,sendDaemonCommand:r,onClose:n,onCreated:o}){var k;const i=s.filter(g=>g.category==="ide"),[c,d]=a.useState(((k=i[0])==null?void 0:k.type)||""),[m,f]=a.useState(""),[p,x]=a.useState(""),[b,S]=a.useState(!1),[A,u]=a.useState(""),[h,y]=a.useState(!1),l=g=>{const N=g.toLowerCase().replace(/[^a-z0-9-]/g,"");f(N),(!p||p===j(m))&&x(j(N))},j=g=>g.split("-").map(N=>N.charAt(0).toUpperCase()+N.slice(1)).join(" "),P=async()=>{if(!(!m||!p||!c)){S(!0),u("");try{const g=await r(e,"provider_clone",{type:m,name:p,category:"ide",location:"user",cloneFrom:c});g!=null&&g.success||g!=null&&g.created?(y(!0),o==null||o(m)):u((g==null?void 0:g.error)||"Failed to create provider")}catch(g){u((g==null?void 0:g.message)||"Connection failed")}S(!1)}};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",onClick:n,children:t.jsxs("div",{className:"w-full max-w-[480px] rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:g=>g.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[t.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),t.jsx("div",{className:"px-5 py-4 flex flex-col gap-4",children:h?t.jsxs("div",{className:"text-center py-6",children:[t.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),t.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[t.jsx("code",{className:"text-violet-400",children:m})," has been created at ",t.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",m,"/"]})]}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",t.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",m]})," or use Auto-Fix to implement scripts."]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:i.map(g=>t.jsxs("button",{onClick:()=>d(g.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===g.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===g.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[t.jsx("div",{className:"text-lg",children:g.icon}),t.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===g.type?"#a78bfa":"var(--text-secondary)"},children:g.displayName})]},g.type))})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),t.jsx("input",{value:m,onChange:g=>l(g.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),t.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",t.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",m||"...","/"]})]})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),t.jsx("input",{value:p,onChange:g=>x(g.target.value),placeholder:"My Custom IDE",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]}),A&&t.jsx("div",{className:"px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:A})]})}),t.jsx("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-end gap-2",children:h?t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:P,disabled:!m||!p||b,className:"machine-btn",style:{background:m&&p?"rgba(34,197,94,0.12)":void 0,borderColor:m&&p?"rgba(34,197,94,0.3)":void 0,color:m&&p?"#86efac":void 0,opacity:!m||!p||b?.4:1},children:b?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function mp({machineId:e,providers:s,sendDaemonCommand:r}){const[n,o]=a.useState([]),[i,c]=a.useState(!1),[d,m]=a.useState(null),[f,p]=a.useState("all"),[x,b]=a.useState(null),[S,A]=a.useState(!1),u=a.useCallback(async()=>{if(e){c(!0);try{const y=await r(e,"get_provider_settings",{}),l=ip(y);if(l){const j=cp(l,s);j.sort((P,k)=>P.category.localeCompare(k.category)||P.displayName.localeCompare(k.displayName)),o(j)}}catch{}c(!1)}},[e,s,r]);a.useEffect(()=>{n.length===0&&u()},[]);const h=async(y,l,j)=>{m(`${y}.${l}`),o(P=>P.map(k=>k.type===y?{...k,values:{...k.values,[l]:j}}:k));try{const P=await r(e,"set_provider_setting",{providerType:y,key:l,value:j});P!=null&&P.success||u()}catch{u()}m(null)};return t.jsxs("div",{children:[t.jsxs("div",{className:"flex justify-between items-center mb-4",children:[t.jsxs("div",{className:"flex gap-1 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(y=>t.jsx("button",{onClick:()=>p(y),className:`machine-btn text-[10px] px-2 py-0.5 ${f===y?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:y.toUpperCase()},y))]}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:()=>A(!0),className:"machine-btn text-[10px] bg-green-500/[0.06] border-green-500/20 text-green-400 hover:bg-green-500/[0.12]",children:"✨ Create Provider"}),t.jsx("button",{onClick:u,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),f!=="all"&&n.filter(y=>y.category===f).length>1&&(()=>{const y=n.filter(k=>k.category===f),l=new Map;for(const k of y)for(const g of k.schema){if(g.type!=="boolean")continue;const N=l.get(g.key),v=!!(k.values[g.key]??g.default);N?(N.onCount+=v?1:0,N.total+=1):l.set(g.key,{label:g.label||g.key,onCount:v?1:0,total:1})}const j=[...l.entries()].filter(([,k])=>k.total===y.length);if(j.length===0)return null;const P=async(k,g)=>{for(const N of y)await h(N.type,k,g)};return t.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[t.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",f.toUpperCase()," providers (",y.length,")"]}),t.jsx("div",{className:"flex flex-wrap gap-2",children:j.map(([k,g])=>{const N=g.onCount===g.total,v=g.onCount===0;return t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[t.jsx("span",{className:"text-text-secondary font-medium",children:g.label}),t.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",g.onCount,"/",g.total,")"]}),t.jsx("button",{onClick:()=>void P(k,!0),disabled:N,className:`machine-btn text-[9px] px-1.5 py-px ${N?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),t.jsx("button",{onClick:()=>void P(k,!1),disabled:v,className:`machine-btn text-[9px] px-1.5 py-px ${v?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},k)})})]})})(),i&&n.length===0?t.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):t.jsx("div",{className:"flex flex-col gap-2",children:n.filter(y=>f==="all"||y.category===f).map(y=>t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[t.jsx("span",{className:"text-lg",children:y.icon}),t.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:y.displayName}),t.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:y.category==="acp"?"rgba(139,92,246,0.08)":y.category==="cli"?"rgba(59,130,246,0.08)":y.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:y.category==="acp"?"#a78bfa":y.category==="cli"?"#60a5fa":y.category==="ide"?"#86efac":"var(--status-warning)"},children:y.category}),y.category==="ide"&&t.jsx("button",{onClick:()=>b(s.find(l=>l.type===y.type)||{type:y.type,name:y.displayName,displayName:y.displayName,icon:y.icon,category:y.category}),className:"ml-auto machine-btn text-[9px] px-2 py-0.5 bg-violet-500/[0.06] border-violet-500/20 text-violet-400 hover:bg-violet-500/[0.12]",children:"🔧 Auto-Fix"})]}),t.jsx("div",{className:"flex flex-col gap-2",children:y.schema.map(l=>t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("div",{className:"text-xs font-medium text-text-primary",children:[l.label||l.key,d===`${y.type}.${l.key}`&&t.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),l.description&&t.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:l.description})]}),t.jsx("div",{className:"shrink-0",children:l.type==="boolean"?t.jsx("button",{onClick:()=>h(y.type,l.key,!(y.values[l.key]??l.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:y.values[l.key]??l.default?"#8b5cf6":"var(--border-subtle)"},children:t.jsx("div",{className:"w-4 h-4 rounded-full bg-white absolute top-[3px] transition-[left] duration-200 shadow-[0_1px_3px_rgba(0,0,0,0.3)]",style:{left:y.values[l.key]??l.default?21:3}})}):l.type==="number"?t.jsx("input",{type:"number",value:Number(y.values[l.key]??l.default??0)||0,min:l.min,max:l.max,onChange:j=>{const P=parseInt(j.target.value)||0;l.min!==void 0&&P<l.min||l.max!==void 0&&P>l.max||h(y.type,l.key,P)},className:"machine-input w-20 text-center text-[11px]"}):l.type==="select"&&l.options?t.jsx("select",{value:String(y.values[l.key]??l.default??""),onChange:j=>h(y.type,l.key,j.target.value),className:"machine-input text-[11px]",children:l.options.map(j=>t.jsx("option",{value:j,children:j},j))}):t.jsx("input",{type:"text",value:String(y.values[l.key]??l.default??""),onBlur:j=>h(y.type,l.key,j.target.value),className:"machine-input w-[120px] text-[11px]"})})]},l.key))})]},y.type))}),x&&t.jsx(dp,{machineId:e,provider:x,sendDaemonCommand:r,onClose:()=>b(null)}),S&&t.jsx(up,{machineId:e,providers:s,sendDaemonCommand:r,onClose:()=>A(!1),onCreated:()=>{A(!1),u()}})]})}function ro(e){if(!e||Object.keys(e).length===0)return"";try{const s=JSON.stringify(e);return s.length>220?`${s.slice(0,220)}…`:s}catch{return"[unserializable payload]"}}function pp({machineId:e,sendDaemonCommand:s}){const[r,n]=a.useState([]),[o,i]=a.useState([]),[c,d]=a.useState([]),[m,f]=a.useState(0),[p,x]=a.useState(0),[b,S]=a.useState(!0),[A,u]=a.useState("debug"),h=a.useRef(null),y=a.useRef(!1);return a.useEffect(()=>{if(!e||!b)return;const l=async()=>{try{const[P,k]=await Promise.all([s(e,"get_logs",{count:200,minLevel:A,since:m}),s(e,"get_debug_trace",{count:120,since:p})]),g=(P==null?void 0:P.result)||P;if(P!=null&&P.success&&Array.isArray(g==null?void 0:g.logs)&&g.logs.length>0){n(w=>[...w,...g.logs.map(T=>({timestamp:T.ts,level:T.level,message:`[${T.category}] ${T.message}`}))].slice(-300));const v=Math.max(...g.logs.map(w=>w.ts));f(v)}const N=(k==null?void 0:k.result)||k;if(k!=null&&k.success&&Array.isArray(N==null?void 0:N.trace)){i(N.trace.slice(-120));const v=N.trace.reduce((w,M)=>Math.max(w,Number(M.ts||0)),p);v>p&&x(v)}}catch{}d(ss.list({limit:120}))};l();const j=setInterval(l,3e3);return()=>clearInterval(j)},[e,b,m,p,A,s]),a.useEffect(()=>{if(b&&(r.length>0||o.length>0||c.length>0)){const l=y.current?"smooth":"instant";setTimeout(()=>{var j;(j=h.current)==null||j.scrollIntoView({behavior:l}),y.current=!0},50)}},[r.length,o.length,c.length,b]),t.jsxs("div",{children:[t.jsxs("div",{className:"flex justify-between items-center mb-3",children:[t.jsxs("div",{className:"flex gap-1 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Level"}),["debug","info","warn","error"].map(l=>t.jsx("button",{onClick:()=>{u(l),n([]),f(0)},className:`machine-btn text-[10px] px-2 py-0.5 ${A===l?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:l.toUpperCase()},l))]}),t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsxs("span",{className:"text-[10px] text-text-muted",children:["logs=",r.length," trace=",o.length," web=",c.length]}),t.jsx("button",{onClick:()=>S(!b),className:`machine-btn ${b?"text-green-500 border-green-500/30":""}`,children:b?"⏸ Pause":"▶ Resume"}),t.jsx("button",{onClick:()=>{n([]),i([]),d([]),f(0),x(0),ss.clear()},className:"machine-btn",children:"Clear"})]})]}),t.jsxs("div",{className:"grid gap-3",children:[t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl p-3 min-h-[180px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[t.jsx("div",{className:"mb-2 text-[10px] uppercase tracking-wider text-text-muted",children:"Daemon logs"}),r.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs..."}),r.map((l,j)=>t.jsxs("div",{className:"flex gap-2 py-px",style:{color:l.level==="error"?"#ef4444":l.level==="warn"?"var(--status-warning)":l.level==="debug"?"#64748b":"#94a3b8"},children:[t.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(l.timestamp).toLocaleTimeString()}),t.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:l.level==="error"?"ERR":l.level==="warn"?"WRN":l.level==="debug"?"DBG":"INF"}),t.jsx("span",{children:l.message})]},`log-${j}`))]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl p-3 min-h-[180px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[t.jsx("div",{className:"mb-2 text-[10px] uppercase tracking-wider text-text-muted",children:"Structured daemon trace"}),o.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No trace entries yet. Run daemon with --dev or --trace."}),o.map(l=>t.jsxs("div",{className:"py-1 border-b border-white/5 last:border-b-0",children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted",children:[t.jsx("span",{children:new Date(l.ts).toLocaleTimeString()}),t.jsx("span",{children:l.level.toUpperCase()}),t.jsxs("span",{children:[l.category,".",l.stage]}),l.interactionId&&t.jsxs("span",{children:["ix=",l.interactionId]})]}),t.jsx("div",{children:ro(l.payload)})]},l.id))]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl p-3 min-h-[160px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[t.jsx("div",{className:"mb-2 text-[10px] uppercase tracking-wider text-text-muted",children:"Browser debug events"}),c.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No browser debug events captured yet."}),c.map(l=>t.jsxs("div",{className:"py-1 border-b border-white/5 last:border-b-0",children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted",children:[t.jsx("span",{children:new Date(l.ts).toLocaleTimeString()}),t.jsx("span",{children:l.kind}),l.topic&&t.jsxs("span",{children:["topic=",l.topic]}),l.interactionId&&t.jsxs("span",{children:["ix=",l.interactionId]})]}),t.jsx("div",{children:ro(l.payload)})]},l.id))]})]}),t.jsx("div",{ref:h})]})}function on(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function cn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function no(e){if(!e)return"unknown";const s=Date.now()-e,r=Math.max(0,Math.round(s/1e3));if(r<60)return`${r}s ago`;const n=Math.round(r/60);if(n<60)return`${n}m ago`;const o=Math.round(n/60);return o<48?`${o}h ago`:`${Math.round(o/24)}d ago`}function fp(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function xp(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 hp(e){var r;const s=new Map;for(const n of e){if(!["starting","running","stopping","interrupted"].includes(n.lifecycle))continue;const o=typeof((r=n.meta)==null?void 0:r.providerSessionId)=="string"?String(n.meta.providerSessionId).trim():"";if(!o)continue;const i=`${n.providerType}::${n.workspace}::${o}`;s.set(i,(s.get(i)||0)+1)}return Array.from(s.values()).filter(n=>n>1).length}function bp({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,o]=a.useState(""),[i,c]=a.useState(null),[d,m]=a.useState(!1),f=ui(e,{enabled:!!e,includeSessions:!0,limit:12,intervalMs:8e3}),p=f.diagnostics,x=f.loading,b=f.applyDiagnostics,S=a.useMemo(()=>new Map(s.map(M=>[M.sessionId||M.id,M])),[s]),A=a.useCallback(async()=>{if(e){m(!0);try{const M=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:12}),T=on(M);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),o("")}catch(M){const T=M instanceof Error?M.message:"Could not load hosted runtime diagnostics";o(T)}finally{m(!1)}}},[b,e,r]);a.useEffect(()=>{!e||p||x||d||A()},[p,x,e,A,d]);const u=a.useCallback(async(M,T)=>{const $=`${M}:${T.sessionId}`;if(!(M==="session_host_stop_session"&&!window.confirm(`Stop ${T.displayName}?
65
65
  This will terminate the hosted runtime.`))){c($);try{const E=await r(e,M,{sessionId:T.sessionId}),F=on(E);if(!(F!=null&&F.success))throw new Error((F==null?void 0:F.error)||"Session host action failed");const D=M==="session_host_resume_session"?"resumed":M==="session_host_restart_session"?"restarted":"stopped";tt.showToast(`Session host ${D}: ${T.displayName}`,"success"),await A()}catch(E){const F=E instanceof Error?E.message:"Session host action failed";tt.showToast(F,"warning"),o(F)}finally{c(E=>E===$?null:E)}}},[e,A,r]),h=a.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
66
- 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",{}),$=on(T);if(!($!=null&&$.success))throw new Error(($==null?void 0:$.error)||"Duplicate prune failed");const E=$.result||{},F=Array.isArray(E.prunedSessionIds)?E.prunedSessionIds.length:0,D=typeof E.duplicateGroupCount=="number"?E.duplicateGroupCount:0;tt.showToast(`Pruned ${F} duplicate runtime(s) across ${D} group(s)`,"success"),await A()}catch(T){const $=T instanceof Error?T.message:"Duplicate prune failed";tt.showToast($,"warning"),o($)}finally{c(T=>T==="session_host_prune_duplicate_sessions"?null:T)}}},[e,A,r]),y=a.useMemo(()=>[...(p==null?void 0:p.sessions)||[]].sort((M,T)=>(T.lastActivityAt||0)-(M.lastActivityAt||0)),[p==null?void 0:p.sessions]),l=a.useMemo(()=>p!=null&&p.liveRuntimes||p!=null&&p.recoverySnapshots||p!=null&&p.inactiveRecords?{liveRuntimes:(p==null?void 0:p.liveRuntimes)||[],recoverySnapshots:(p==null?void 0:p.recoverySnapshots)||[],inactiveRecords:(p==null?void 0:p.inactiveRecords)||[]}:Li(y),[p==null?void 0:p.inactiveRecords,p==null?void 0:p.liveRuntimes,p==null?void 0:p.recoverySnapshots,y]),j=l.liveRuntimes,P=l.recoverySnapshots,k=l.inactiveRecords,g=a.useMemo(()=>hp(j),[j]),N=a.useMemo(()=>[...(p==null?void 0:p.recentTransitions)||[]].slice(-6).reverse(),[p==null?void 0:p.recentTransitions]),v=a.useMemo(()=>[...(p==null?void 0:p.recentLogs)||[]].reverse().find(M=>M.level==="warn"||M.level==="error")||null,[p==null?void 0:p.recentLogs]),w=(M,T)=>{var R;const $=i===`session_host_resume_session:${M.sessionId}`,E=i===`session_host_restart_session:${M.sessionId}`,F=i===`session_host_stop_session:${M.sessionId}`,D=Xn(M.meta),C=S.get(M.sessionId),V=M.attachedClients.length===1?"1 client":`${M.attachedClients.length} clients`,J=T==="recovery"?"Recover":"Resume",I=Di(T);return t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:M.displayName||(C==null?void 0:C.cliName)||M.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${xp(M.lifecycle)}`,children:M.lifecycle}),D&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:D})]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:"text-text-primary/90",children:M.workspaceLabel||(C==null?void 0:C.runtimeWorkspaceLabel)||M.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:M.runtimeKey}),M.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",M.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((R=M.writeOwner)==null?void 0:R.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:fp(M.writeOwner)}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[t.jsx(An,{size:11})," ",V]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",no(M.lastActivityAt)]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-sky-200",children:["Next: ",I]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[T==="recovery"&&(M.lifecycle==="interrupted"||M.lifecycle==="failed"||M.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{u("session_host_resume_session",M)},children:$?`${J}ing…`:J}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{u("session_host_restart_session",M)},children:E?"Restarting…":"Restart"}),T==="live"&&(M.lifecycle==="running"||M.lifecycle==="starting"||M.lifecycle==="interrupted")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!i,onClick:()=>{u("session_host_stop_session",M)},children:F?"Stopping…":"Stop"})]})]})},M.sessionId)};return t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[t.jsx(Bt,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:"Live runtime status, next actions, and explicit recover/restart controls for hosted CLI sessions."})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[g>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{h()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${g})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${p?"bg-green-500/[0.08] text-green-500":"bg-amber-500/[0.08] text-amber-400"}`,children:p?"Managed":"Unavailable"}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{A()},disabled:x||d,children:[t.jsx(js,{size:13}),x||d?"Refreshing…":"Refresh"]})]})]}),n&&!p&&t.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(ns,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics unavailable"}),t.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),p&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:p.runtimeCount})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:P.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:p.recentRequests.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),t.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:no(p.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:cn(p.hostStartedAt)})]})]}),v&&t.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[t.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[t.jsx(ns,{size:13})," Latest host warning"]}),t.jsx("div",{className:"text-text-primary leading-relaxed",children:v.message}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[cn(v.timestamp),v.sessionId?` · ${v.sessionId}`:""]})]}),t.jsxs("div",{className:"mb-4 space-y-4",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[t.jsx(Mr,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:bs("live")}),j.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):t.jsx("div",{className:"space-y-2",children:j.map(M=>w(M,"live"))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[t.jsx(Bt,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:bs("recovery")}),P.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):t.jsx("div",{className:"space-y-2",children:P.map(M=>w(M,"recovery"))})]}),k.length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:bs("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:k.map(M=>w(M,"inactive"))})]})]}),t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),N.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:N.map(M=>{var $;const T=y.find(E=>E.sessionId===M.sessionId);return t.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-text-primary font-medium",children:(T==null?void 0:T.displayName)||(($=S.get(M.sessionId))==null?void 0:$.cliName)||M.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[M.action,M.lifecycle?` · ${M.lifecycle}`:"",M.detail?` · ${M.detail}`:"",M.error?` · ${M.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${M.success===!1?"text-red-300":"text-text-secondary"}`,children:cn(M.timestamp)})]},`${M.sessionId}:${M.timestamp}:${M.action}`)})})]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",t.jsx("span",{className:"font-mono text-text-primary",children:p.endpoint||"unknown"}),n?t.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function gp({machine:e,launchPick:s,actions:r}){const{runLaunchCliCore:n,setLaunchPick:o}=r;return t.jsx("div",{className:"fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/55 backdrop-blur-[2px]",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:t.jsxs("div",{className:"w-full max-w-md rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-5",children:[t.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),t.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),t.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?t.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(i=>t.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{o(null),n({cliType:s.cliType,workspaceId:i.id,argsStr:s.argsStr,model:s.model})},children:[t.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),t.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{o(null),n({cliType:s.cliType,useDefaultWorkspace:!0,argsStr:s.argsStr,model:s.model})},children:"Default workspace"}),t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{o(null),n({cliType:s.cliType,useHome:!0,argsStr:s.argsStr,model:s.model})},children:"Home directory"}),t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>o(null),children:"Cancel"})]})]})})}function ln({icon:e,children:s}){return t.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,t.jsx("span",{children:s})]})}function dn({children:e,className:s=""}){return t.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${s}`,children:e})}function yp({machineEntry:e,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:o,onOpenRecent:i,onOpenConversation:c}){const d=n.slice(0,6),m=r.slice(0,4),p=Ds(e,"0.8.54"),x=b=>b==="ide"?"IDE":b==="cli"?"CLI":"ACP";return t.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[d.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(ln,{icon:t.jsx(Kt,{size:13}),children:"Current Chats"}),t.jsx(dn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(b=>{const S=gn(b);return t.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>c(b),children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:st(b)}),S>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Rn(S)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:is(b)})]},b.tabKey)})})})]}),m.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(ln,{icon:t.jsx(wo,{size:13}),children:"Recent Launches"}),t.jsx(dn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:m.map(b=>t.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>i(b),children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate w-full group-hover:text-accent-primary transition-colors",children:b.label}),t.jsxs("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:[x(b.kind),b.subtitle?` · ${b.subtitle}`:""]})]},b.id))})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(ln,{icon:t.jsx(ns,{size:13}),children:"Daemon Update"}),t.jsx(dn,{className:"border-amber-500/20 bg-amber-500/5",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:p?"Daemon update required":"Version mismatch detected"}),t.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:p?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),t.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:o,children:[t.jsx(js,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function vp(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const wp={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 jp(e){const s=e instanceof Error?e.message:String(e||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function un({category:e,machine:s,machineId:r,providers:n,managedEntries:o,getIcon:i,actions:c,sendDaemonCommand:d,initialWorkspaceId:m,initialWorkspacePath:f}){const p=ws(),{handleLaunchIde:x,handleStopCli:b,handleRestartIde:S,handleStopIde:A,handleDetectIdes:u,launchingIde:h,launchingAgentType:y,addLog:l}=c,[j,P]=a.useState(null),k=a.useCallback(L=>{L&&p({pathname:"/",search:`?activeTab=${encodeURIComponent(L)}`})},[p]),g=wp[e],N=e==="ide",v=e==="acp",w=a.useMemo(()=>n.filter(L=>L.category===e&&(e==="ide"||L.installed!==!1)),[e,n]),M=a.useMemo(()=>new Map(w.map(L=>[L.type,L.displayName||L.type])),[w]),[T,$]=a.useState(""),[E,F]=a.useState(""),[D,C]=a.useState([]),[V,J]=a.useState(""),[I,R]=a.useState(""),[B,z]=a.useState([]),[Z,fe]=a.useState(!1),[Pe,ke]=a.useState(""),[ve,Q]=a.useState(!1),[xe,W]=a.useState(null),[ee,ne]=a.useState(f?"__custom__":m||s.defaultWorkspaceId||""),[oe,he]=a.useState(f||""),[te,de]=a.useState([]),[se,pe]=a.useState(!1),[ae,Ne]=a.useState(""),[ge,_]=a.useState([]),[ue,X]=a.useState(!1),[ce,Ce]=a.useState(""),Re=a.useRef(null),[me,We]=a.useState(null),Be=a.useRef("__home__"),[Ze,Ge]=a.useState("__home__"),[gt,Xe]=a.useState(!1),ot=a.useRef(0),ut=te.filter(L=>!o.some(U=>U.type===L&&bt(U.status)!=="stopped")),Ue=a.useRef({});a.useEffect(()=>{s.defaultWorkspaceId&&!ee&&ne(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),a.useEffect(()=>{if(f){ne("__custom__"),he(f);return}m&&(ne(m),he(""))},[m,f]),a.useEffect(()=>{N||T&&(w.some(L=>L.type===T)||($(""),R("")))},[w,N,T]);const He=(()=>{if(ee==="__custom__")return oe.trim();if(!ee)return"";const L=(s.workspaces||[]).find(U=>U.id===ee);return(L==null?void 0:L.path)||""})(),It=a.useCallback(L=>{const U=Ue.current[L];U&&(clearTimeout(U),delete Ue.current[L]),de(re=>re.includes(L)?re.filter(ye=>ye!==L):re)},[]),ct=a.useRef(new Set),pt=a.useCallback(async L=>{if(d){X(!0),Ce("");try{const U=await $r(d,r,L);Ne(U.path),he(U.path),_(U.directories)}catch(U){Ce(U instanceof Error?U.message:"Could not load folder")}finally{X(!1)}}},[r,d]),ft=a.useCallback(()=>{if(!d)return;ne("__custom__"),pe(!0);const L=o.map(re=>re.workspace),U=Er(s.platform,Dr(oe.trim(),He,f,L,s.defaultWorkspacePath,(s.workspaces||[]).map(re=>re.path)));pt(U)},[oe,f,pt,s.defaultWorkspacePath,s.platform,s.workspaces,o,He,d]),dt=a.useCallback(L=>{const U=String(L.workspace||"").trim();if(!U)return;const re=(s.workspaces||[]).find(ye=>ur(ye.path)===ur(U));if(re){ne(re.id),he("");return}ne("__custom__"),he(U)},[s.workspaces]),Tt=a.useCallback(L=>{const U=String(L.workspace||"").trim();if(!U)return{workspaceId:null,workspacePath:"",useHome:!0};const re=(s.workspaces||[]).find(ye=>ur(ye.path)===ur(U));return re?{workspaceId:re.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:U,useHome:!1}},[s.workspaces]),it=a.useCallback(async L=>{if(!d||!L||e!=="cli"){z([]),fe(!1),ke("");return}const U=ot.current+1;ot.current=U,fe(!0),ke("");try{const re=await d(r,"list_saved_sessions",{providerType:L,kind:"cli",limit:30});if(ot.current!==U)return;const ye=(re==null?void 0:re.result)??re;z(Array.isArray(ye==null?void 0:ye.sessions)?ye.sessions:[])}catch(re){if(ot.current!==U)return;z([]),ke(re instanceof Error?re.message:"Could not load saved sessions")}finally{ot.current===U&&fe(!1)}},[e,r,d]),q=a.useMemo(()=>{if(e!=="cli"||!T)return null;const L=M.get(T)||T;return{routeId:r,daemonId:r,providerSessionId:I||void 0,transport:"pty",mode:"chat",agentName:L,agentType:T,status:"idle",title:L,messages:[],ideType:T,workspaceName:He,displayPrimary:L,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${T}`}},[e,r,M,He,I,T]),Te=a.useCallback(L=>{if(e==="ide"||!L){C([]);return}C(Pi(r,L))},[e,r]);a.useEffect(()=>{if(R(""),Te(T),e!=="cli"||!T){z([]),ke(""),fe(!1);return}it(T)},[e,Te,it,T]),a.useEffect(()=>{if(!I)return;const L=B.find(U=>U.providerSessionId===I);L!=null&&L.canResume||R("")},[B,I]);const Ae=a.useCallback((L,U)=>{Re.current=U,Be.current=L.selectedWorkspaceKey||"__home__",Ge(L.selectedWorkspaceKey||"__home__"),We(L)},[]),Qe=a.useCallback(()=>{Re.current&&(Xe(!0),Re.current().finally(()=>{Re.current=null,Xe(!1),We(null)}))},[]),K=a.useCallback(L=>{if(!L)return;de(re=>re.includes(L)?re:[...re,L]);const U=Ue.current[L];U&&clearTimeout(U),Ue.current[L]=setTimeout(()=>{de(re=>re.includes(L)?re.filter(ye=>ye!==L):re),delete Ue.current[L]},2e4)},[]);a.useEffect(()=>{for(const U of o)bt(U.status)!=="stopped"&&(te.includes(U.type)&&!ct.current.has(U.type)&&(ct.current.add(U.type),l("info",`${M.get(U.type)||U.type} launched`,!0)),It(U.type));const L=new Set(o.filter(U=>bt(U.status)!=="stopped").map(U=>U.type));ct.current.forEach(U=>{!te.includes(U)&&!L.has(U)&&ct.current.delete(U)})},[l,It,o,te,M]),a.useEffect(()=>()=>{Object.values(Ue.current).forEach(clearTimeout),Ue.current={}},[]);const[O,G]=a.useState({}),[H,ie]=a.useState(null);a.useEffect(()=>{if(!N||!r||!d)return;(async()=>{try{const U=await d(r,"get_ide_extensions",{}),re=(U==null?void 0:U.result)||U;re!=null&&re.success&&(re!=null&&re.ideExtensions)&&G(re.ideExtensions)}catch{}})()},[N,r,d]);const Se=L=>N?et(L.type):e==="cli"?L.cliName:L.acpName,Y=N?s.detectedIdes||[]:[],le=a.useCallback(async L=>{const U=(L==null?void 0:L.type)||T,re=(L==null?void 0:L.workspacePath)??He;if(N){await x(U,re?{workspace:re}:void 0)&&K(U);return}const ye=await c.runLaunchCliCore({cliType:U,dir:L!=null&&L.workspaceId?void 0:re||void 0,workspaceId:(L==null?void 0:L.workspaceId)||void 0,useHome:(L==null?void 0:L.useHome)||!(L!=null&&L.workspaceId)&&!re,argsStr:(L==null?void 0:L.argsStr)??(E||void 0),model:(L==null?void 0:L.model)??(v&&V||void 0),resumeSessionId:(L==null?void 0:L.resumeSessionId)||!v&&e==="cli"&&U===T&&I||void 0});if(ye.success||ye.pending){const _e=(L==null?void 0:L.argsStr)??E;!N&&(_e!=null&&_e.trim())&&(Ri(r,U,_e),Te(U)),K(U),ye.success&&ye.sessionId&&k(ye.sessionId)}},[c,x,v,N,E,V,Te,K,r,k,He,I,T]),$e=()=>{var ye;const L=N?et(T):M.get(T)||T,{options:U,selectedKey:re}=ts({machine:s,currentWorkspaceId:ee&&ee!=="__custom__"?ee:null,currentWorkspacePath:He});Ae({title:Yt("start-fresh",L),description:Xt("start-fresh"),confirmLabel:Jt("start-fresh"),busyLabel:Zt("start-fresh"),workspaceOptions:U,selectedWorkspaceKey:re,details:[{label:"Mode",value:g.label},{label:"Provider",value:L},...!N&&e==="cli"&&I?[{label:"Resume",value:((ye=B.find(_e=>_e.providerSessionId===I))==null?void 0:ye.title)||I}]:[],...!N&&E.trim()?[{label:"Arguments",value:E.trim()}]:[],...v&&V.trim()?[{label:"Model",value:V.trim()}]:[]]},async()=>{const _e=U.find(Ie=>Ie.key===Be.current);_e!=null&&_e.workspaceId?(ne(_e.workspaceId),he("")):_e!=null&&_e.workspacePath?(ne("__custom__"),he(_e.workspacePath)):(ne(""),he("")),await le({workspaceId:(_e==null?void 0:_e.workspaceId)??null,workspacePath:(_e==null?void 0:_e.workspacePath)??"",useHome:!(_e!=null&&_e.workspaceId)&&!(_e!=null&&_e.workspacePath)})})},Le=L=>{N?A(L):b(L.type,L.workspace,L.id)},Oe=a.useCallback(async(L,U,re=!1)=>{if(L.mode===U){re&&L.sessionId&&k(L.sessionId);return}if(!d||!L.sessionId){re&&L.sessionId&&k(L.sessionId);return}try{await d(r,"set_cli_view_mode",{targetSessionId:L.sessionId,cliType:L.type,mode:U}),re&&k(L.sessionId)}catch(ye){jp(ye)?console.warn("Skipped CLI view mode switch:",ye instanceof Error?ye.message:String(ye)):console.error("Failed to switch CLI view mode:",ye)}},[r,k,d]),Fe=t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:ee,onChange:L=>{const U=L.target.value;if(ne(U),U==="__custom__"&&d){ft();return}U!=="__custom__"&&he("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(s.workspaces||[]).length>0?t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(s.workspaces||[]).map(L=>t.jsxs("option",{value:L.id,children:[L.id===s.defaultWorkspaceId?"⭐ ":"",Pr(L.path,L.label)]},L.id)),t.jsx("option",{value:"__custom__",children:d?"📁 Select workspace…":"✏️ Custom path…"})]}):t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),t.jsx("option",{value:"__custom__",children:d?"📁 Select workspace…":"✏️ Custom path…"})]})}),ee==="__custom__"&&(d?t.jsx("button",{type:"button",className:"px-3 py-1.5 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] hover:border-accent-primary text-text-secondary hover:text-text-primary transition-colors",onClick:ft,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:oe,onChange:L=>he(L.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),t.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:ee==="__custom__"?He?t.jsx("span",{className:"font-mono truncate block",title:He,children:He}):d?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":He?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:ee===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:He,children:He})]}):"No workspace selected. This launches in the home directory."})]});return t.jsxs("div",{children:[t.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${g.accent} relative overflow-hidden`,children:[t.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[t.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",g.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:N?Y.length>0?Y.map(L=>{const U=o.find(ze=>(ze.type||"").toLowerCase()===(L.type||"").toLowerCase()&&bt(ze.status)!=="stopped"),re=L.running||!!U,ye=!!U&&U.cdpConnected,_e=te.includes(L.type||L.id||""),Ie=T===(L.type||"");return t.jsxs("button",{onClick:()=>{if(ye&&U){const ze=U.sessionId;ze?p(`/dashboard?activeTab=${encodeURIComponent(ze)}`,{state:{openRemoteForTabKey:ze}}):p("/dashboard",{state:{openRemoteForTabKey:U.id}});return}_e||$(ze=>ze===(L.type||"")?"":L.type||"")},disabled:!!h||_e,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${ye?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Ie?"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:h&&h!==L.type?.4:1},children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i(L.type)}),re&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${ye?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:L.name||et(L.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ye?"text-green-400":_e?"text-orange-400":Ie?"text-accent-primary":"text-text-muted"}`,children:ye?"Open Session":_e?"Starting...":Ie?"Configure":"Select"})]})]},L.type)}):t.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",t.jsxs("button",{onClick:u,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[t.jsx(Cc,{size:14})," Scan System"]})]}):w.length>0?w.map(L=>{const U=T===L.type,re=te.includes(L.type),_e=!!o.find(Ie=>Ie.type===L.type&&bt(Ie.status)!=="stopped");return t.jsxs("button",{onClick:()=>$(Ie=>Ie===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 ${U?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:L.icon}),_e&&t.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:L.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${re?"text-orange-400":U?"text-accent-primary":"text-text-muted"}`,children:re?"Starting...":U?"Configure":"Select"})]})]},L.type)}):t.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",t.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),T&&(N?Y.find(L=>L.type===T):w.find(L=>L.type===T))&&t.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[t.jsx("span",{children:"Launch Settings"}),t.jsx("span",{className:"text-accent-primary font-bold",children:N?et(T):M.get(T)||T})]}),Fe,!N&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!v&&e==="cli"&&t.jsxs("div",{className:"flex flex-col gap-1.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Resume saved history"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void it(T),disabled:!T||Z,children:Z?"Loading…":"Refresh"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>{T&&(Q(!0),it(T))},disabled:!T,children:Go()})]})]}),I?(()=>{const L=B.find(U=>U.providerSessionId===I);return L?t.jsx("div",{className:"rounded-md border border-[#ffffff1a] bg-bg-primary px-3 py-2 text-[10px] text-text-muted leading-relaxed",children:t.jsxs("div",{className:"flex items-start justify-between gap-2",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-text-primary text-[11px] font-semibold truncate",children:L.title||L.providerSessionId}),t.jsx("div",{className:"font-mono break-all",children:L.providerSessionId}),t.jsx("div",{children:L.workspace||"Workspace unknown"})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:()=>R(""),children:"Clear"})]})}):null})():t.jsx("div",{className:"text-[10px] text-text-muted",children:"Start fresh, or choose saved history when you want continuity."}),Pe&&t.jsx("div",{className:"text-[10px] text-red-400",children:Pe})]}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[v&&t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),t.jsx("input",{type:"text",placeholder:"Leave empty for default",value:V,onChange:L=>J(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"})]}),t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),t.jsx("input",{type:"text",placeholder:"Optional flags...",value:E,onChange:L=>F(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"}),D.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:D.map(L=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>F(L),title:L,children:L},L))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:$e,disabled:!!y||!!h||te.includes(T),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:y===T||h===T?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",o.length+te.filter(L=>!o.some(U=>U.type===L&&bt(U.status)!=="stopped")).length,")"]}),o.length===0&&ut.length===0?t.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",g.plural," running"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[ut.map(L=>t.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:i(L)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:N?et(L):M.get(L)||L}),t.jsx("div",{className:"text-[11px] text-text-muted",children:y===L?"Launching process...":"Waiting for process and session to register..."})]})]}),t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:"var(--status-warning)"},children:"starting"})]})},`pending:${L}`)),o.map(L=>{const U=N?L:null,re=v?L:null,ye=!N&&!v?L:null,_e=bt(L.status);return t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex justify-between items-center mb-2",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:i(L.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Se(L),(U==null?void 0:U.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",U.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[t.jsx("span",{children:L.workspace||"—"}),(re==null?void 0:re.currentModel)&&t.jsxs("span",{className:"text-cyan-500",children:["🤖 ",re.currentModel]}),(re==null?void 0:re.currentPlan)&&t.jsxs("span",{style:{color:"var(--status-warning)"},children:["📋 ",re.currentPlan]}),(ye==null?void 0:ye.mode)&&t.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)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ye.runtimeKey&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),t.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",ye.runtimeKey]}),t.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var Ie;(Ie=navigator.clipboard)==null||Ie.writeText(`adhdev attach ${ye.runtimeKey}`),P(ye.runtimeKey||null),window.setTimeout(()=>{P(ze=>ze===ye.runtimeKey?null:ze)},1200)},children:j===ye.runtimeKey?"Copied":"Copy"})]}),ye.runtimeWriteOwner&&t.jsx("span",{style:{color:ye.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ye.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:vp(ye.runtimeWriteOwner)})]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${_e==="stopped"?"bg-red-500/[0.08] text-red-500":_e==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:_e}),N&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const Ie=L.sessionId;if(Ie){p(`/dashboard?activeTab=${encodeURIComponent(Ie)}`,{state:{openRemoteForTabKey:Ie}});return}p("/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:t.jsx(kt,{size:13})}),t.jsx("button",{onClick:()=>{const Ie=L.workspace||"",{options:ze,selectedKey:qe}=ts({machine:s,currentWorkspacePath:Ie});Ae({title:Yt("restart-ide",et(L.type)),description:Xt("restart-ide"),confirmLabel:Jt("restart-ide"),busyLabel:Zt("restart-ide"),workspaceOptions:ze,selectedWorkspaceKey:qe,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:et(L.type)}]},async()=>{const nt=ze.find(Pt=>Pt.key===Be.current),De=(nt==null?void 0:nt.workspacePath)??"";if(De&&De!==Ie){await le({type:L.type,workspacePath:De});return}await S(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:t.jsx(js,{size:14})})]}),v&&t.jsx("button",{onClick:()=>{const Ie=L.sessionId;Ie&&k(Ie)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"View chat",disabled:!L.sessionId,children:t.jsx(Kt,{size:14})}),ye&&_e!=="stopped"&&t.jsxs(t.Fragment,{children:[ye.mode&&t.jsx(Kn,{mode:ye.mode,onChange:Ie=>void Oe(ye,Ie,!1),compact:!0}),t.jsx("button",{onClick:()=>{const Ie=L.sessionId;Ie&&k(Ie)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"Open current view in dashboard",disabled:!L.sessionId,children:ye.mode==="chat"?t.jsx(Kt,{size:14}):t.jsx(kt,{size:13})})]}),_e==="stopped"?t.jsx("button",{onClick:()=>{const Ie=L.workspace||"",ze=N?et(L.type):Se(L),{options:qe,selectedKey:nt}=ts({machine:s,currentWorkspacePath:Ie});Ae({title:Yt("restart-stopped",ze),description:Xt("restart-stopped"),confirmLabel:Jt("restart-stopped"),busyLabel:Zt("restart-stopped"),workspaceOptions:qe,selectedWorkspaceKey:nt,details:[{label:"Mode",value:g.label},{label:"Provider",value:ze}]},async()=>{const De=qe.find(Pt=>Pt.key===Be.current);await le({type:L.type,workspaceId:(De==null?void 0:De.workspaceId)??null,workspacePath:(De==null?void 0:De.workspacePath)??"",useHome:!(De!=null&&De.workspaceId)&&!(De!=null&&De.workspacePath),model:re==null?void 0:re.currentModel})})},disabled:te.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:te.includes(L.type)?"⏳":t.jsx(_n,{size:14})}):t.jsx("button",{onClick:()=>Le(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:t.jsx(vt,{size:14})})]})]}),U&&U.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:U.aiAgents.map(Ie=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${To(Ie.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Ie.name," · ",bt(Ie.status)]},Ie.id))}),U&&(O[U.type]||[]).length>0&&d&&t.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[t.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:(O[U.type]||[]).map(Ie=>t.jsxs("button",{disabled:H===`${U.type}.${Ie.type}`,onClick:async()=>{const ze=`${U.type}.${Ie.type}`;ie(ze);try{await d(r,"set_ide_extension",{ideType:U.type,extensionType:Ie.type,enabled:!Ie.enabled}),G(qe=>({...qe,[U.type]:(qe[U.type]||[]).map(nt=>nt.type===Ie.type?{...nt,enabled:!nt.enabled}:nt)}))}catch(qe){console.error("Extension toggle failed:",qe)}finally{ie(null)}},className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-medium border transition-colors duration-150 cursor-pointer ${Ie.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Ie.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Ie.name,t.jsx("span",{className:"text-[9px] font-normal",children:Ie.enabled?"ON":"OFF"})]},Ie.type))})]})]},L.id)})]}),se&&d&&t.jsx(Br,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:ae,directories:ge,busy:ue,error:ce,confirmLabel:"Use this folder",onClose:()=>pe(!1),onNavigate:L=>{pt(L)},onConfirm:L=>{he(L),ne("__custom__"),pe(!1)}}),me&&t.jsx(qn,{title:me.title,description:me.description,details:me.details,workspaceOptions:me.workspaceOptions,selectedWorkspaceKey:Ze,onWorkspaceChange:L=>{Be.current=L,Ge(L)},confirmLabel:me.confirmLabel,busyLabel:me.busyLabel,busy:gt,onConfirm:Qe,onCancel:()=>{Re.current=null,We(null)}}),ve&&q&&t.jsx(On,{activeConv:q,ides:[],isCreatingChat:!1,isRefreshingHistory:Z,savedSessions:B,isSavedSessionsLoading:Z,isResumingSavedSessionId:xe,onClose:()=>Q(!1),onNewChat:()=>{R(""),Q(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{it(T)},onResumeSavedSession:L=>{if(!L.canResume||xe)return;const U=Tt(L);R(L.providerSessionId),dt(L),W(L.providerSessionId),Q(!1),le({type:L.providerType,workspaceId:U.workspaceId,workspacePath:U.workspacePath,useHome:U.useHome,resumeSessionId:L.providerSessionId}).finally(()=>{W(re=>re===L.providerSessionId?null:re)})}})]})}const ao=[{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 kp({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:o,acpSessions:i,actions:c,getIcon:d,initialCategory:m="ide",initialWorkspaceId:f,initialWorkspacePath:p,sendDaemonCommand:x}){var u;const[b,S]=a.useState(m);a.useEffect(()=>{S(m)},[m]);const A=a.useMemo(()=>({ide:n.length,cli:o.length,acp:i.length}),[n.length,o.length,i.length]);return t.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[t.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),t.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),t.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[t.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:ao.map(h=>t.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${b===h.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>S(h.id),children:[t.jsx("span",{children:h.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${b===h.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:A[h.id]})]},h.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(u=ao.find(h=>h.id===b))==null?void 0:u.helper})]}),b==="ide"&&t.jsx(un,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:d,actions:c,sendDaemonCommand:x,initialWorkspaceId:f,initialWorkspacePath:p}),b==="cli"&&t.jsx(un,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:o,getIcon:d,actions:c,sendDaemonCommand:x,initialWorkspaceId:f,initialWorkspacePath:p}),b==="acp"&&t.jsx(un,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:d,actions:c,sendDaemonCommand:x,initialWorkspaceId:f,initialWorkspacePath:p})]})}function Np({onNicknameSynced:e}={}){var oe,he,te,de,se,pe,ae,Ne,ge;const{id:s}=cc(),r=ws(),n=In(),{sendCommand:o}=Ct(),i=Gs(),c=Ko(),d=c.ides||[],m=c.initialLoaded??!0,f=d.find(_=>_.id===s&&_.type==="adhdev-daemon"),p=d.some(_=>_.type==="adhdev-daemon"),[x,b]=a.useState("workspace"),[S,A]=a.useState("ide"),u=a.useRef(null),[h,y]=a.useState(null),l=a.useRef("__home__"),[j,P]=a.useState("__home__"),[k,g]=a.useState(!1),N=a.useRef(null);a.useEffect(()=>{!s||!f||!(!f.workspaces||!f.availableProviders||!f.detectedIdes||!f.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,f,s]),bu(s&&x==="overview"?[s]:[],{enabled:x==="overview",intervalMs:15e3});const v=()=>{if(p){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},w=ap({machineId:s,registeredMachineId:(f==null?void 0:f.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:N});a.useEffect(()=>tt.onToast(ue=>{c.setToasts(ce=>{if(ce.some(me=>me.message===ue.message&&ue.timestamp-me.timestamp<3e3))return ce;const Re={id:ue.id,message:ue.message,type:ue.type,timestamp:ue.timestamp,targetKey:ue.targetKey,actions:ue.actions};return[...ce.slice(-4),Re]});const X=ue.duration||5e3;setTimeout(()=>c.setToasts(ce=>ce.filter(Ce=>Ce.id!==ue.id)),X)}),[c]);const M=(f==null?void 0:f.availableProviders)||[],T={};for(const _ of M)T[_.type]=_.icon;const $=_=>T[_]||"",E=f?{id:f.id,hostname:Ao(f,{fallbackId:f.id}),platform:((oe=f.machine)==null?void 0:oe.platform)||"unknown",arch:((he=f.machine)==null?void 0:he.arch)||"",cpus:((te=f.machine)==null?void 0:te.cpus)||0,totalMem:((de=f.machine)==null?void 0:de.totalMem)||0,freeMem:(se=f.machine)==null?void 0:se.freeMem,availableMem:(pe=f.machine)==null?void 0:pe.availableMem,loadavg:(ae=f.machine)==null?void 0:ae.loadavg,uptime:(Ne=f.machine)==null?void 0:Ne.uptime,release:((ge=f.machine)==null?void 0:ge.release)||"",cdpConnected:!!f.cdpConnected,machineNickname:f.machineNickname||null,p2p:f.p2p?{screenshotActive:!1,...f.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:f.detectedIdes||[],workspaces:f.workspaces||[],defaultWorkspaceId:f.defaultWorkspaceId??f.activeWorkspaceId??null,defaultWorkspacePath:f.defaultWorkspacePath??f.activeWorkspacePath??null}:null,F=d.filter(_=>_.daemonId===s&&_.type!=="adhdev-daemon").filter(_=>!Hs(_)&&!xs(_)).map(_=>({id:_.id,sessionId:_.sessionId,type:_.type,version:_.version||"",instanceId:_.instanceId||"",status:_.status,workspace:_.workspace||null,terminals:_.terminals||0,aiAgents:hl(_.aiAgents||(_.agents||[]).map(ue=>({id:ue.name,name:ue.name,status:ue.status,version:ue.version}))),activeChat:_.activeChat||null,chats:_.chats||[],childSessions:_.childSessions||[],cdpConnected:_.cdpConnected||!1,daemonId:s})),D=d.filter(_=>_.daemonId===s&&Hs(_)).map(_=>({id:_.id,sessionId:_.sessionId,type:_.type,cliName:_.cliName||_.type,status:_.status,workspace:_.workspace||"",activeChat:_.activeChat||null,providerSessionId:_.providerSessionId,mode:_.mode,runtimeKey:_.runtimeKey,runtimeDisplayName:_.runtimeDisplayName,runtimeWorkspaceLabel:_.runtimeWorkspaceLabel,runtimeWriteOwner:_.runtimeWriteOwner||null,runtimeAttachedClients:_.runtimeAttachedClients||[],daemonId:s})),C=d.filter(_=>_.daemonId===s&&xs(_)).map(_=>({id:_.id,sessionId:_.sessionId,type:_.type,acpName:_.cliName||_.type,status:_.status,workspace:_.workspace||"",activeChat:_.activeChat||null,providerSessionId:_.providerSessionId,currentModel:_.currentModel,currentPlan:_.currentPlan,daemonId:s})),V=f?jt(f,{fallbackId:s}):"",J="workspace",I=n.state,R=I==null?void 0:I.initialMachineTab,B=I==null?void 0:I.initialWorkspaceCategory,z=I==null?void 0:I.initialWorkspaceId,Z=I==null?void 0:I.initialWorkspacePath,fe=R==="ides"||R==="clis"||R==="acps"?"workspace":R||J,Pe=R==="ides"?"ide":R==="clis"?"cli":R==="acps"?"acp":B,ke=[...F.map(_=>{var ue,X,ce,Ce,Re;return{id:`ide:${_.type}:${_.workspace||""}`,label:((ue=_.activeChat)==null?void 0:ue.title)||_.type,kind:"ide",providerType:_.type,subtitle:_.workspace||void 0,workspace:_.workspace||void 0,timestamp:((Re=(Ce=(ce=(X=_.activeChat)==null?void 0:X.messages)==null?void 0:ce.at)==null?void 0:Ce.call(ce,-1))==null?void 0:Re.timestamp)||0}}),...D.map(_=>{var ue,X,ce,Ce,Re;return{id:`cli:${_.type}:${_.workspace||""}`,label:((ue=_.activeChat)==null?void 0:ue.title)||_.cliName,kind:"cli",providerType:_.type,providerSessionId:_.providerSessionId,subtitle:_.workspace||void 0,workspace:_.workspace||void 0,timestamp:((Re=(Ce=(ce=(X=_.activeChat)==null?void 0:X.messages)==null?void 0:ce.at)==null?void 0:Ce.call(ce,-1))==null?void 0:Re.timestamp)||0}}),...C.map(_=>{var ue,X,ce,Ce,Re;return{id:`acp:${_.type}:${_.workspace||""}`,label:((ue=_.activeChat)==null?void 0:ue.title)||_.acpName,kind:"acp",providerType:_.type,providerSessionId:_.providerSessionId,subtitle:_.currentModel||_.workspace||void 0,workspace:_.workspace||void 0,currentModel:_.currentModel,timestamp:((Re=(Ce=(ce=(X=_.activeChat)==null?void 0:X.messages)==null?void 0:ce.at)==null?void 0:Ce.call(ce,-1))==null?void 0:Re.timestamp)||0}})].sort((_,ue)=>ue.timestamp-_.timestamp).map(({timestamp:_,...ue})=>ue),ve=((f==null?void 0:f.recentLaunches)||[]).length>0?((f==null?void 0:f.recentLaunches)||[]).map(_=>({id:_.id,label:_.title||_.providerName||_.providerType,kind:_.kind,providerType:_.providerType,providerSessionId:_.providerSessionId,subtitle:_.currentModel||_.workspace||void 0,workspace:_.workspace,currentModel:_.currentModel})):ke,Q=a.useMemo(()=>{var ue;const _=((ue=c.connectionStates)==null?void 0:ue[s||""])||void 0;return d.filter(X=>X.daemonId===s&&X.type!=="adhdev-daemon").flatMap(X=>Hn(X,{},{connectionStates:s&&_?{[s]:_}:void 0,defaultConnectionState:_})).filter(X=>!(X.transport==="pty"&&X.mode==="terminal")).sort((X,ce)=>gn(ce)-gn(X))},[d,c.connectionStates,s]),xe=a.useCallback(_=>{const ue=_.sessionId||_.tabKey;ue&&r(`/dashboard?activeTab=${encodeURIComponent(ue)}`)},[r]),W=a.useCallback(()=>{u.current&&(g(!0),u.current().finally(()=>{u.current=null,g(!1),y(null)}))},[]),ee=a.useCallback(_=>{if(!E)return;const{options:ue,selectedKey:X}=ts({machine:E,currentWorkspacePath:_.workspace}),ce=async()=>{A(_.kind),b("workspace")};u.current=async()=>{const Ce=ue.find(We=>We.key===l.current),Re=(Ce==null?void 0:Ce.workspacePath)??null,me=(Ce==null?void 0:Ce.workspaceId)??null;if(_.kind==="ide"&&_.providerType){await w.handleLaunchIde(_.providerType,Re?{workspace:Re}:void 0);return}if((_.kind==="cli"||_.kind==="acp")&&_.providerType){await w.runLaunchCliCore({cliType:_.providerType,dir:me?void 0:Re||"",workspaceId:me||void 0,model:_.kind==="acp"?_.currentModel:void 0,resumeSessionId:_.providerSessionId});return}await ce()},l.current=X,P(X),y({title:_.kind==="ide"?Yt("restart-ide",_.label):_.providerSessionId?qo(_.label):Yt("start-fresh",_.label),description:_.kind==="ide"?Xt("restart-ide"):_.providerSessionId?Yo():Xt("start-fresh"),confirmLabel:_.kind==="ide"?Jt("restart-ide"):_.providerSessionId?Nr(!0):Jt("start-fresh"),busyLabel:_.kind==="ide"?Zt("restart-ide"):_.providerSessionId?Wn(!0):Zt("start-fresh"),workspaceOptions:ue,details:[{label:"Mode",value:_.kind.toUpperCase()},..._.providerType?[{label:"Provider",value:_.providerType}]:[]]})},[w,E]);if(a.useEffect(()=>{b(fe)},[J,fe,s]),a.useEffect(()=>{Pe&&A(Pe)},[Pe,s]),!E)return m?t.jsxs("div",{className:"p-10 text-center text-text-muted",children:[t.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),t.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),t.jsx("button",{onClick:v,className:"machine-btn-back",children:"← Back"})]}):t.jsx("div",{className:"p-10 text-center text-text-muted",children:t.jsx("p",{children:"⏳ Loading machine..."})});const ne=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(kt,{size:14})," Workspace"]}),count:F.length+D.length+C.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Bt,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ar,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ic,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Nc,{size:14})," Logs"]})}];return t.jsxs("div",{className:"flex flex-col h-full",children:[t.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[t.jsx("div",{className:"flex items-center justify-between w-full",children:t.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[t.jsx("button",{onClick:v,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),t.jsxs("div",{className:"flex flex-col min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[w.editingNickname?t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsx("input",{autoFocus:!0,value:w.nicknameInput,onChange:_=>w.setNicknameInput(_.target.value),onKeyDown:_=>{_.key==="Enter"&&w.handleSaveNickname(),_.key==="Escape"&&w.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),t.jsx("button",{onClick:w.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),t.jsx("button",{onClick:()=>w.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):t.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{w.setEditingNickname(!0),w.setNicknameInput(E.machineNickname||"")},title:"Click to set nickname",children:V}),t.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),t.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[t.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[E.platform," · ",E.arch]}),t.jsxs("span",{children:[E.cpus," cores"]}),(f==null?void 0:f.version)&&t.jsxs("span",{children:["v",f.version]}),E.p2p.available&&t.jsxs("span",{children:["P2P ",E.p2p.state==="connected"?"connected":E.p2p.state]}),E.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:E.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ne.map(_=>t.jsxs("button",{onClick:()=>b(_.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${x===_.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[_.label,_.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${x===_.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:_.count})]},_.id))})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:t.jsx("div",{className:"max-w-7xl mx-auto h-full",children:t.jsxs("div",{className:"h-full",children:[x==="workspace"&&t.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[t.jsx(yp,{machineEntry:f,providers:M,recentLaunches:ve,currentConversations:Q,onUpgradeDaemon:async()=>{try{await o(s,"daemon_upgrade",{})}catch{}},onOpenRecent:ee,onOpenConversation:xe}),t.jsx(kp,{machine:E,machineId:s,providers:M,ideSessions:F,cliSessions:D,acpSessions:C,actions:w,getIcon:$,initialCategory:S,initialWorkspaceId:z,initialWorkspacePath:Z,sendDaemonCommand:o})]}),x==="providers"&&t.jsx(mp,{machineId:s,providers:M,sendDaemonCommand:o}),x==="overview"&&t.jsx(op,{machineId:s,machine:E,ideSessions:F,cliSessions:D,acpSessions:C,actions:w,sendDaemonCommand:o}),x==="session-host"&&t.jsx(bp,{machineId:s,cliSessions:D,sendDaemonCommand:o}),x==="logs"&&t.jsx(pp,{machineId:s,sendDaemonCommand:o})]})})}),w.launchPick&&E&&t.jsx(gp,{machine:E,launchPick:w.launchPick,actions:w}),h&&t.jsx(qn,{title:h.title,description:h.description,details:h.details,workspaceOptions:h.workspaceOptions,selectedWorkspaceKey:j,onWorkspaceChange:_=>{l.current=_,P(_)},confirmLabel:h.confirmLabel,busyLabel:h.busyLabel,busy:k,onConfirm:W,onCancel:()=>{u.current=null,y(null)}}),t.jsx(Xo,{toasts:c.toasts||[],onDismiss:_=>c.setToasts(ue=>ue.filter(X=>X.id!==_)),onClickToast:_=>{_.targetKey&&r(`/dashboard?activeTab=${encodeURIComponent(_.targetKey)}`)}}),t.jsx("style",{children:`
66
+ 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",{}),$=on(T);if(!($!=null&&$.success))throw new Error(($==null?void 0:$.error)||"Duplicate prune failed");const E=$.result||{},F=Array.isArray(E.prunedSessionIds)?E.prunedSessionIds.length:0,D=typeof E.duplicateGroupCount=="number"?E.duplicateGroupCount:0;tt.showToast(`Pruned ${F} duplicate runtime(s) across ${D} group(s)`,"success"),await A()}catch(T){const $=T instanceof Error?T.message:"Duplicate prune failed";tt.showToast($,"warning"),o($)}finally{c(T=>T==="session_host_prune_duplicate_sessions"?null:T)}}},[e,A,r]),y=a.useMemo(()=>[...(p==null?void 0:p.sessions)||[]].sort((M,T)=>(T.lastActivityAt||0)-(M.lastActivityAt||0)),[p==null?void 0:p.sessions]),l=a.useMemo(()=>p!=null&&p.liveRuntimes||p!=null&&p.recoverySnapshots||p!=null&&p.inactiveRecords?{liveRuntimes:(p==null?void 0:p.liveRuntimes)||[],recoverySnapshots:(p==null?void 0:p.recoverySnapshots)||[],inactiveRecords:(p==null?void 0:p.inactiveRecords)||[]}:Li(y),[p==null?void 0:p.inactiveRecords,p==null?void 0:p.liveRuntimes,p==null?void 0:p.recoverySnapshots,y]),j=l.liveRuntimes,P=l.recoverySnapshots,k=l.inactiveRecords,g=a.useMemo(()=>hp(j),[j]),N=a.useMemo(()=>[...(p==null?void 0:p.recentTransitions)||[]].slice(-6).reverse(),[p==null?void 0:p.recentTransitions]),v=a.useMemo(()=>[...(p==null?void 0:p.recentLogs)||[]].reverse().find(M=>M.level==="warn"||M.level==="error")||null,[p==null?void 0:p.recentLogs]),w=(M,T)=>{var R;const $=i===`session_host_resume_session:${M.sessionId}`,E=i===`session_host_restart_session:${M.sessionId}`,F=i===`session_host_stop_session:${M.sessionId}`,D=Xn(M.meta),C=S.get(M.sessionId),V=M.attachedClients.length===1?"1 client":`${M.attachedClients.length} clients`,J=T==="recovery"?"Recover":"Resume",I=Di(T);return t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:M.displayName||(C==null?void 0:C.cliName)||M.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${xp(M.lifecycle)}`,children:M.lifecycle}),D&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:D})]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:"text-text-primary/90",children:M.workspaceLabel||(C==null?void 0:C.runtimeWorkspaceLabel)||M.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:M.runtimeKey}),M.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",M.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((R=M.writeOwner)==null?void 0:R.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:fp(M.writeOwner)}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[t.jsx(An,{size:11})," ",V]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",no(M.lastActivityAt)]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-sky-200",children:["Next: ",I]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[T==="recovery"&&(M.lifecycle==="interrupted"||M.lifecycle==="failed"||M.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{u("session_host_resume_session",M)},children:$?`${J}ing…`:J}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{u("session_host_restart_session",M)},children:E?"Restarting…":"Restart"}),T==="live"&&(M.lifecycle==="running"||M.lifecycle==="starting"||M.lifecycle==="interrupted")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!i,onClick:()=>{u("session_host_stop_session",M)},children:F?"Stopping…":"Stop"})]})]})},M.sessionId)};return t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[t.jsx(Bt,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:"Live runtime status, next actions, and explicit recover/restart controls for hosted CLI sessions."})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[g>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{h()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${g})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${p?"bg-green-500/[0.08] text-green-500":"bg-amber-500/[0.08] text-amber-400"}`,children:p?"Managed":"Unavailable"}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{A()},disabled:x||d,children:[t.jsx(js,{size:13}),x||d?"Refreshing…":"Refresh"]})]})]}),n&&!p&&t.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(ns,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics unavailable"}),t.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),p&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:p.runtimeCount})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:P.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:p.recentRequests.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),t.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:no(p.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:cn(p.hostStartedAt)})]})]}),v&&t.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[t.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[t.jsx(ns,{size:13})," Latest host warning"]}),t.jsx("div",{className:"text-text-primary leading-relaxed",children:v.message}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[cn(v.timestamp),v.sessionId?` · ${v.sessionId}`:""]})]}),t.jsxs("div",{className:"mb-4 space-y-4",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[t.jsx(Mr,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:bs("live")}),j.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):t.jsx("div",{className:"space-y-2",children:j.map(M=>w(M,"live"))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[t.jsx(Bt,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:bs("recovery")}),P.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):t.jsx("div",{className:"space-y-2",children:P.map(M=>w(M,"recovery"))})]}),k.length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:bs("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:k.map(M=>w(M,"inactive"))})]})]}),t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),N.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:N.map(M=>{var $;const T=y.find(E=>E.sessionId===M.sessionId);return t.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-text-primary font-medium",children:(T==null?void 0:T.displayName)||(($=S.get(M.sessionId))==null?void 0:$.cliName)||M.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[M.action,M.lifecycle?` · ${M.lifecycle}`:"",M.detail?` · ${M.detail}`:"",M.error?` · ${M.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${M.success===!1?"text-red-300":"text-text-secondary"}`,children:cn(M.timestamp)})]},`${M.sessionId}:${M.timestamp}:${M.action}`)})})]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",t.jsx("span",{className:"font-mono text-text-primary",children:p.endpoint||"unknown"}),n?t.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function gp({machine:e,launchPick:s,actions:r}){const{runLaunchCliCore:n,setLaunchPick:o}=r;return t.jsx("div",{className:"fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/55 backdrop-blur-[2px]",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:t.jsxs("div",{className:"w-full max-w-md rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-5",children:[t.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),t.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),t.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?t.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(i=>t.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{o(null),n({cliType:s.cliType,workspaceId:i.id,argsStr:s.argsStr,model:s.model})},children:[t.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),t.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{o(null),n({cliType:s.cliType,useDefaultWorkspace:!0,argsStr:s.argsStr,model:s.model})},children:"Default workspace"}),t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{o(null),n({cliType:s.cliType,useHome:!0,argsStr:s.argsStr,model:s.model})},children:"Home directory"}),t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>o(null),children:"Cancel"})]})]})})}function ln({icon:e,children:s}){return t.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,t.jsx("span",{children:s})]})}function dn({children:e,className:s=""}){return t.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${s}`,children:e})}function yp({machineEntry:e,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:o,onOpenRecent:i,onOpenConversation:c}){const d=n.slice(0,6),m=r.slice(0,4),p=Ds(e,"0.8.56"),x=b=>b==="ide"?"IDE":b==="cli"?"CLI":"ACP";return t.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[d.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(ln,{icon:t.jsx(Kt,{size:13}),children:"Current Chats"}),t.jsx(dn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(b=>{const S=gn(b);return t.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>c(b),children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:st(b)}),S>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Rn(S)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:is(b)})]},b.tabKey)})})})]}),m.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(ln,{icon:t.jsx(wo,{size:13}),children:"Recent Launches"}),t.jsx(dn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:m.map(b=>t.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>i(b),children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate w-full group-hover:text-accent-primary transition-colors",children:b.label}),t.jsxs("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:[x(b.kind),b.subtitle?` · ${b.subtitle}`:""]})]},b.id))})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(ln,{icon:t.jsx(ns,{size:13}),children:"Daemon Update"}),t.jsx(dn,{className:"border-amber-500/20 bg-amber-500/5",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:p?"Daemon update required":"Version mismatch detected"}),t.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:p?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),t.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:o,children:[t.jsx(js,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function vp(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const wp={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 jp(e){const s=e instanceof Error?e.message:String(e||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function un({category:e,machine:s,machineId:r,providers:n,managedEntries:o,getIcon:i,actions:c,sendDaemonCommand:d,initialWorkspaceId:m,initialWorkspacePath:f}){const p=ws(),{handleLaunchIde:x,handleStopCli:b,handleRestartIde:S,handleStopIde:A,handleDetectIdes:u,launchingIde:h,launchingAgentType:y,addLog:l}=c,[j,P]=a.useState(null),k=a.useCallback(L=>{L&&p({pathname:"/",search:`?activeTab=${encodeURIComponent(L)}`})},[p]),g=wp[e],N=e==="ide",v=e==="acp",w=a.useMemo(()=>n.filter(L=>L.category===e&&(e==="ide"||L.installed!==!1)),[e,n]),M=a.useMemo(()=>new Map(w.map(L=>[L.type,L.displayName||L.type])),[w]),[T,$]=a.useState(""),[E,F]=a.useState(""),[D,C]=a.useState([]),[V,J]=a.useState(""),[I,R]=a.useState(""),[B,z]=a.useState([]),[Z,fe]=a.useState(!1),[Pe,ke]=a.useState(""),[ve,Q]=a.useState(!1),[xe,W]=a.useState(null),[ee,ne]=a.useState(f?"__custom__":m||s.defaultWorkspaceId||""),[oe,he]=a.useState(f||""),[te,de]=a.useState([]),[se,pe]=a.useState(!1),[ae,Ne]=a.useState(""),[ge,_]=a.useState([]),[ue,X]=a.useState(!1),[ce,Ce]=a.useState(""),Re=a.useRef(null),[me,We]=a.useState(null),Be=a.useRef("__home__"),[Ze,Ge]=a.useState("__home__"),[gt,Xe]=a.useState(!1),ot=a.useRef(0),ut=te.filter(L=>!o.some(U=>U.type===L&&bt(U.status)!=="stopped")),Ue=a.useRef({});a.useEffect(()=>{s.defaultWorkspaceId&&!ee&&ne(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),a.useEffect(()=>{if(f){ne("__custom__"),he(f);return}m&&(ne(m),he(""))},[m,f]),a.useEffect(()=>{N||T&&(w.some(L=>L.type===T)||($(""),R("")))},[w,N,T]);const He=(()=>{if(ee==="__custom__")return oe.trim();if(!ee)return"";const L=(s.workspaces||[]).find(U=>U.id===ee);return(L==null?void 0:L.path)||""})(),It=a.useCallback(L=>{const U=Ue.current[L];U&&(clearTimeout(U),delete Ue.current[L]),de(re=>re.includes(L)?re.filter(ye=>ye!==L):re)},[]),ct=a.useRef(new Set),pt=a.useCallback(async L=>{if(d){X(!0),Ce("");try{const U=await $r(d,r,L);Ne(U.path),he(U.path),_(U.directories)}catch(U){Ce(U instanceof Error?U.message:"Could not load folder")}finally{X(!1)}}},[r,d]),ft=a.useCallback(()=>{if(!d)return;ne("__custom__"),pe(!0);const L=o.map(re=>re.workspace),U=Er(s.platform,Dr(oe.trim(),He,f,L,s.defaultWorkspacePath,(s.workspaces||[]).map(re=>re.path)));pt(U)},[oe,f,pt,s.defaultWorkspacePath,s.platform,s.workspaces,o,He,d]),dt=a.useCallback(L=>{const U=String(L.workspace||"").trim();if(!U)return;const re=(s.workspaces||[]).find(ye=>ur(ye.path)===ur(U));if(re){ne(re.id),he("");return}ne("__custom__"),he(U)},[s.workspaces]),Tt=a.useCallback(L=>{const U=String(L.workspace||"").trim();if(!U)return{workspaceId:null,workspacePath:"",useHome:!0};const re=(s.workspaces||[]).find(ye=>ur(ye.path)===ur(U));return re?{workspaceId:re.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:U,useHome:!1}},[s.workspaces]),it=a.useCallback(async L=>{if(!d||!L||e!=="cli"){z([]),fe(!1),ke("");return}const U=ot.current+1;ot.current=U,fe(!0),ke("");try{const re=await d(r,"list_saved_sessions",{providerType:L,kind:"cli",limit:30});if(ot.current!==U)return;const ye=(re==null?void 0:re.result)??re;z(Array.isArray(ye==null?void 0:ye.sessions)?ye.sessions:[])}catch(re){if(ot.current!==U)return;z([]),ke(re instanceof Error?re.message:"Could not load saved sessions")}finally{ot.current===U&&fe(!1)}},[e,r,d]),q=a.useMemo(()=>{if(e!=="cli"||!T)return null;const L=M.get(T)||T;return{routeId:r,daemonId:r,providerSessionId:I||void 0,transport:"pty",mode:"chat",agentName:L,agentType:T,status:"idle",title:L,messages:[],ideType:T,workspaceName:He,displayPrimary:L,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${T}`}},[e,r,M,He,I,T]),Te=a.useCallback(L=>{if(e==="ide"||!L){C([]);return}C(Pi(r,L))},[e,r]);a.useEffect(()=>{if(R(""),Te(T),e!=="cli"||!T){z([]),ke(""),fe(!1);return}it(T)},[e,Te,it,T]),a.useEffect(()=>{if(!I)return;const L=B.find(U=>U.providerSessionId===I);L!=null&&L.canResume||R("")},[B,I]);const Ae=a.useCallback((L,U)=>{Re.current=U,Be.current=L.selectedWorkspaceKey||"__home__",Ge(L.selectedWorkspaceKey||"__home__"),We(L)},[]),Qe=a.useCallback(()=>{Re.current&&(Xe(!0),Re.current().finally(()=>{Re.current=null,Xe(!1),We(null)}))},[]),K=a.useCallback(L=>{if(!L)return;de(re=>re.includes(L)?re:[...re,L]);const U=Ue.current[L];U&&clearTimeout(U),Ue.current[L]=setTimeout(()=>{de(re=>re.includes(L)?re.filter(ye=>ye!==L):re),delete Ue.current[L]},2e4)},[]);a.useEffect(()=>{for(const U of o)bt(U.status)!=="stopped"&&(te.includes(U.type)&&!ct.current.has(U.type)&&(ct.current.add(U.type),l("info",`${M.get(U.type)||U.type} launched`,!0)),It(U.type));const L=new Set(o.filter(U=>bt(U.status)!=="stopped").map(U=>U.type));ct.current.forEach(U=>{!te.includes(U)&&!L.has(U)&&ct.current.delete(U)})},[l,It,o,te,M]),a.useEffect(()=>()=>{Object.values(Ue.current).forEach(clearTimeout),Ue.current={}},[]);const[O,G]=a.useState({}),[H,ie]=a.useState(null);a.useEffect(()=>{if(!N||!r||!d)return;(async()=>{try{const U=await d(r,"get_ide_extensions",{}),re=(U==null?void 0:U.result)||U;re!=null&&re.success&&(re!=null&&re.ideExtensions)&&G(re.ideExtensions)}catch{}})()},[N,r,d]);const Se=L=>N?et(L.type):e==="cli"?L.cliName:L.acpName,Y=N?s.detectedIdes||[]:[],le=a.useCallback(async L=>{const U=(L==null?void 0:L.type)||T,re=(L==null?void 0:L.workspacePath)??He;if(N){await x(U,re?{workspace:re}:void 0)&&K(U);return}const ye=await c.runLaunchCliCore({cliType:U,dir:L!=null&&L.workspaceId?void 0:re||void 0,workspaceId:(L==null?void 0:L.workspaceId)||void 0,useHome:(L==null?void 0:L.useHome)||!(L!=null&&L.workspaceId)&&!re,argsStr:(L==null?void 0:L.argsStr)??(E||void 0),model:(L==null?void 0:L.model)??(v&&V||void 0),resumeSessionId:(L==null?void 0:L.resumeSessionId)||!v&&e==="cli"&&U===T&&I||void 0});if(ye.success||ye.pending){const _e=(L==null?void 0:L.argsStr)??E;!N&&(_e!=null&&_e.trim())&&(Ri(r,U,_e),Te(U)),K(U),ye.success&&ye.sessionId&&k(ye.sessionId)}},[c,x,v,N,E,V,Te,K,r,k,He,I,T]),$e=()=>{var ye;const L=N?et(T):M.get(T)||T,{options:U,selectedKey:re}=ts({machine:s,currentWorkspaceId:ee&&ee!=="__custom__"?ee:null,currentWorkspacePath:He});Ae({title:Yt("start-fresh",L),description:Xt("start-fresh"),confirmLabel:Jt("start-fresh"),busyLabel:Zt("start-fresh"),workspaceOptions:U,selectedWorkspaceKey:re,details:[{label:"Mode",value:g.label},{label:"Provider",value:L},...!N&&e==="cli"&&I?[{label:"Resume",value:((ye=B.find(_e=>_e.providerSessionId===I))==null?void 0:ye.title)||I}]:[],...!N&&E.trim()?[{label:"Arguments",value:E.trim()}]:[],...v&&V.trim()?[{label:"Model",value:V.trim()}]:[]]},async()=>{const _e=U.find(Ie=>Ie.key===Be.current);_e!=null&&_e.workspaceId?(ne(_e.workspaceId),he("")):_e!=null&&_e.workspacePath?(ne("__custom__"),he(_e.workspacePath)):(ne(""),he("")),await le({workspaceId:(_e==null?void 0:_e.workspaceId)??null,workspacePath:(_e==null?void 0:_e.workspacePath)??"",useHome:!(_e!=null&&_e.workspaceId)&&!(_e!=null&&_e.workspacePath)})})},Le=L=>{N?A(L):b(L.type,L.workspace,L.id)},Oe=a.useCallback(async(L,U,re=!1)=>{if(L.mode===U){re&&L.sessionId&&k(L.sessionId);return}if(!d||!L.sessionId){re&&L.sessionId&&k(L.sessionId);return}try{await d(r,"set_cli_view_mode",{targetSessionId:L.sessionId,cliType:L.type,mode:U}),re&&k(L.sessionId)}catch(ye){jp(ye)?console.warn("Skipped CLI view mode switch:",ye instanceof Error?ye.message:String(ye)):console.error("Failed to switch CLI view mode:",ye)}},[r,k,d]),Fe=t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:ee,onChange:L=>{const U=L.target.value;if(ne(U),U==="__custom__"&&d){ft();return}U!=="__custom__"&&he("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(s.workspaces||[]).length>0?t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(s.workspaces||[]).map(L=>t.jsxs("option",{value:L.id,children:[L.id===s.defaultWorkspaceId?"⭐ ":"",Pr(L.path,L.label)]},L.id)),t.jsx("option",{value:"__custom__",children:d?"📁 Select workspace…":"✏️ Custom path…"})]}):t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),t.jsx("option",{value:"__custom__",children:d?"📁 Select workspace…":"✏️ Custom path…"})]})}),ee==="__custom__"&&(d?t.jsx("button",{type:"button",className:"px-3 py-1.5 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] hover:border-accent-primary text-text-secondary hover:text-text-primary transition-colors",onClick:ft,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:oe,onChange:L=>he(L.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),t.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:ee==="__custom__"?He?t.jsx("span",{className:"font-mono truncate block",title:He,children:He}):d?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":He?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:ee===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:He,children:He})]}):"No workspace selected. This launches in the home directory."})]});return t.jsxs("div",{children:[t.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${g.accent} relative overflow-hidden`,children:[t.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[t.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",g.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:N?Y.length>0?Y.map(L=>{const U=o.find(ze=>(ze.type||"").toLowerCase()===(L.type||"").toLowerCase()&&bt(ze.status)!=="stopped"),re=L.running||!!U,ye=!!U&&U.cdpConnected,_e=te.includes(L.type||L.id||""),Ie=T===(L.type||"");return t.jsxs("button",{onClick:()=>{if(ye&&U){const ze=U.sessionId;ze?p(`/dashboard?activeTab=${encodeURIComponent(ze)}`,{state:{openRemoteForTabKey:ze}}):p("/dashboard",{state:{openRemoteForTabKey:U.id}});return}_e||$(ze=>ze===(L.type||"")?"":L.type||"")},disabled:!!h||_e,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${ye?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Ie?"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:h&&h!==L.type?.4:1},children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i(L.type)}),re&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${ye?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:L.name||et(L.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ye?"text-green-400":_e?"text-orange-400":Ie?"text-accent-primary":"text-text-muted"}`,children:ye?"Open Session":_e?"Starting...":Ie?"Configure":"Select"})]})]},L.type)}):t.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",t.jsxs("button",{onClick:u,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[t.jsx(Cc,{size:14})," Scan System"]})]}):w.length>0?w.map(L=>{const U=T===L.type,re=te.includes(L.type),_e=!!o.find(Ie=>Ie.type===L.type&&bt(Ie.status)!=="stopped");return t.jsxs("button",{onClick:()=>$(Ie=>Ie===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 ${U?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:L.icon}),_e&&t.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:L.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${re?"text-orange-400":U?"text-accent-primary":"text-text-muted"}`,children:re?"Starting...":U?"Configure":"Select"})]})]},L.type)}):t.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",t.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),T&&(N?Y.find(L=>L.type===T):w.find(L=>L.type===T))&&t.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[t.jsx("span",{children:"Launch Settings"}),t.jsx("span",{className:"text-accent-primary font-bold",children:N?et(T):M.get(T)||T})]}),Fe,!N&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!v&&e==="cli"&&t.jsxs("div",{className:"flex flex-col gap-1.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Resume saved history"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void it(T),disabled:!T||Z,children:Z?"Loading…":"Refresh"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>{T&&(Q(!0),it(T))},disabled:!T,children:Go()})]})]}),I?(()=>{const L=B.find(U=>U.providerSessionId===I);return L?t.jsx("div",{className:"rounded-md border border-[#ffffff1a] bg-bg-primary px-3 py-2 text-[10px] text-text-muted leading-relaxed",children:t.jsxs("div",{className:"flex items-start justify-between gap-2",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-text-primary text-[11px] font-semibold truncate",children:L.title||L.providerSessionId}),t.jsx("div",{className:"font-mono break-all",children:L.providerSessionId}),t.jsx("div",{children:L.workspace||"Workspace unknown"})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:()=>R(""),children:"Clear"})]})}):null})():t.jsx("div",{className:"text-[10px] text-text-muted",children:"Start fresh, or choose saved history when you want continuity."}),Pe&&t.jsx("div",{className:"text-[10px] text-red-400",children:Pe})]}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[v&&t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),t.jsx("input",{type:"text",placeholder:"Leave empty for default",value:V,onChange:L=>J(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"})]}),t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),t.jsx("input",{type:"text",placeholder:"Optional flags...",value:E,onChange:L=>F(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"}),D.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:D.map(L=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>F(L),title:L,children:L},L))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:$e,disabled:!!y||!!h||te.includes(T),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:y===T||h===T?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",o.length+te.filter(L=>!o.some(U=>U.type===L&&bt(U.status)!=="stopped")).length,")"]}),o.length===0&&ut.length===0?t.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",g.plural," running"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[ut.map(L=>t.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:i(L)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:N?et(L):M.get(L)||L}),t.jsx("div",{className:"text-[11px] text-text-muted",children:y===L?"Launching process...":"Waiting for process and session to register..."})]})]}),t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:"var(--status-warning)"},children:"starting"})]})},`pending:${L}`)),o.map(L=>{const U=N?L:null,re=v?L:null,ye=!N&&!v?L:null,_e=bt(L.status);return t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex justify-between items-center mb-2",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:i(L.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Se(L),(U==null?void 0:U.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",U.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[t.jsx("span",{children:L.workspace||"—"}),(re==null?void 0:re.currentModel)&&t.jsxs("span",{className:"text-cyan-500",children:["🤖 ",re.currentModel]}),(re==null?void 0:re.currentPlan)&&t.jsxs("span",{style:{color:"var(--status-warning)"},children:["📋 ",re.currentPlan]}),(ye==null?void 0:ye.mode)&&t.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)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ye.runtimeKey&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),t.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",ye.runtimeKey]}),t.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var Ie;(Ie=navigator.clipboard)==null||Ie.writeText(`adhdev attach ${ye.runtimeKey}`),P(ye.runtimeKey||null),window.setTimeout(()=>{P(ze=>ze===ye.runtimeKey?null:ze)},1200)},children:j===ye.runtimeKey?"Copied":"Copy"})]}),ye.runtimeWriteOwner&&t.jsx("span",{style:{color:ye.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ye.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:vp(ye.runtimeWriteOwner)})]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${_e==="stopped"?"bg-red-500/[0.08] text-red-500":_e==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:_e}),N&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const Ie=L.sessionId;if(Ie){p(`/dashboard?activeTab=${encodeURIComponent(Ie)}`,{state:{openRemoteForTabKey:Ie}});return}p("/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:t.jsx(kt,{size:13})}),t.jsx("button",{onClick:()=>{const Ie=L.workspace||"",{options:ze,selectedKey:qe}=ts({machine:s,currentWorkspacePath:Ie});Ae({title:Yt("restart-ide",et(L.type)),description:Xt("restart-ide"),confirmLabel:Jt("restart-ide"),busyLabel:Zt("restart-ide"),workspaceOptions:ze,selectedWorkspaceKey:qe,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:et(L.type)}]},async()=>{const nt=ze.find(Pt=>Pt.key===Be.current),De=(nt==null?void 0:nt.workspacePath)??"";if(De&&De!==Ie){await le({type:L.type,workspacePath:De});return}await S(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:t.jsx(js,{size:14})})]}),v&&t.jsx("button",{onClick:()=>{const Ie=L.sessionId;Ie&&k(Ie)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"View chat",disabled:!L.sessionId,children:t.jsx(Kt,{size:14})}),ye&&_e!=="stopped"&&t.jsxs(t.Fragment,{children:[ye.mode&&t.jsx(Kn,{mode:ye.mode,onChange:Ie=>void Oe(ye,Ie,!1),compact:!0}),t.jsx("button",{onClick:()=>{const Ie=L.sessionId;Ie&&k(Ie)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"Open current view in dashboard",disabled:!L.sessionId,children:ye.mode==="chat"?t.jsx(Kt,{size:14}):t.jsx(kt,{size:13})})]}),_e==="stopped"?t.jsx("button",{onClick:()=>{const Ie=L.workspace||"",ze=N?et(L.type):Se(L),{options:qe,selectedKey:nt}=ts({machine:s,currentWorkspacePath:Ie});Ae({title:Yt("restart-stopped",ze),description:Xt("restart-stopped"),confirmLabel:Jt("restart-stopped"),busyLabel:Zt("restart-stopped"),workspaceOptions:qe,selectedWorkspaceKey:nt,details:[{label:"Mode",value:g.label},{label:"Provider",value:ze}]},async()=>{const De=qe.find(Pt=>Pt.key===Be.current);await le({type:L.type,workspaceId:(De==null?void 0:De.workspaceId)??null,workspacePath:(De==null?void 0:De.workspacePath)??"",useHome:!(De!=null&&De.workspaceId)&&!(De!=null&&De.workspacePath),model:re==null?void 0:re.currentModel})})},disabled:te.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:te.includes(L.type)?"⏳":t.jsx(_n,{size:14})}):t.jsx("button",{onClick:()=>Le(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:t.jsx(vt,{size:14})})]})]}),U&&U.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:U.aiAgents.map(Ie=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${To(Ie.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Ie.name," · ",bt(Ie.status)]},Ie.id))}),U&&(O[U.type]||[]).length>0&&d&&t.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[t.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:(O[U.type]||[]).map(Ie=>t.jsxs("button",{disabled:H===`${U.type}.${Ie.type}`,onClick:async()=>{const ze=`${U.type}.${Ie.type}`;ie(ze);try{await d(r,"set_ide_extension",{ideType:U.type,extensionType:Ie.type,enabled:!Ie.enabled}),G(qe=>({...qe,[U.type]:(qe[U.type]||[]).map(nt=>nt.type===Ie.type?{...nt,enabled:!nt.enabled}:nt)}))}catch(qe){console.error("Extension toggle failed:",qe)}finally{ie(null)}},className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-medium border transition-colors duration-150 cursor-pointer ${Ie.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Ie.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Ie.name,t.jsx("span",{className:"text-[9px] font-normal",children:Ie.enabled?"ON":"OFF"})]},Ie.type))})]})]},L.id)})]}),se&&d&&t.jsx(Br,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:ae,directories:ge,busy:ue,error:ce,confirmLabel:"Use this folder",onClose:()=>pe(!1),onNavigate:L=>{pt(L)},onConfirm:L=>{he(L),ne("__custom__"),pe(!1)}}),me&&t.jsx(qn,{title:me.title,description:me.description,details:me.details,workspaceOptions:me.workspaceOptions,selectedWorkspaceKey:Ze,onWorkspaceChange:L=>{Be.current=L,Ge(L)},confirmLabel:me.confirmLabel,busyLabel:me.busyLabel,busy:gt,onConfirm:Qe,onCancel:()=>{Re.current=null,We(null)}}),ve&&q&&t.jsx(On,{activeConv:q,ides:[],isCreatingChat:!1,isRefreshingHistory:Z,savedSessions:B,isSavedSessionsLoading:Z,isResumingSavedSessionId:xe,onClose:()=>Q(!1),onNewChat:()=>{R(""),Q(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{it(T)},onResumeSavedSession:L=>{if(!L.canResume||xe)return;const U=Tt(L);R(L.providerSessionId),dt(L),W(L.providerSessionId),Q(!1),le({type:L.providerType,workspaceId:U.workspaceId,workspacePath:U.workspacePath,useHome:U.useHome,resumeSessionId:L.providerSessionId}).finally(()=>{W(re=>re===L.providerSessionId?null:re)})}})]})}const ao=[{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 kp({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:o,acpSessions:i,actions:c,getIcon:d,initialCategory:m="ide",initialWorkspaceId:f,initialWorkspacePath:p,sendDaemonCommand:x}){var u;const[b,S]=a.useState(m);a.useEffect(()=>{S(m)},[m]);const A=a.useMemo(()=>({ide:n.length,cli:o.length,acp:i.length}),[n.length,o.length,i.length]);return t.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[t.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),t.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),t.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[t.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:ao.map(h=>t.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${b===h.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>S(h.id),children:[t.jsx("span",{children:h.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${b===h.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:A[h.id]})]},h.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(u=ao.find(h=>h.id===b))==null?void 0:u.helper})]}),b==="ide"&&t.jsx(un,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:d,actions:c,sendDaemonCommand:x,initialWorkspaceId:f,initialWorkspacePath:p}),b==="cli"&&t.jsx(un,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:o,getIcon:d,actions:c,sendDaemonCommand:x,initialWorkspaceId:f,initialWorkspacePath:p}),b==="acp"&&t.jsx(un,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:d,actions:c,sendDaemonCommand:x,initialWorkspaceId:f,initialWorkspacePath:p})]})}function Np({onNicknameSynced:e}={}){var oe,he,te,de,se,pe,ae,Ne,ge;const{id:s}=cc(),r=ws(),n=In(),{sendCommand:o}=Ct(),i=Gs(),c=Ko(),d=c.ides||[],m=c.initialLoaded??!0,f=d.find(_=>_.id===s&&_.type==="adhdev-daemon"),p=d.some(_=>_.type==="adhdev-daemon"),[x,b]=a.useState("workspace"),[S,A]=a.useState("ide"),u=a.useRef(null),[h,y]=a.useState(null),l=a.useRef("__home__"),[j,P]=a.useState("__home__"),[k,g]=a.useState(!1),N=a.useRef(null);a.useEffect(()=>{!s||!f||!(!f.workspaces||!f.availableProviders||!f.detectedIdes||!f.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,f,s]),bu(s&&x==="overview"?[s]:[],{enabled:x==="overview",intervalMs:15e3});const v=()=>{if(p){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},w=ap({machineId:s,registeredMachineId:(f==null?void 0:f.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:N});a.useEffect(()=>tt.onToast(ue=>{c.setToasts(ce=>{if(ce.some(me=>me.message===ue.message&&ue.timestamp-me.timestamp<3e3))return ce;const Re={id:ue.id,message:ue.message,type:ue.type,timestamp:ue.timestamp,targetKey:ue.targetKey,actions:ue.actions};return[...ce.slice(-4),Re]});const X=ue.duration||5e3;setTimeout(()=>c.setToasts(ce=>ce.filter(Ce=>Ce.id!==ue.id)),X)}),[c]);const M=(f==null?void 0:f.availableProviders)||[],T={};for(const _ of M)T[_.type]=_.icon;const $=_=>T[_]||"",E=f?{id:f.id,hostname:Ao(f,{fallbackId:f.id}),platform:((oe=f.machine)==null?void 0:oe.platform)||"unknown",arch:((he=f.machine)==null?void 0:he.arch)||"",cpus:((te=f.machine)==null?void 0:te.cpus)||0,totalMem:((de=f.machine)==null?void 0:de.totalMem)||0,freeMem:(se=f.machine)==null?void 0:se.freeMem,availableMem:(pe=f.machine)==null?void 0:pe.availableMem,loadavg:(ae=f.machine)==null?void 0:ae.loadavg,uptime:(Ne=f.machine)==null?void 0:Ne.uptime,release:((ge=f.machine)==null?void 0:ge.release)||"",cdpConnected:!!f.cdpConnected,machineNickname:f.machineNickname||null,p2p:f.p2p?{screenshotActive:!1,...f.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:f.detectedIdes||[],workspaces:f.workspaces||[],defaultWorkspaceId:f.defaultWorkspaceId??f.activeWorkspaceId??null,defaultWorkspacePath:f.defaultWorkspacePath??f.activeWorkspacePath??null}:null,F=d.filter(_=>_.daemonId===s&&_.type!=="adhdev-daemon").filter(_=>!Hs(_)&&!xs(_)).map(_=>({id:_.id,sessionId:_.sessionId,type:_.type,version:_.version||"",instanceId:_.instanceId||"",status:_.status,workspace:_.workspace||null,terminals:_.terminals||0,aiAgents:hl(_.aiAgents||(_.agents||[]).map(ue=>({id:ue.name,name:ue.name,status:ue.status,version:ue.version}))),activeChat:_.activeChat||null,chats:_.chats||[],childSessions:_.childSessions||[],cdpConnected:_.cdpConnected||!1,daemonId:s})),D=d.filter(_=>_.daemonId===s&&Hs(_)).map(_=>({id:_.id,sessionId:_.sessionId,type:_.type,cliName:_.cliName||_.type,status:_.status,workspace:_.workspace||"",activeChat:_.activeChat||null,providerSessionId:_.providerSessionId,mode:_.mode,runtimeKey:_.runtimeKey,runtimeDisplayName:_.runtimeDisplayName,runtimeWorkspaceLabel:_.runtimeWorkspaceLabel,runtimeWriteOwner:_.runtimeWriteOwner||null,runtimeAttachedClients:_.runtimeAttachedClients||[],daemonId:s})),C=d.filter(_=>_.daemonId===s&&xs(_)).map(_=>({id:_.id,sessionId:_.sessionId,type:_.type,acpName:_.cliName||_.type,status:_.status,workspace:_.workspace||"",activeChat:_.activeChat||null,providerSessionId:_.providerSessionId,currentModel:_.currentModel,currentPlan:_.currentPlan,daemonId:s})),V=f?jt(f,{fallbackId:s}):"",J="workspace",I=n.state,R=I==null?void 0:I.initialMachineTab,B=I==null?void 0:I.initialWorkspaceCategory,z=I==null?void 0:I.initialWorkspaceId,Z=I==null?void 0:I.initialWorkspacePath,fe=R==="ides"||R==="clis"||R==="acps"?"workspace":R||J,Pe=R==="ides"?"ide":R==="clis"?"cli":R==="acps"?"acp":B,ke=[...F.map(_=>{var ue,X,ce,Ce,Re;return{id:`ide:${_.type}:${_.workspace||""}`,label:((ue=_.activeChat)==null?void 0:ue.title)||_.type,kind:"ide",providerType:_.type,subtitle:_.workspace||void 0,workspace:_.workspace||void 0,timestamp:((Re=(Ce=(ce=(X=_.activeChat)==null?void 0:X.messages)==null?void 0:ce.at)==null?void 0:Ce.call(ce,-1))==null?void 0:Re.timestamp)||0}}),...D.map(_=>{var ue,X,ce,Ce,Re;return{id:`cli:${_.type}:${_.workspace||""}`,label:((ue=_.activeChat)==null?void 0:ue.title)||_.cliName,kind:"cli",providerType:_.type,providerSessionId:_.providerSessionId,subtitle:_.workspace||void 0,workspace:_.workspace||void 0,timestamp:((Re=(Ce=(ce=(X=_.activeChat)==null?void 0:X.messages)==null?void 0:ce.at)==null?void 0:Ce.call(ce,-1))==null?void 0:Re.timestamp)||0}}),...C.map(_=>{var ue,X,ce,Ce,Re;return{id:`acp:${_.type}:${_.workspace||""}`,label:((ue=_.activeChat)==null?void 0:ue.title)||_.acpName,kind:"acp",providerType:_.type,providerSessionId:_.providerSessionId,subtitle:_.currentModel||_.workspace||void 0,workspace:_.workspace||void 0,currentModel:_.currentModel,timestamp:((Re=(Ce=(ce=(X=_.activeChat)==null?void 0:X.messages)==null?void 0:ce.at)==null?void 0:Ce.call(ce,-1))==null?void 0:Re.timestamp)||0}})].sort((_,ue)=>ue.timestamp-_.timestamp).map(({timestamp:_,...ue})=>ue),ve=((f==null?void 0:f.recentLaunches)||[]).length>0?((f==null?void 0:f.recentLaunches)||[]).map(_=>({id:_.id,label:_.title||_.providerName||_.providerType,kind:_.kind,providerType:_.providerType,providerSessionId:_.providerSessionId,subtitle:_.currentModel||_.workspace||void 0,workspace:_.workspace,currentModel:_.currentModel})):ke,Q=a.useMemo(()=>{var ue;const _=((ue=c.connectionStates)==null?void 0:ue[s||""])||void 0;return d.filter(X=>X.daemonId===s&&X.type!=="adhdev-daemon").flatMap(X=>Hn(X,{},{connectionStates:s&&_?{[s]:_}:void 0,defaultConnectionState:_})).filter(X=>!(X.transport==="pty"&&X.mode==="terminal")).sort((X,ce)=>gn(ce)-gn(X))},[d,c.connectionStates,s]),xe=a.useCallback(_=>{const ue=_.sessionId||_.tabKey;ue&&r(`/dashboard?activeTab=${encodeURIComponent(ue)}`)},[r]),W=a.useCallback(()=>{u.current&&(g(!0),u.current().finally(()=>{u.current=null,g(!1),y(null)}))},[]),ee=a.useCallback(_=>{if(!E)return;const{options:ue,selectedKey:X}=ts({machine:E,currentWorkspacePath:_.workspace}),ce=async()=>{A(_.kind),b("workspace")};u.current=async()=>{const Ce=ue.find(We=>We.key===l.current),Re=(Ce==null?void 0:Ce.workspacePath)??null,me=(Ce==null?void 0:Ce.workspaceId)??null;if(_.kind==="ide"&&_.providerType){await w.handleLaunchIde(_.providerType,Re?{workspace:Re}:void 0);return}if((_.kind==="cli"||_.kind==="acp")&&_.providerType){await w.runLaunchCliCore({cliType:_.providerType,dir:me?void 0:Re||"",workspaceId:me||void 0,model:_.kind==="acp"?_.currentModel:void 0,resumeSessionId:_.providerSessionId});return}await ce()},l.current=X,P(X),y({title:_.kind==="ide"?Yt("restart-ide",_.label):_.providerSessionId?qo(_.label):Yt("start-fresh",_.label),description:_.kind==="ide"?Xt("restart-ide"):_.providerSessionId?Yo():Xt("start-fresh"),confirmLabel:_.kind==="ide"?Jt("restart-ide"):_.providerSessionId?Nr(!0):Jt("start-fresh"),busyLabel:_.kind==="ide"?Zt("restart-ide"):_.providerSessionId?Wn(!0):Zt("start-fresh"),workspaceOptions:ue,details:[{label:"Mode",value:_.kind.toUpperCase()},..._.providerType?[{label:"Provider",value:_.providerType}]:[]]})},[w,E]);if(a.useEffect(()=>{b(fe)},[J,fe,s]),a.useEffect(()=>{Pe&&A(Pe)},[Pe,s]),!E)return m?t.jsxs("div",{className:"p-10 text-center text-text-muted",children:[t.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),t.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),t.jsx("button",{onClick:v,className:"machine-btn-back",children:"← Back"})]}):t.jsx("div",{className:"p-10 text-center text-text-muted",children:t.jsx("p",{children:"⏳ Loading machine..."})});const ne=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(kt,{size:14})," Workspace"]}),count:F.length+D.length+C.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Bt,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ar,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ic,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Nc,{size:14})," Logs"]})}];return t.jsxs("div",{className:"flex flex-col h-full",children:[t.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[t.jsx("div",{className:"flex items-center justify-between w-full",children:t.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[t.jsx("button",{onClick:v,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),t.jsxs("div",{className:"flex flex-col min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[w.editingNickname?t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsx("input",{autoFocus:!0,value:w.nicknameInput,onChange:_=>w.setNicknameInput(_.target.value),onKeyDown:_=>{_.key==="Enter"&&w.handleSaveNickname(),_.key==="Escape"&&w.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),t.jsx("button",{onClick:w.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),t.jsx("button",{onClick:()=>w.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):t.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{w.setEditingNickname(!0),w.setNicknameInput(E.machineNickname||"")},title:"Click to set nickname",children:V}),t.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),t.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[t.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[E.platform," · ",E.arch]}),t.jsxs("span",{children:[E.cpus," cores"]}),(f==null?void 0:f.version)&&t.jsxs("span",{children:["v",f.version]}),E.p2p.available&&t.jsxs("span",{children:["P2P ",E.p2p.state==="connected"?"connected":E.p2p.state]}),E.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:E.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ne.map(_=>t.jsxs("button",{onClick:()=>b(_.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${x===_.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[_.label,_.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${x===_.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:_.count})]},_.id))})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:t.jsx("div",{className:"max-w-7xl mx-auto h-full",children:t.jsxs("div",{className:"h-full",children:[x==="workspace"&&t.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[t.jsx(yp,{machineEntry:f,providers:M,recentLaunches:ve,currentConversations:Q,onUpgradeDaemon:async()=>{try{await o(s,"daemon_upgrade",{})}catch{}},onOpenRecent:ee,onOpenConversation:xe}),t.jsx(kp,{machine:E,machineId:s,providers:M,ideSessions:F,cliSessions:D,acpSessions:C,actions:w,getIcon:$,initialCategory:S,initialWorkspaceId:z,initialWorkspacePath:Z,sendDaemonCommand:o})]}),x==="providers"&&t.jsx(mp,{machineId:s,providers:M,sendDaemonCommand:o}),x==="overview"&&t.jsx(op,{machineId:s,machine:E,ideSessions:F,cliSessions:D,acpSessions:C,actions:w,sendDaemonCommand:o}),x==="session-host"&&t.jsx(bp,{machineId:s,cliSessions:D,sendDaemonCommand:o}),x==="logs"&&t.jsx(pp,{machineId:s,sendDaemonCommand:o})]})})}),w.launchPick&&E&&t.jsx(gp,{machine:E,launchPick:w.launchPick,actions:w}),h&&t.jsx(qn,{title:h.title,description:h.description,details:h.details,workspaceOptions:h.workspaceOptions,selectedWorkspaceKey:j,onWorkspaceChange:_=>{l.current=_,P(_)},confirmLabel:h.confirmLabel,busyLabel:h.busyLabel,busy:k,onConfirm:W,onCancel:()=>{u.current=null,y(null)}}),t.jsx(Xo,{toasts:c.toasts||[],onDismiss:_=>c.setToasts(ue=>ue.filter(X=>X.id!==_)),onClickToast:_=>{_.targetKey&&r(`/dashboard?activeTab=${encodeURIComponent(_.targetKey)}`)}}),t.jsx("style",{children:`
67
67
  @keyframes toast-in {
68
68
  from { opacity: 0; transform: translateX(40px); }
69
69
  to { opacity: 1; transform: translateX(0); }
70
70
  }
71
- `})]})}class Sp{constructor(){lt(this,"adapters",new Map);lt(this,"states",new Map);lt(this,"runtimeListeners",new Map);lt(this,"screenshotCallbacks",new Map);lt(this,"statusCallbacks",new Set)}resolveDaemonId(s){if(this.adapters.has(s))return s;if(s.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(s,r){this.adapters.set(s,r),this.states.set(s,r.connectionState)}unregister(s){this.adapters.delete(s),this.states.delete(s)}setState(s,r){this.states.set(s,r)}retryConnection(s){}get(s){const r=this.resolveDaemonId(s);return r?this.adapters.get(r):void 0}getState(s){const r=this.resolveDaemonId(s);return r&&this.states.get(r)||"disconnected"}sendData(s,r){return!1}sendPtyInput(s,r,n){return!1}sendPtyResize(s,r,n,o){return!1}onScreenshot(s,r){return this.screenshotCallbacks.set(s,r),()=>{this.screenshotCallbacks.delete(s)}}emitScreenshot(s,r){this.screenshotCallbacks.forEach(n=>n(s,r))}onStatus(s){return this.statusCallbacks.add(s),()=>{this.statusCallbacks.delete(s)}}emitStatus(s,r){this.statusCallbacks.forEach(n=>n(s,r))}emitRuntimeSnapshot(s,r,n=0,o=!1){this.emitRuntimeEvent(s,{type:"runtime_snapshot",sessionId:s,seq:n,text:r,truncated:o})}emitSessionOutput(s,r,n){!s||typeof r!="string"||!r||this.emitRuntimeEvent(s,{type:"session_output",sessionId:s,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(s,r){const n=this.runtimeListeners.get(s)||new Set;return n.add(r),this.runtimeListeners.set(s,n),()=>{const o=this.runtimeListeners.get(s);o&&(o.delete(r),o.size===0&&this.runtimeListeners.delete(s))}}async requestRuntimeSnapshot(s,r){if(!r)return;const n=await fetch(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`);if(!n.ok)return;const o=await n.json();this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof o.seq=="number"?o.seq:0,text:typeof o.text=="string"?o.text:"",truncated:!!o.truncated,cols:typeof o.cols=="number"?o.cols:void 0,rows:typeof o.rows=="number"?o.rows:void 0})}emitRuntimeEvent(s,r){var n;(n=this.runtimeListeners.get(s))==null||n.forEach(o=>o(r))}}const Dt=new Sp;function Cp(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=new URLSearchParams(window.location.search).get("token");return n?`${s}?token=${encodeURIComponent(n)}`:s}const mr=Cp(),oo=3e3,Ip=3e4;let Rt=null,Tp=0;const Tr=new Map;let Vt=null,$s=null;function io(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function _s(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function Ap(e){return e==="connected"?"connected":e}async function gr(e,s,r){const n=Bd(e,r||{}),o=Rt;if(o&&o.readyState===WebSocket.OPEN){const i=`req_${++Tp}_${Date.now()}`;return new Promise((c,d)=>{const m=setTimeout(()=>{Tr.delete(i),d(new Error(`WS command timeout: ${s}`))},3e4);Tr.set(i,{resolve:f=>{clearTimeout(m),c(f)},reject:f=>{clearTimeout(m),d(f)}}),o.send(JSON.stringify({type:"command",requestId:i,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function Nn(e,s){const r=Rt;if(!r||r.readyState!==WebSocket.OPEN)return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class Mp{constructor(s){lt(this,"daemonId");lt(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN}get connectionState(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return gr(this.daemonId,s,r)}async sendInput(s,r){return gr(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,Vt&&(clearInterval(Vt),Vt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await gr(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const o=await fetch(`data:image/jpeg;base64,${n.base64}`).then(i=>i.blob());Dt.emitScreenshot(this.daemonId,o)}}catch{}};r(),Vt=setInterval(r,2e3)}stopScreenshots(s){Vt&&(clearInterval(Vt),Vt=null)}}let St=null;function _p(e){return(!St||St.daemonId!==e)&&(St=new Mp(e)),St}function Pp({children:e}){const s=a.useRef(vr()),r=vr();s.current=r;const{setUserName:n}=rs(),o=a.useRef(n);o.current=n;const i=a.useRef(null),c=a.useRef(null),[,d]=a.useState("disconnected"),m=a.useCallback((u,h)=>{d(u),$s==null||$s(u,h)},[]),f=a.useRef(null),p=a.useRef(),x=a.useRef(oo),b=a.useRef(!0),S=a.useRef(!1),A=a.useRef("initial_connect");return a.useEffect(()=>{b.current=!0,S.current=!1;function u(){var l,j;if(!b.current||((l=f.current)==null?void 0:l.readyState)===WebSocket.OPEN||((j=f.current)==null?void 0:j.readyState)===WebSocket.CONNECTING)return;m("connecting"),console.log(`[Standalone WS] Connecting to ${mr}...`),_s("connect_attempt",{url:mr,reason:A.current,delayMs:x.current});let y;try{y=new WebSocket(mr)}catch(P){console.error("[Standalone WS] Failed to create WebSocket:",P),h();return}f.current=y,y.onopen=()=>{if(!b.current){y.close();return}m("connected"),x.current=oo,_s("open",{url:mr,reason:A.current}),Ot.resubscribeAll({sendData:Nn}),console.log("[Standalone WS] Connected")},Rt=y,y.onmessage=P=>{var k,g;try{const N=JSON.parse(P.data);if((N.type==="command_result"||N.type==="error")&&N.requestId){const v=Tr.get(N.requestId);v&&(Tr.delete(N.requestId),N.type==="error"?v.reject(new Error(((k=N.data)==null?void 0:k.message)||"Command failed")):v.resolve(N.data));return}if(N.type==="session_output"){const v=N.sessionId||N.cliId||N.cliType;v&&Dt.emitSessionOutput(v,typeof N.data=="string"?N.data:"",typeof N.seq=="number"?N.seq:void 0);return}if(N.type==="runtime_snapshot"){Dt.emitRuntimeSnapshot(N.sessionId,typeof N.text=="string"?N.text:"",typeof N.seq=="number"?N.seq:0,!!N.truncated);return}if(N.type==="topic_update"){const v=N.update;v&&Ot.publish(v);return}if(N.type==="status"||N.type==="initial_state"){const v=N.data;if(!v)return;const{injectEntries:w,markLoaded:M,getIdes:T}=s.current,$=v.instanceId||"standalone",E=T().find(C=>C.id===$),F=_p($);Dt.register($,F),Dt.setState($,"connected"),m("connected",$),Dt.emitStatus($,v);const D=jr(v,{daemonId:$,existingDaemon:E,existingEntries:T()});io("ws_status",{type:N.type,daemonId:$,sessions:(v.sessions||[]).map(C=>({id:C.id,parentId:C.parentId,providerType:C.providerType,kind:C.kind,transport:C.transport,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,title:C.title})),recentLaunches:(v.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),io("entries",{daemonId:$,entries:D.filter(C=>C.type!=="adhdev-daemon").map(C=>({id:C.id,type:C.type,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,sessionId:C.sessionId}))}),D.length>0&&w(D,{authoritativeDaemonIds:[$]}),M(),c.current!==$&&((g=i.current)==null||g.call(i),c.current=$,i.current=Ot.subscribe({sendData:Nn},$,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${$}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const V=s.current.getIdes(),J=V.find(R=>R.id===$),I=jr(C.status,{daemonId:$,existingDaemon:J,existingEntries:V,timestamp:C.timestamp});I.length>0&&s.current.injectEntries(I),C.userName&&o.current&&o.current(C.userName)}))}}catch(N){console.error("[Standalone WS] Parse error:",N)}},y.onclose=P=>{b.current&&(St==null||St.stopScreenshots(),St&&Dt.setState(St.daemonId,"disconnected"),m("disconnected"),f.current=null,A.current=`close:${P.code}${P.wasClean?":clean":":unclean"}`,_s("close",{code:P.code,reason:P.reason||"",wasClean:P.wasClean}),h())},y.onerror=P=>{S.current||!b.current||(A.current="error",_s("error",{message:P instanceof Event?"event":String(P),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",P))}}function h(){if(!b.current)return;clearTimeout(p.current);const y=x.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),_s("schedule_reconnect",{reason:A.current,delayMs:y}),p.current=setTimeout(()=>{x.current=Math.min(x.current*1.5,Ip),u()},y)}return u(),()=>{var y;b.current=!1,S.current=!0,(y=i.current)==null||y.call(i),i.current=null,c.current=null,clearTimeout(p.current),f.current&&(f.current.onerror=null,f.current.onclose=null,f.current.close(),f.current=null,Rt=null),St&&(St.stopScreenshots(),Dt.unregister(St.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function Rp({children:e}){const[s,r]=a.useState("disconnected"),[n,o]=a.useState(null);a.useEffect(()=>($s=(c,d)=>{r(c),d&&o(d)},()=>{$s=null}),[]);const i=a.useMemo(()=>{const c=s==="connected",d=Ap(s),m={};return n&&(m[n]=d),m.standalone=d,{wsStatus:s,isConnected:c,connectionStates:m}},[s,n]);return t.jsx(hc,{connectionOverrides:i,children:t.jsx(Pp,{children:e})})}const Lp=[{id:"dashboard",path:"/dashboard",icon:t.jsx(ho,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(Bt,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx(Ar,{}),label:"Settings"}];function Dp({children:e}){const s=ws(),r=In(),[n,o]=a.useState(!1),[i,c]=a.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),d=p=>{s(p),o(!1)},m=()=>{c(p=>{const x=!p;try{localStorage.setItem("sidebar-collapsed",x?"1":"0")}catch{}return x})},f=p=>`nav-item${r.pathname.startsWith(p)?" active":""} cursor-pointer ${i?"justify-center py-2.5 px-0":""}`;return t.jsxs("div",{className:`app-layout${n?" mobile-menu-open":""}${i?" sidebar-collapsed":""}`,children:[t.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:()=>o(!0),children:[t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"})]}),n&&t.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:()=>o(!1),onKeyDown:p=>p.key==="Escape"&&o(!1)}),t.jsxs("aside",{className:`sidebar ${n?"sidebar-open":""}`,children:[t.jsxs("div",{className:"sidebar-header",children:[t.jsxs("div",{className:`sidebar-logo ${i?"justify-center gap-0":""}`,children:[t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&t.jsx("span",{children:"ADHDev"})]}),t.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:()=>o(!1),children:"✕"})]}),t.jsx("nav",{className:"sidebar-nav",children:Lp.map(p=>t.jsxs("div",{className:f(p.path),id:`nav-${p.id}`,onClick:()=>d(p.path),title:i?p.label:void 0,children:[t.jsx("span",{className:"nav-icon",children:p.icon}),!i&&p.label]},p.id))}),t.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":""}`,id:"nav-docs",onClick:()=>window.open("https://docs.adhf.dev","_blank"),title:i?"Docs":void 0,children:[t.jsx("span",{className:"nav-icon",children:t.jsx(bo,{})}),!i&&t.jsxs(t.Fragment,{children:["Docs",t.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]})]}),t.jsxs("div",{className:`nav-item cursor-pointer${r.pathname==="/about"?" active":""} ${i?"justify-center py-2.5 px-0":""}`,id:"nav-about",onClick:()=>s("/about"),title:i?"About":void 0,children:[t.jsx("span",{className:"nav-icon",children:t.jsx(go,{})}),!i&&"About"]}),!i&&t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.54"]}),t.jsx(Jd,{collapsed:i}),t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:m,title:i?"Expand sidebar":"Collapse sidebar",children:[t.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&t.jsx("span",{className:"text-xs",children:"Collapse"})]})]})]}),t.jsx("main",{className:"main-content relative",children:t.jsx("div",{className:"main-content-inner",children:e})})]})}const Ep=[{icon:t.jsx(Bt,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(Kt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(yo,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(kt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(Ks,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(bo,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],$p=[{icon:t.jsx(Mc,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(ho,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(_r,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(kc,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(An,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(Sc,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Bp=[{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 Kp(){return t.jsxs(si,{icon:t.jsx(go,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:t.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","0.8.54"]}),children:[t.jsx(Mt,{children:t.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[t.jsxs("div",{className:"max-w-2xl",children:[t.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),t.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:"Keep the same dashboard experience, with the runtime fully on-device."}),t.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:"Standalone keeps the browser, daemon, screenshots, and control path on your own machine. It is the same core product shape as cloud, just without the remote networking and team layers."})]}),t.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[t.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"Docs ↗"}),t.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"GitHub ↗"}),t.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:"Try Cloud ↗"})]})]})}),t.jsx(Mt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:t.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:Ep.map(e=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[t.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[t.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:e.icon}),e.title]}),t.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),t.jsx(Mt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:t.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:Qo.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:ti.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:ei.map(e=>`${e.icon} ${e.name}`)}].map(e=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[t.jsx("div",{className:"text-[10px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),t.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(s=>t.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:s},s))})]},e.label))})}),t.jsx(Mt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:t.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:$p.map(e=>t.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[t.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[t.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:e.icon}),e.title]}),t.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),t.jsx(Mt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:t.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:t.jsxs("table",{className:"w-full text-[13px]",children:[t.jsx("thead",{children:t.jsxs("tr",{className:"bg-bg-secondary",children:[t.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),t.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),t.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),t.jsx("tbody",{children:Bp.map((e,s)=>t.jsxs("tr",{className:s%2===0?"bg-bg-glass":"bg-transparent",children:[t.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e.feature}),t.jsx("td",{className:"px-4 py-2.5 text-center",children:e.selfhost?t.jsx("span",{className:"text-emerald-500",children:"✓"}):t.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),t.jsx("td",{className:"px-4 py-2.5 text-center",children:t.jsx("span",{className:"text-emerald-500",children:"✓"})})]},e.feature))})]})})}),t.jsx(ri,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:"Cloud is optional, not required",description:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",action:t.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[t.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),t.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[t.jsx(Wc,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Wp(){const{ides:e}=rs(),s=e.find(x=>x.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=Ct(),{userName:o}=rs(),[i,c]=a.useState(o||"");a.useEffect(()=>{o!==void 0&&c(o)},[o]);const d=x=>{const b=x.target.value.trim();s!=null&&s.id&&b!==o&&n(s.id,"set_user_name",{userName:b}).catch(console.error)},[m,f]=a.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),p=x=>{f(x);try{localStorage.setItem("adhdev_sound",x?"1":"0")}catch{}};return t.jsxs(si,{icon:t.jsx(Ar,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(Fd,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost."}),t.jsx(Mt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:t.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[t.jsx("span",{className:"text-text-muted",children:"Version"}),t.jsxs("span",{className:"font-mono text-xs",children:["v","0.8.54"]}),t.jsx("span",{className:"text-text-muted",children:"Status"}),t.jsx("span",{className:s?"text-green-400":"text-yellow-400",children:s?"● Running":"○ Not connected"}),t.jsx("span",{className:"text-text-muted",children:"WebSocket"}),t.jsx("span",{className:"font-mono text-xs",children:"ws://localhost:19222"}),t.jsx("span",{className:"text-text-muted",children:"HTTP"}),t.jsx("span",{className:"font-mono text-xs",children:"http://localhost:19280"})]})}),t.jsx(Mt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?t.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):t.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(x=>t.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:`w-2 h-2 rounded-full ${x.running?"bg-green-400":"bg-text-muted/30"}`}),t.jsx("span",{className:"text-sm font-medium",children:x.name})]}),t.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:x.type})]},x.type))})}),t.jsx(Mt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(tu,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),t.jsx(Mt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode and theme.",children:t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),t.jsx(au,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),t.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose a preset or create a custom surface, accent, and chat palette for the standalone UI."}),t.jsx(pu,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),t.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose whether phones open the dashboard as a chat app first or in the full workspace layout."}),t.jsx(xu,{})]})]})}),t.jsx(Mt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(Zd,{}),t.jsx(Gt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Kc,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:m,onChange:p})]})}),t.jsx(Mt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:t.jsx("div",{className:"flex flex-col gap-3",children:t.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[t.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[t.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[t.jsx(jc,{size:16,className:"text-text-secondary"})," Display Name"]}),t.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),t.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-1.5 text-sm w-48 text-right focus:border-accent focus:outline-none transition-colors",placeholder:"Anonymous",value:i,onChange:x=>c(x.target.value),onBlur:d,onKeyDown:x=>{x.key==="Enter"&&x.currentTarget.blur()}})]})})})]})}Xd();uu();const Op=fo({baseUrl:""});function co(){const{ides:e,initialLoaded:s}=rs();if(!s)return t.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?t.jsx(fn,{to:`/machines/${r.id}`,replace:!0}):t.jsx(fn,{to:"/dashboard",replace:!0})}function Hp(){const e=a.useMemo(()=>({sendCommand:gr,sendData:Nn}),[]);return t.jsx(lc,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(yc,{client:Op,children:t.jsx(Rp,{children:t.jsx(wc,{value:e,children:t.jsx(Dp,{children:t.jsxs(dc,{children:[t.jsx(zt,{path:"/dashboard",element:t.jsx(np,{})}),t.jsx(zt,{path:"/machine",element:t.jsx(co,{})}),t.jsx(zt,{path:"/machines/:id",element:t.jsx(Np,{})}),t.jsx(zt,{path:"/machines",element:t.jsx(co,{})}),t.jsx(zt,{path:"/about",element:t.jsx(Kp,{})}),t.jsx(zt,{path:"/settings",element:t.jsx(Wp,{})}),t.jsx(zt,{path:"*",element:t.jsx(fn,{to:"/dashboard",replace:!0})})]})})})})})})}xd({connectionManager:Dt});uc(document.getElementById("root")).render(t.jsx(Hp,{}));
71
+ `})]})}class Sp{constructor(){lt(this,"adapters",new Map);lt(this,"states",new Map);lt(this,"runtimeListeners",new Map);lt(this,"screenshotCallbacks",new Map);lt(this,"statusCallbacks",new Set)}resolveDaemonId(s){if(this.adapters.has(s))return s;if(s.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(s,r){this.adapters.set(s,r),this.states.set(s,r.connectionState)}unregister(s){this.adapters.delete(s),this.states.delete(s)}setState(s,r){this.states.set(s,r)}retryConnection(s){}get(s){const r=this.resolveDaemonId(s);return r?this.adapters.get(r):void 0}getState(s){const r=this.resolveDaemonId(s);return r&&this.states.get(r)||"disconnected"}sendData(s,r){return!1}sendPtyInput(s,r,n){return!1}sendPtyResize(s,r,n,o){return!1}onScreenshot(s,r){return this.screenshotCallbacks.set(s,r),()=>{this.screenshotCallbacks.delete(s)}}emitScreenshot(s,r){this.screenshotCallbacks.forEach(n=>n(s,r))}onStatus(s){return this.statusCallbacks.add(s),()=>{this.statusCallbacks.delete(s)}}emitStatus(s,r){this.statusCallbacks.forEach(n=>n(s,r))}emitRuntimeSnapshot(s,r,n=0,o=!1){this.emitRuntimeEvent(s,{type:"runtime_snapshot",sessionId:s,seq:n,text:r,truncated:o})}emitSessionOutput(s,r,n){!s||typeof r!="string"||!r||this.emitRuntimeEvent(s,{type:"session_output",sessionId:s,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(s,r){const n=this.runtimeListeners.get(s)||new Set;return n.add(r),this.runtimeListeners.set(s,n),()=>{const o=this.runtimeListeners.get(s);o&&(o.delete(r),o.size===0&&this.runtimeListeners.delete(s))}}async requestRuntimeSnapshot(s,r){if(!r)return;const n=await fetch(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`);if(!n.ok)return;const o=await n.json();this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof o.seq=="number"?o.seq:0,text:typeof o.text=="string"?o.text:"",truncated:!!o.truncated,cols:typeof o.cols=="number"?o.cols:void 0,rows:typeof o.rows=="number"?o.rows:void 0})}emitRuntimeEvent(s,r){var n;(n=this.runtimeListeners.get(s))==null||n.forEach(o=>o(r))}}const Dt=new Sp;function Cp(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=new URLSearchParams(window.location.search).get("token");return n?`${s}?token=${encodeURIComponent(n)}`:s}const mr=Cp(),oo=3e3,Ip=3e4;let Rt=null,Tp=0;const Tr=new Map;let Vt=null,$s=null;function io(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function _s(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function Ap(e){return e==="connected"?"connected":e}async function gr(e,s,r){const n=Bd(e,r||{}),o=Rt;if(o&&o.readyState===WebSocket.OPEN){const i=`req_${++Tp}_${Date.now()}`;return new Promise((c,d)=>{const m=setTimeout(()=>{Tr.delete(i),d(new Error(`WS command timeout: ${s}`))},3e4);Tr.set(i,{resolve:f=>{clearTimeout(m),c(f)},reject:f=>{clearTimeout(m),d(f)}}),o.send(JSON.stringify({type:"command",requestId:i,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function Nn(e,s){const r=Rt;if(!r||r.readyState!==WebSocket.OPEN)return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class Mp{constructor(s){lt(this,"daemonId");lt(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN}get connectionState(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return gr(this.daemonId,s,r)}async sendInput(s,r){return gr(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,Vt&&(clearInterval(Vt),Vt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await gr(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const o=await fetch(`data:image/jpeg;base64,${n.base64}`).then(i=>i.blob());Dt.emitScreenshot(this.daemonId,o)}}catch{}};r(),Vt=setInterval(r,2e3)}stopScreenshots(s){Vt&&(clearInterval(Vt),Vt=null)}}let St=null;function _p(e){return(!St||St.daemonId!==e)&&(St=new Mp(e)),St}function Pp({children:e}){const s=a.useRef(vr()),r=vr();s.current=r;const{setUserName:n}=rs(),o=a.useRef(n);o.current=n;const i=a.useRef(null),c=a.useRef(null),[,d]=a.useState("disconnected"),m=a.useCallback((u,h)=>{d(u),$s==null||$s(u,h)},[]),f=a.useRef(null),p=a.useRef(),x=a.useRef(oo),b=a.useRef(!0),S=a.useRef(!1),A=a.useRef("initial_connect");return a.useEffect(()=>{b.current=!0,S.current=!1;function u(){var l,j;if(!b.current||((l=f.current)==null?void 0:l.readyState)===WebSocket.OPEN||((j=f.current)==null?void 0:j.readyState)===WebSocket.CONNECTING)return;m("connecting"),console.log(`[Standalone WS] Connecting to ${mr}...`),_s("connect_attempt",{url:mr,reason:A.current,delayMs:x.current});let y;try{y=new WebSocket(mr)}catch(P){console.error("[Standalone WS] Failed to create WebSocket:",P),h();return}f.current=y,y.onopen=()=>{if(!b.current){y.close();return}m("connected"),x.current=oo,_s("open",{url:mr,reason:A.current}),Ot.resubscribeAll({sendData:Nn}),console.log("[Standalone WS] Connected")},Rt=y,y.onmessage=P=>{var k,g;try{const N=JSON.parse(P.data);if((N.type==="command_result"||N.type==="error")&&N.requestId){const v=Tr.get(N.requestId);v&&(Tr.delete(N.requestId),N.type==="error"?v.reject(new Error(((k=N.data)==null?void 0:k.message)||"Command failed")):v.resolve(N.data));return}if(N.type==="session_output"){const v=N.sessionId||N.cliId||N.cliType;v&&Dt.emitSessionOutput(v,typeof N.data=="string"?N.data:"",typeof N.seq=="number"?N.seq:void 0);return}if(N.type==="runtime_snapshot"){Dt.emitRuntimeSnapshot(N.sessionId,typeof N.text=="string"?N.text:"",typeof N.seq=="number"?N.seq:0,!!N.truncated);return}if(N.type==="topic_update"){const v=N.update;v&&Ot.publish(v);return}if(N.type==="status"||N.type==="initial_state"){const v=N.data;if(!v)return;const{injectEntries:w,markLoaded:M,getIdes:T}=s.current,$=v.instanceId||"standalone",E=T().find(C=>C.id===$),F=_p($);Dt.register($,F),Dt.setState($,"connected"),m("connected",$),Dt.emitStatus($,v);const D=jr(v,{daemonId:$,existingDaemon:E,existingEntries:T()});io("ws_status",{type:N.type,daemonId:$,sessions:(v.sessions||[]).map(C=>({id:C.id,parentId:C.parentId,providerType:C.providerType,kind:C.kind,transport:C.transport,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,title:C.title})),recentLaunches:(v.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),io("entries",{daemonId:$,entries:D.filter(C=>C.type!=="adhdev-daemon").map(C=>({id:C.id,type:C.type,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,sessionId:C.sessionId}))}),D.length>0&&w(D,{authoritativeDaemonIds:[$]}),M(),c.current!==$&&((g=i.current)==null||g.call(i),c.current=$,i.current=Ot.subscribe({sendData:Nn},$,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${$}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const V=s.current.getIdes(),J=V.find(R=>R.id===$),I=jr(C.status,{daemonId:$,existingDaemon:J,existingEntries:V,timestamp:C.timestamp});I.length>0&&s.current.injectEntries(I),C.userName&&o.current&&o.current(C.userName)}))}}catch(N){console.error("[Standalone WS] Parse error:",N)}},y.onclose=P=>{b.current&&(St==null||St.stopScreenshots(),St&&Dt.setState(St.daemonId,"disconnected"),m("disconnected"),f.current=null,A.current=`close:${P.code}${P.wasClean?":clean":":unclean"}`,_s("close",{code:P.code,reason:P.reason||"",wasClean:P.wasClean}),h())},y.onerror=P=>{S.current||!b.current||(A.current="error",_s("error",{message:P instanceof Event?"event":String(P),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",P))}}function h(){if(!b.current)return;clearTimeout(p.current);const y=x.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),_s("schedule_reconnect",{reason:A.current,delayMs:y}),p.current=setTimeout(()=>{x.current=Math.min(x.current*1.5,Ip),u()},y)}return u(),()=>{var y;b.current=!1,S.current=!0,(y=i.current)==null||y.call(i),i.current=null,c.current=null,clearTimeout(p.current),f.current&&(f.current.onerror=null,f.current.onclose=null,f.current.close(),f.current=null,Rt=null),St&&(St.stopScreenshots(),Dt.unregister(St.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function Rp({children:e}){const[s,r]=a.useState("disconnected"),[n,o]=a.useState(null);a.useEffect(()=>($s=(c,d)=>{r(c),d&&o(d)},()=>{$s=null}),[]);const i=a.useMemo(()=>{const c=s==="connected",d=Ap(s),m={};return n&&(m[n]=d),m.standalone=d,{wsStatus:s,isConnected:c,connectionStates:m}},[s,n]);return t.jsx(hc,{connectionOverrides:i,children:t.jsx(Pp,{children:e})})}const Lp=[{id:"dashboard",path:"/dashboard",icon:t.jsx(ho,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(Bt,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx(Ar,{}),label:"Settings"}];function Dp({children:e}){const s=ws(),r=In(),[n,o]=a.useState(!1),[i,c]=a.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),d=p=>{s(p),o(!1)},m=()=>{c(p=>{const x=!p;try{localStorage.setItem("sidebar-collapsed",x?"1":"0")}catch{}return x})},f=p=>`nav-item${r.pathname.startsWith(p)?" active":""} cursor-pointer ${i?"justify-center py-2.5 px-0":""}`;return t.jsxs("div",{className:`app-layout${n?" mobile-menu-open":""}${i?" sidebar-collapsed":""}`,children:[t.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:()=>o(!0),children:[t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"})]}),n&&t.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:()=>o(!1),onKeyDown:p=>p.key==="Escape"&&o(!1)}),t.jsxs("aside",{className:`sidebar ${n?"sidebar-open":""}`,children:[t.jsxs("div",{className:"sidebar-header",children:[t.jsxs("div",{className:`sidebar-logo ${i?"justify-center gap-0":""}`,children:[t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&t.jsx("span",{children:"ADHDev"})]}),t.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:()=>o(!1),children:"✕"})]}),t.jsx("nav",{className:"sidebar-nav",children:Lp.map(p=>t.jsxs("div",{className:f(p.path),id:`nav-${p.id}`,onClick:()=>d(p.path),title:i?p.label:void 0,children:[t.jsx("span",{className:"nav-icon",children:p.icon}),!i&&p.label]},p.id))}),t.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":""}`,id:"nav-docs",onClick:()=>window.open("https://docs.adhf.dev","_blank"),title:i?"Docs":void 0,children:[t.jsx("span",{className:"nav-icon",children:t.jsx(bo,{})}),!i&&t.jsxs(t.Fragment,{children:["Docs",t.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]})]}),t.jsxs("div",{className:`nav-item cursor-pointer${r.pathname==="/about"?" active":""} ${i?"justify-center py-2.5 px-0":""}`,id:"nav-about",onClick:()=>s("/about"),title:i?"About":void 0,children:[t.jsx("span",{className:"nav-icon",children:t.jsx(go,{})}),!i&&"About"]}),!i&&t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.56"]}),t.jsx(Jd,{collapsed:i}),t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:m,title:i?"Expand sidebar":"Collapse sidebar",children:[t.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&t.jsx("span",{className:"text-xs",children:"Collapse"})]})]})]}),t.jsx("main",{className:"main-content relative",children:t.jsx("div",{className:"main-content-inner",children:e})})]})}const Ep=[{icon:t.jsx(Bt,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(Kt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(yo,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(kt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(Ks,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(bo,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],$p=[{icon:t.jsx(Mc,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(ho,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(_r,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(kc,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(An,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(Sc,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Bp=[{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 Kp(){return t.jsxs(si,{icon:t.jsx(go,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:t.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","0.8.56"]}),children:[t.jsx(Mt,{children:t.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[t.jsxs("div",{className:"max-w-2xl",children:[t.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),t.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:"Keep the same dashboard experience, with the runtime fully on-device."}),t.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:"Standalone keeps the browser, daemon, screenshots, and control path on your own machine. It is the same core product shape as cloud, just without the remote networking and team layers."})]}),t.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[t.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"Docs ↗"}),t.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"GitHub ↗"}),t.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:"Try Cloud ↗"})]})]})}),t.jsx(Mt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:t.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:Ep.map(e=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[t.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[t.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:e.icon}),e.title]}),t.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),t.jsx(Mt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:t.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:Qo.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:ti.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:ei.map(e=>`${e.icon} ${e.name}`)}].map(e=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[t.jsx("div",{className:"text-[10px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),t.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(s=>t.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:s},s))})]},e.label))})}),t.jsx(Mt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:t.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:$p.map(e=>t.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[t.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[t.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:e.icon}),e.title]}),t.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),t.jsx(Mt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:t.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:t.jsxs("table",{className:"w-full text-[13px]",children:[t.jsx("thead",{children:t.jsxs("tr",{className:"bg-bg-secondary",children:[t.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),t.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),t.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),t.jsx("tbody",{children:Bp.map((e,s)=>t.jsxs("tr",{className:s%2===0?"bg-bg-glass":"bg-transparent",children:[t.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e.feature}),t.jsx("td",{className:"px-4 py-2.5 text-center",children:e.selfhost?t.jsx("span",{className:"text-emerald-500",children:"✓"}):t.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),t.jsx("td",{className:"px-4 py-2.5 text-center",children:t.jsx("span",{className:"text-emerald-500",children:"✓"})})]},e.feature))})]})})}),t.jsx(ri,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:"Cloud is optional, not required",description:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",action:t.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[t.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),t.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[t.jsx(Wc,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Wp(){const{ides:e}=rs(),s=e.find(x=>x.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=Ct(),{userName:o}=rs(),[i,c]=a.useState(o||"");a.useEffect(()=>{o!==void 0&&c(o)},[o]);const d=x=>{const b=x.target.value.trim();s!=null&&s.id&&b!==o&&n(s.id,"set_user_name",{userName:b}).catch(console.error)},[m,f]=a.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),p=x=>{f(x);try{localStorage.setItem("adhdev_sound",x?"1":"0")}catch{}};return t.jsxs(si,{icon:t.jsx(Ar,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(Fd,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost."}),t.jsx(Mt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:t.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[t.jsx("span",{className:"text-text-muted",children:"Version"}),t.jsxs("span",{className:"font-mono text-xs",children:["v","0.8.56"]}),t.jsx("span",{className:"text-text-muted",children:"Status"}),t.jsx("span",{className:s?"text-green-400":"text-yellow-400",children:s?"● Running":"○ Not connected"}),t.jsx("span",{className:"text-text-muted",children:"WebSocket"}),t.jsx("span",{className:"font-mono text-xs",children:"ws://localhost:19222"}),t.jsx("span",{className:"text-text-muted",children:"HTTP"}),t.jsx("span",{className:"font-mono text-xs",children:"http://localhost:19280"})]})}),t.jsx(Mt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?t.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):t.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(x=>t.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:`w-2 h-2 rounded-full ${x.running?"bg-green-400":"bg-text-muted/30"}`}),t.jsx("span",{className:"text-sm font-medium",children:x.name})]}),t.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:x.type})]},x.type))})}),t.jsx(Mt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(tu,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),t.jsx(Mt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode and theme.",children:t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),t.jsx(au,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),t.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose a preset or create a custom surface, accent, and chat palette for the standalone UI."}),t.jsx(pu,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),t.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose whether phones open the dashboard as a chat app first or in the full workspace layout."}),t.jsx(xu,{})]})]})}),t.jsx(Mt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(Zd,{}),t.jsx(Gt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Kc,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:m,onChange:p})]})}),t.jsx(Mt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:t.jsx("div",{className:"flex flex-col gap-3",children:t.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[t.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[t.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[t.jsx(jc,{size:16,className:"text-text-secondary"})," Display Name"]}),t.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),t.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-1.5 text-sm w-48 text-right focus:border-accent focus:outline-none transition-colors",placeholder:"Anonymous",value:i,onChange:x=>c(x.target.value),onBlur:d,onKeyDown:x=>{x.key==="Enter"&&x.currentTarget.blur()}})]})})})]})}Xd();uu();const Op=fo({baseUrl:""});function co(){const{ides:e,initialLoaded:s}=rs();if(!s)return t.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?t.jsx(fn,{to:`/machines/${r.id}`,replace:!0}):t.jsx(fn,{to:"/dashboard",replace:!0})}function Hp(){const e=a.useMemo(()=>({sendCommand:gr,sendData:Nn}),[]);return t.jsx(lc,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(yc,{client:Op,children:t.jsx(Rp,{children:t.jsx(wc,{value:e,children:t.jsx(Dp,{children:t.jsxs(dc,{children:[t.jsx(zt,{path:"/dashboard",element:t.jsx(np,{})}),t.jsx(zt,{path:"/machine",element:t.jsx(co,{})}),t.jsx(zt,{path:"/machines/:id",element:t.jsx(Np,{})}),t.jsx(zt,{path:"/machines",element:t.jsx(co,{})}),t.jsx(zt,{path:"/about",element:t.jsx(Kp,{})}),t.jsx(zt,{path:"/settings",element:t.jsx(Wp,{})}),t.jsx(zt,{path:"*",element:t.jsx(fn,{to:"/dashboard",replace:!0})})]})})})})})})}xd({connectionManager:Dt});uc(document.getElementById("root")).render(t.jsx(Hp,{}));