@adhdev/daemon-standalone 0.8.50 → 0.8.51

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 Ri=Object.defineProperty;var Di=(t,s,r)=>s in t?Ri(t,s,{enumerable:!0,config
28
28
  `})]})}function vn(t,s={}){if(!t)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:o=60}=s,i=Date.now()-t,c=Math.floor(i/1e3);if(c<o)return n;const d=Math.floor(c/60);if(d<60)return`${d}m${r}`;const p=Math.floor(d/60);if(p<24)return`${p}h${r}`;const f=Math.floor(p/24);return f<7?`${f}d${r}`:new Date(t).toLocaleDateString()}const uo=t=>vn(t);function Bc(t){return{unread:!!t.unread,lastSeenAt:t.lastSeenAt||0,lastUpdated:t.lastUpdated||0,inboxBucket:t.inboxBucket||"idle",surfaceHidden:!!t.surfaceHidden}}function ys(t){const s=t.connectionState==="failed"||t.connectionState==="closed",r=t.connectionState==="connecting"||t.connectionState==="new",n=t.status==="generating",o=t.status==="waiting_approval";return{isReconnecting:s,isConnecting:r,isGenerating:n,isWaiting:o}}function Ws(t){const s=new Map,r=(n,o)=>{n&&s.set(n,{sessionId:n,...Bc(o)})};for(const n of t)if(n.type!=="adhdev-daemon"){r(n.sessionId,n);for(const o of n.childSessions||[])r(o.id,o)}return s}function Ds(t,s){if(t.sessionId){const r=s.get(t.sessionId);if(r)return r}return{sessionId:t.sessionId||t.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1}}function Es(t,s,r){const n=Ds(t,s),o=ys(t),i=o.isReconnecting,c=o.isConnecting,d=o.isGenerating,p=o.isWaiting,f=n.inboxBucket==="needs_attention"||t.status==="needs_attention"||t.status==="waiting_for_user_input"||p,m=n.inboxBucket==="working"||d,h=n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation));return{unread:h,requiresAction:f,isWorking:m,isReconnecting:i,isConnecting:c,isGenerating:d,isWaiting:p,inboxBucket:f?"needs_attention":m?"working":h?"task_complete":"idle"}}function Kc(t,s,r){return Es(t,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Wc(t,s,r){return Ds(t,r||new Map).surfaceHidden}function po({activeConv:t,onModalButton:s}){const[r,n]=a.useState(null);if(a.useEffect(()=>{n(null)},[t.modalMessage,t.status,t.connectionState]),!ys(t).isWaiting||!t.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 e.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:[t.modalMessage&&e.jsx("div",{className:"text-[11px] opacity-85 mb-1.5 whitespace-nowrap overflow-hidden text-ellipsis max-w-full",children:t.modalMessage.replace(/[\n\r]+/g," ").slice(0,120)}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[e.jsx(ts,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:t.modalButtons.map((d,p)=>{const f=c(d).toLowerCase(),m=/^(run|approve|accept|yes|allow|always)/.test(f),h=/^(reject|deny|delete|remove|abort)/.test(f),w=r===d,S=r!==null;return e.jsx("button",{onClick:()=>i(d),disabled:S,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${m?"font-extrabold":h?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${S&&!w?"opacity-40":"opacity-100"} ${S?"cursor-not-allowed":"cursor-pointer"}`,style:m?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:h?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:w?"⏳ ...":c(d)},p)})})]})]})}const It=new Map;function ta({routeId:t,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,serverModel:i,serverMode:c,acpConfigOptions:d,acpModes:p}){var je;const{sendCommand:f}=St(),m=!!(d||p),h=`${t}:${s||n}`,w=It.get(h),[S,I]=a.useState(!1),[u,b]=a.useState(!1),[v,l]=a.useState((w==null?void 0:w.models)||[]),[N,A]=a.useState((w==null?void 0:w.modes)||[]),k=G=>G?typeof G=="string"?G:typeof G=="object"?G.name||G.id||JSON.stringify(G):String(G):"",[x,g]=a.useState(k(i)),[y,j]=a.useState(k(c)),[E,R]=a.useState(!1),[K,D]=a.useState(!1),V=a.useRef(0),_=G=>G.map(oe=>typeof oe=="string"?oe:(oe==null?void 0:oe.name)||(oe==null?void 0:oe.id)||String(oe));a.useEffect(()=>{if(d){const G=d.find(oe=>oe.category==="model");if(G){const oe=_(G.options.map(be=>be.value));l(oe),G.currentValue&&g(k(G.currentValue));const W=It.get(h)||{models:[],modes:[]};It.set(h,{...W,models:oe})}}if(p&&p.length>0){const G=_(p.map(W=>W.id));A(G);const oe=It.get(h)||{models:[],modes:[]};It.set(h,{...oe,modes:G})}else if(d){const G=d.find(oe=>oe.category!=="model");if(G){const oe=_(G.options.map(be=>be.value));A(oe),G.currentValue&&j(k(G.currentValue));const W=It.get(h)||{models:[],modes:[]};It.set(h,{...W,modes:oe})}}},[d,p,h]),a.useEffect(()=>{I(!1),b(!1),g(k(i)),j(k(c));const G=It.get(h);G?(l(G.models),A(G.modes)):(l([]),A([]))},[t,n,s]),a.useEffect(()=>{i&&Date.now()>V.current&&g(k(i))},[i]),a.useEffect(()=>{c&&Date.now()>V.current&&j(k(c))},[c]);const C=a.useCallback(async(G,oe={})=>{const W={...oe,...s&&{targetSessionId:s}};return await f(t,G,W)},[t,s,f]),T=async()=>{var G,oe;if(v.length>0){I(!S);return}if(m){I(!0);return}R(!0);try{const W=await C("list_extension_models",s?{}:{agentType:n,...r?{ideType:r}:{}}),be=(W==null?void 0:W.models)||((G=W==null?void 0:W.result)==null?void 0:G.models)||[],X=_(be);l(X),W!=null&&W.current&&g(k(W.current)),(oe=W==null?void 0:W.result)!=null&&oe.current&&g(k(W.result.current));const ue=It.get(h)||{models:[],modes:[]};It.set(h,{...ue,models:X}),I(!0)}catch{}finally{R(!1)}},z=async()=>{var G,oe;if(N.length>0){b(!u);return}if(m){b(!0);return}D(!0);try{const W=await C("list_extension_modes",s?{}:{agentType:n,...r?{ideType:r}:{}}),be=(W==null?void 0:W.modes)||((G=W==null?void 0:W.result)==null?void 0:G.modes)||[],X=_(be);A(X),W!=null&&W.current&&j(k(W.current)),(oe=W==null?void 0:W.result)!=null&&oe.current&&j(k(W.result.current));const ue=It.get(h)||{models:[],modes:[]};It.set(h,{...ue,modes:X}),b(!0)}catch{}finally{D(!1)}},L=async G=>{I(!1);const oe=x;g(G),V.current=Date.now()+5e3;try{const W=m?await C("change_model",{...s?{}:{agentType:n,...r?{ideType:r}:{}},model:G}):await C("set_extension_model",{...s?{}:{agentType:n,...r?{ideType:r}:{}},model:G});if((W==null?void 0:W.success)===!1)throw new Error((W==null?void 0:W.error)||"Could not change model")}catch(W){console.warn("Model change failed",W),g(oe),V.current=0}},$=m&&!(p&&p.length>0)&&(d==null?void 0:d.some(G=>G.category!=="model")),H=$?(je=d==null?void 0:d.find(G=>G.category!=="model"))==null?void 0:je.configId:void 0,se=async G=>{b(!1);const oe=y;j(G),V.current=Date.now()+5e3;try{let W;if(m&&$&&H?W=await C("set_thought_level",{...s?{}:{agentType:n,...r?{ideType:r}:{}},configId:H,value:G}):m?W=await C("set_mode",{...s?{}:{agentType:n,...r?{ideType:r}:{}},mode:G}):W=await C("set_extension_mode",{...s?{}:{agentType:n,...r?{ideType:r}:{}},mode:G}),(W==null?void 0:W.success)===!1)throw new Error((W==null?void 0:W.error)||"Could not change mode")}catch(W){console.warn("Mode change failed",W),j(oe),V.current=0}},ie={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"}[n]||"#94a3b8";return e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1 flex-wrap text-[10px] border-t border-border-subtle bg-[var(--surface-primary)]",children:[e.jsx("span",{className:"text-[9px] font-bold tracking-wide opacity-70",style:{color:ie},children:o}),e.jsx("span",{className:"text-border-subtle text-[10px]",children:"│"}),e.jsxs("div",{className:"relative",children:[e.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:S?`${ie}55`:"transparent",border:"1px solid",color:x?"var(--text-primary)":"var(--text-muted)"},onClick:T,children:[e.jsx("span",{className:"text-[9px] opacity-60",children:"🤖"}),E?"...":x||"Model",e.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),S&&v.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>I(!1)}),e.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:[e.jsx("div",{className:"px-3 py-1.5 text-[9px] font-bold text-text-muted tracking-wider border-b border-border-subtle",children:"SELECT MODEL"}),v.map(G=>e.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:G===x?`${ie}18`:"transparent",color:G===x?ie:"var(--text-secondary)",fontWeight:G===x?600:400,borderLeft:G===x?`2px solid ${ie}`:"2px solid transparent"},onMouseEnter:oe=>{oe.currentTarget.style.background=`${ie}12`},onMouseLeave:oe=>{oe.currentTarget.style.background=G===x?`${ie}18`:"transparent"},onClick:()=>L(G),children:G},G))]})]})]}),e.jsxs("div",{className:"relative",children:[e.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:u?`${ie}55`:"transparent",border:"1px solid",color:y?"var(--text-primary)":"var(--text-muted)"},onClick:z,children:[e.jsx("span",{className:"text-[9px] opacity-60",children:$?"🧠":"⚡"}),K?"...":y||($?"Thinking":"Mode"),e.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),u&&N.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>b(!1)}),e.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:[e.jsx("div",{className:"px-3 py-1.5 text-[9px] font-bold text-text-muted tracking-wider border-b border-border-subtle",children:$?"SELECT THINKING LEVEL":"SELECT MODE"}),N.map(G=>e.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:G===y?`${ie}18`:"transparent",color:G===y?ie:"var(--text-secondary)",fontWeight:G===y?600:400,borderLeft:G===y?`2px solid ${ie}`:"2px solid transparent"},onMouseEnter:oe=>{oe.currentTarget.style.background=`${ie}12`},onMouseLeave:oe=>{oe.currentTarget.style.background=G===y?`${ie}18`:"transparent"},onClick:()=>se(G),children:G},G))]})]})]})]})}const sa=new Map,Oc={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Hc({routeId:t,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,controls:i,controlValues:c,serverModel:d,serverMode:p,acpConfigOptions:f,acpModes:m}){const{sendCommand:h}=St(),w=`${t}:${s||n}`,S=Oc[n]||"#94a3b8",[I,u]=a.useState({}),b=a.useRef(0),v={};for(const T of i||[])T.defaultValue!==void 0&&(v[T.id]=T.defaultValue);const l={...v,...d?{model:d}:{},...p?{mode:p}:{},...c||{},...Date.now()<b.current?I:{}};a.useEffect(()=>{c&&Date.now()>b.current&&u({})},[c]);const[N,A]=a.useState(sa.get(w)||{}),[k,x]=a.useState(null),[g,y]=a.useState(null),j=a.useCallback(async(T,z={})=>{const L={...z,...s&&{targetSessionId:s}};return await h(t,T,L)},[t,s,h]),E=a.useCallback(async(T,z={},L)=>{const $=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};try{const H=await j("invoke_provider_script",{...$,scriptName:T,...z});return(H==null?void 0:H.success)===!1&&L?await j(L,{...$,...z}):H}catch(H){if(!L)throw H;return await j(L,{...$,...z})}},[j,n,r]);if(!i||i.length===0)return e.jsx(ta,{routeId:t,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,serverModel:d,serverMode:p,acpConfigOptions:f,acpModes:m});const R=i.filter(T=>T.placement==="bar").sort((T,z)=>(T.order??50)-(z.order??50));if(R.length===0)return e.jsx(ta,{routeId:t,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,serverModel:d,serverMode:p,acpConfigOptions:f,acpModes:m});const K=async T=>{var L,$,H;if(k===T.id){x(null);return}if((((L=T.options)==null?void 0:L.map(se=>se.value))||N[T.id]||[]).length>0){x(T.id);return}if(T.dynamic&&T.listScript){y(T.id);try{const se=Vs(T.listScript),Y=await E(T.listScript,{},se),je=((Y==null?void 0:Y.models)||(Y==null?void 0:Y.modes)||(($=Y==null?void 0:Y.result)==null?void 0:$.models)||((H=Y==null?void 0:Y.result)==null?void 0:H.modes)||(Y==null?void 0:Y.options)||[]).map(G=>typeof G=="string"?G:(G==null?void 0:G.name)||(G==null?void 0:G.id)||(G==null?void 0:G.value)||String(G));A(G=>{const oe={...G,[T.id]:je};return sa.set(w,oe),oe}),x(T.id)}catch{}finally{y(null)}}},D=async(T,z)=>{x(null),u(L=>({...L,[T.id]:z})),b.current=Date.now()+5e3;try{if(!T.setScript)return;await E(T.setScript,{model:T.id==="model"?z:void 0,mode:T.id==="mode"?z:void 0,value:z},Vs(T.setScript))}catch{}},V=async T=>{var Y;const z=((Y=T.options)==null?void 0:Y.map(ie=>ie.value))||N[T.id]||[];if(z.length===0)return;const L=String(l[T.id]||""),H=(z.indexOf(L)+1)%z.length,se=z[H];if(typeof se=="string"){u(ie=>({...ie,[T.id]:se})),b.current=Date.now()+5e3;try{if(!T.setScript)return;await E(T.setScript,{value:se},Vs(T.setScript))}catch{}}},_=async T=>{const L=!l[T.id];u($=>({...$,[T.id]:L})),b.current=Date.now()+5e3;try{if(!T.setScript)return;await E(T.setScript,{value:L},Vs(T.setScript))}catch{}},C=async T=>{if(T.invokeScript){if(T.confirmMessage){const z=[T.confirmTitle,T.confirmMessage,T.confirmLabel].filter($=>typeof $=="string"&&$.trim().length>0);if(!window.confirm(z.join(`
29
29
 
30
30
  `)))return}try{await E(T.invokeScript)}catch{}}};return e.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:[e.jsx("span",{className:"text-[9px] font-bold tracking-wide opacity-70",style:{color:S},children:o}),e.jsx("span",{className:"text-border-subtle text-[10px]",children:"│"}),R.map(T=>{var se;const z=String(l[T.id]||""),L=k===T.id,$=g===T.id,H=((se=T.options)==null?void 0:se.map(Y=>Y.value))||N[T.id]||[];switch(T.type){case"select":return e.jsxs("div",{className:"relative",children:[e.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:L?`${S}55`:"transparent",border:"1px solid",color:z?"var(--text-primary)":"var(--text-muted)"},onClick:()=>K(T),children:[T.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:T.icon}),$?"...":z||T.label,e.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),L&&H.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>x(null)}),e.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:[e.jsx("div",{className:"px-3 py-1.5 text-[9px] font-bold text-text-muted tracking-wider border-b border-border-subtle",children:T.label.toUpperCase()}),H.map(Y=>e.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:Y===z?`${S}18`:"transparent",color:Y===z?S:"var(--text-secondary)",fontWeight:Y===z?600:400,borderLeft:Y===z?`2px solid ${S}`:"2px solid transparent"},onMouseEnter:ie=>{ie.currentTarget.style.background=`${S}12`},onMouseLeave:ie=>{ie.currentTarget.style.background=Y===z?`${S}18`:"transparent"},onClick:()=>D(T,Y),children:Y},Y))]})]})]},T.id);case"cycle":return e.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:z?"var(--text-primary)":"var(--text-muted)"},onClick:()=>V(T),title:`Click to cycle: ${H.join(" → ")}`,children:[T.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:T.icon}),z||T.label,e.jsx("span",{className:"text-[7px] opacity-50",children:"⟳"})]},T.id);case"toggle":return e.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:z?`${S}44`:"transparent",background:z?`${S}14`:"var(--surface-tertiary)",color:z?S:"var(--text-muted)"},onClick:()=>_(T),children:[T.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:T.icon}),T.label]},T.id);case"action":return e.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:()=>C(T),children:[T.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:T.icon}),T.resultDisplay==="inline"&&z?`${T.label}: ${z}`:T.label]},T.id);case"display":return e.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:z?"var(--text-primary)":"var(--text-muted)"},children:[T.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:T.icon}),z?`${T.label}: ${z}`:T.label]},T.id);default:return null}})]})}function Vs(t){return{setModel:"set_extension_model",setMode:"set_extension_mode",listModels:"list_extension_models",listModes:"list_extension_modes",setThinkingLevel:"set_thought_level"}[t]}const Uc=a.memo(function({contextKey:s,panelLabel:r,isSending:n,onSend:o,isActive:i=!0}){const c=a.useRef(null),[d,p]=a.useState("");a.useEffect(()=>{p("")},[s]),a.useEffect(()=>{var m;i&&((m=c.current)==null||m.focus())},[s,i]);const f=()=>{const m=d.trim();!m||n||(p(""),o(m))};return e.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:e.jsxs("div",{className:"flex gap-2.5 items-center",title:i?`Send message to ${r}`:void 0,children:[e.jsx("div",{className:"flex-1 relative",children:e.jsx("input",{ref:c,type:"text",placeholder:`Send message to ${r}...`,value:d,onChange:m=>p(m.target.value),onPaste:m=>{const h=m.clipboardData.getData("text");h&&p(w=>w+h),m.preventDefault()},onKeyDown:m=>{if(m.key==="Enter"){if(m.nativeEvent.isComposing){m.preventDefault();return}m.preventDefault(),f()}},onBlur:m=>{if(window.innerWidth<768){const h=m.relatedTarget;if((h==null?void 0:h.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))"}})}),e.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:e.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:e.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})});var zc=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Fc(t){var s;return(((s=t==null?void 0:t.buttons)==null?void 0:s.length)??0)>0}function xt(t,s){if(Fc(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(t||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":zc.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 mo(t){return xt(t)==="generating"}function Ze(t){return t?t.charAt(0).toUpperCase()+t.slice(1).toLowerCase():"IDE"}function Vc(t){if(t<60)return`${Math.round(t)}s`;const s=Math.floor(t/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 Rr(t){return t<1024*1024*1024?`${(t/(1024*1024)).toFixed(0)} MB`:`${(t/(1024*1024*1024)).toFixed(1)} GB`}function kr(t,s){const r=typeof s=="string"?s.trim():"";if(r)return r;const n=typeof t=="string"?t.trim():"";if(!n)return"";const o=n.replace(/[\\/]+$/,""),i=o.split(/[\\/]/).filter(Boolean);return i[i.length-1]||o}function Gc(t){if(t.length>16&&/^[a-f0-9]+$/i.test(t))return`Machine-${t.substring(0,8)}`;if(t.includes("_")){const s=t.split("_"),r=s[s.length-1];return r.length>12?`Machine-${r.substring(0,8)}`:r}return t}function qc(t){const s=t.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function Yc(t){return Gc(t.trim().replace(/\.local$/i,""))}function Xc(t){const s=t.machineNickname??t.nickname;return typeof s!="string"?null:s.trim()||null}function fo(t,s={}){var o,i;const r=[t.hostname,(o=t.machine)==null?void 0:o.hostname,(i=t.system)==null?void 0:i.hostname].find(c=>typeof c=="string"&&c.trim().length>0&&!qc(c));if(r&&r!=="Unknown")return Yc(r);const n=s.fallbackId||t.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function kt(t,s={}){return Xc(t)||fo(t,s)}function $s(t){return t.transport==="pty"}function ms(t){return t.transport==="acp"}function ra(t,s){return Ze(t)}function na(t,s,r){const n=(t||"").trim().toLowerCase();if(!n)return!0;const o=(s||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=Ze(r||"").trim().toLowerCase();return n===o||n===i||n===c}function Jc(t){return xt(t==null?void 0:t.status,{activeModal:t==null?void 0:t.activeModal})}function Zc(t){if(!Array.isArray(t)||t.length<=1)return t;const s=new Map,r=["generating","waiting_approval","connected","idle","panel_hidden"];for(const n of t){const o=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),i=s.get(o),c=xt(n.status);if(!i){s.set(o,{...n,status:c});continue}const d=r.indexOf(i.status||"idle"),p=r.indexOf(c||"idle");p>=0&&(d<0||p<d)&&s.set(o,{...n,status:c})}return Array.from(s.values())}function Qc(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){const s=Date.parse(t);if(Number.isFinite(s))return s}return 0}function el(t){var r,n;const s=(n=(r=t==null?void 0:t.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return s&&Qc(s.receivedAt)||0}function tl(t){return(t.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function rn(t){return Math.max(tl(t),el(t.activeChat))}function sl(t,s,r,n,o,i){const c=s-t;if(c!==0)return c;const d=r.localeCompare(n);return d!==0?d:o.localeCompare(i)}function wn(t,s){return sl(rn(t),rn(s),kt(t,{fallbackId:t.id}),kt(s,{fallbackId:s.id}),t.id,s.id)}const Xe=t=>t.transport==="pty",hs=(t,s)=>Xe(t)?t.mode||"terminal":"chat",xo=(t,s)=>Xe(t)&&hs(t)==="terminal",Ve=t=>t.transport==="acp";function Bt(t){return t.streamSource!=="agent-stream"}function zt(t){var s;return t.daemonId||((s=t.routeId)==null?void 0:s.split(":")[0])||t.routeId||""}function ho(t){return t.machineName||""}function mr(t){return zt(t)}function jt(t){return t.agentType||""}function jn(t){return t.hostIdeType||""}function Nr(t){return t.displayPrimary||t.agentName||"Agent"}function kn(t){return[t.displaySecondary,ho(t)].filter(Boolean)}function Os(t){return t.agentName||Ze(jt(t))}function rl(t){var s,r;if(!Bt(t)){const n=(r=(s=t.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return Ze(jn(t)||jt(t))}function Nn(t){return Bt(t)?t.sessionId:t.nativeSessionId}function aa(t){return Bt(t)?"native":t.tabKey}function nl(t){return t.sessionId}function al(t,s){if(s)return Bt(t)||!s.childSessions?s:s.childSessions.find(r=>r.id===t.sessionId||r.providerType===t.agentType)||s}function ol(t,s){const r=jt(t),n=Bt(t)?s!=null&&s.type?Ze(s.type):Ze(jn(t)||r):Os(t);return{isNativeConversation:Bt(t),isCli:Xe(t),isAcp:Ve(t),isCliTerminal:xo(t),providerType:r,displayLabel:n,targetEntry:al(t,s)}}function bo({conversation:t,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:o=!0}){const i=bs(),c=zt(t),d=ho(t),p=t.transport==="cdp-page"||t.transport==="cdp-webview",f=t.streamSource==="agent-stream"&&!!t.agentName,m=!f&&(t.transport==="pty"||t.transport==="acp"),h=Os(t),w=rl(t),S=a.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),I=a.useCallback(()=>{if(r){r();return}const u=Nn(t);u&&i(`/dashboard?activeTab=${encodeURIComponent(u)}`)},[t,i,r]);return e.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[p&&(o?e.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:I,title:w,children:[e.jsx(Nt,{size:12}),e.jsx("span",{children:w})]}):e.jsxs("span",{className:"conversation-meta-chip",title:w,children:[e.jsx(Nt,{size:12}),e.jsx("span",{children:w})]})),f&&e.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[e.jsx(Rs,{size:12}),e.jsx("span",{children:h})]}),m&&e.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[e.jsx(Rs,{size:12}),e.jsx("span",{children:h})]}),d&&(o?e.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:S,title:d,children:[e.jsx(Ut,{size:12}),e.jsx("span",{children:d})]}):e.jsxs("span",{className:"conversation-meta-chip",title:d,children:[e.jsx(Ut,{size:12}),e.jsx("span",{children:d})]}))]})}function oa(t,s){return`${t}:${s}`}function il(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Gs(t,s){il()&&console.debug(`[subscription-manager] ${t}`,s)}class cl{constructor(){nt(this,"active",new Map)}subscribe(s,r,n,o){var f;const i=oa(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 m={daemonId:r,request:n,handlers:new Set([o])};this.active.set(i,m),Gs("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((f=s.sendData)==null?void 0:f.call(s,r,n))??!1}const p=()=>{var w;const m=this.active.get(i);if(!m||(m.handlers.delete(o),m.handlers.size>0))return;this.active.delete(i);const h={type:"unsubscribe",topic:n.topic,key:n.key};Gs("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(w=s.sendData)==null||w.call(s,r,h)};return p.initialSendAccepted=d,p}publish(s){const r=oa(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,Qt.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),Qt.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;Gs("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);Gs("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 cl;function ll(t,s){const r=new Map;for(const n of t||[])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 qs(t,s){return{...t,parentId:t.parentId??(s==null?void 0:s.parentSessionId)??null,providerName:t.providerName??(s==null?void 0:s.cliName)??(s==null?void 0:s.type)??t.providerType,workspace:t.workspace??(s==null?void 0:s.workspace)??null,capabilities:t.capabilities??(s==null?void 0:s.sessionCapabilities)??[],cdpConnected:t.cdpConnected??(s==null?void 0:s.cdpConnected),currentModel:t.currentModel??(s==null?void 0:s.currentModel),currentPlan:t.currentPlan??(s==null?void 0:s.currentPlan),currentAutoApprove:t.currentAutoApprove??(s==null?void 0:s.currentAutoApprove),controlValues:t.controlValues??(s==null?void 0:s.controlValues),providerControls:t.providerControls??(s==null?void 0:s.providerControls),acpConfigOptions:t.acpConfigOptions??(s==null?void 0:s.acpConfigOptions),acpModes:t.acpModes??(s==null?void 0:s.acpModes),runtimeWriteOwner:t.runtimeWriteOwner??(s==null?void 0:s.runtimeWriteOwner),runtimeAttachedClients:t.runtimeAttachedClients??(s==null?void 0:s.runtimeAttachedClients),lastMessagePreview:t.lastMessagePreview??(s==null?void 0:s.lastMessagePreview),lastMessageRole:t.lastMessageRole??(s==null?void 0:s.lastMessageRole),lastMessageAt:t.lastMessageAt??(s==null?void 0:s.lastMessageAt),lastMessageHash:t.lastMessageHash??(s==null?void 0:s.lastMessageHash)}}function dl(t){const s=[],r=new Map;for(const n of t)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 fr(t,s){const r=[],{daemonId:n,existingDaemon:o,existingEntries:i,timestamp:c}=s,d=c||t.timestamp||Date.now(),p=t.sessions||[],{topLevel:f,childrenByParent:m}=dl(p),h=ll(i,n),w=t.machine?{...(o==null?void 0:o.machine)||{},...t.machine}:o==null?void 0:o.machine,S=f.filter(b=>b.kind==="workspace"&&b.transport==="cdp-page"),I=f.filter(b=>b.kind==="agent"&&b.transport==="pty"),u=f.filter(b=>b.kind==="agent"&&b.transport==="acp");r.push({...o||{},id:n,type:"adhdev-daemon",status:"online",timestamp:d,...t.version&&{version:t.version},...w&&{machine:w,platform:w.platform},...t.instanceId&&{instanceId:t.instanceId},...t.machineNickname!==void 0&&{machineNickname:t.machineNickname},...t.p2p&&{p2p:t.p2p},...t.workspaces&&{workspaces:t.workspaces},...t.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:t.defaultWorkspaceId},...t.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:t.defaultWorkspacePath},...t.terminalSizingMode!==void 0&&{terminalSizingMode:t.terminalSizingMode},...t.recentLaunches&&{recentLaunches:t.recentLaunches},...t.terminalBackend&&{terminalBackend:t.terminalBackend},...t.detectedIdes&&{detectedIdes:t.detectedIdes},...t.availableProviders&&{availableProviders:t.availableProviders},cdpConnected:S.some(b=>!!b.cdpConnected)});for(const b of S){const v=h.get(b.id),l=qs(b,v),N=(m.get(b.id)||[]).map(A=>qs(A,h.get(A.id)));r.push({id:`${n}:ide:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(v==null?void 0:v.providerSessionId),parentSessionId:l.parentId,sessionKind:l.kind,transport:l.transport,sessionCapabilities:l.capabilities,type:l.providerType,status:l.cdpConnected?"online":"detected",daemonId:n,instanceId:b.id,workspace:l.workspace,terminals:0,childSessions:N,agents:N.map(A=>({id:A.id,name:A.providerName||A.providerType,type:A.providerType,status:A.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 b of I){const v=h.get(b.id),l=qs(b,v);r.push({id:`${n}:cli:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(v==null?void 0:v.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:b.id,cliName:l.providerName||l.providerType,mode:l.mode||(v==null?void 0:v.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 b of u){const v=h.get(b.id),l=qs(b,v);r.push({id:`${n}:acp:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(v==null?void 0:v.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:b.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 Dr=new Map,Er=new Map,$r=new Set,Is=new Map,ul=1200;function pl(t){if(!t||typeof t!="object")return null;const s=t,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 ia(t,s){const r=Is.get(t);!r||r.size===0||(Is.delete(t),r.forEach(n=>n(s)))}function ml(t,s){return new Promise(r=>{const n=Is.get(t)||new Set;Is.set(t,n);const o=c=>{clearTimeout(i),n.delete(o),n.size===0&&Is.delete(t),r(c)},i=setTimeout(()=>o(!1),s);n.add(o)})}function Hs(){const{sendCommand:t,sendData:s}=St(),{injectEntries:r,getIdes:n}=pr();return a.useCallback(async(o,i)=>{if(!o)return;const c=(i==null?void 0:i.minFreshMs)??6e4,d=Er.get(o)||0;if(!(i!=null&&i.force)&&$r.has(o)&&d>0||!(i!=null&&i.force)&&d>0&&Date.now()-d<c)return;const p=Dr.get(o);if(p)return p;const f=(async()=>{if(s&&!$r.has(o)&&($r.add(o),Ot.subscribe({sendData:s},o,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${o}`,params:{includeSessions:!0}},u=>{const b=n(),v=b.find(N=>N.id===o),l=fr(u.status,{daemonId:o,existingDaemon:v,existingEntries:b,timestamp:u.timestamp});l.length>0&&r(l),Er.set(o,Date.now()),ia(o,!0)}),!(i!=null&&i.force)&&await ml(o,ul)))return;const m=await t(o,"get_status_metadata"),h=pl(m);if(!h)return;const w=n(),S=w.find(u=>u.id===o),I=fr(h,{daemonId:o,existingDaemon:S,existingEntries:w,timestamp:h.timestamp||Date.now()});I.length>0&&r(I,{authoritativeDaemonIds:[o]}),Er.set(o,Date.now()),ia(o,!0)})().finally(()=>{Dr.delete(o)});return Dr.set(o,f),f},[n,r,t,s])}function rs(t){const s=Number((t==null?void 0:t.receivedAt)||(t==null?void 0:t.timestamp)||0);return Number.isFinite(s)?s:0}function go(t,s){if(!t||!s)return!1;if(t===s||t.id&&s.id&&String(t.id)===String(s.id)||t._localId&&s._localId&&String(t._localId)===String(s._localId))return!0;const r=String(t.role||"").toLowerCase(),n=String(s.role||"").toLowerCase();if(r!==n)return!1;const o=ss(t.content),i=ss(s.content);if(!o||o!==i)return!1;const c=rs(t),d=rs(s);return c&&d?Math.abs(c-d)<=15e3:!!t._localId!=!!s._localId}function ca(t){let s=0;return t!=null&&t._localId||(s+=4),t!=null&&t.id&&(s+=3),t!=null&&t._turnKey&&(s+=2),rs(t)&&(s+=1),s}function fl(t,s){const r=ca(t),n=ca(s);return n!==r?n>r?s:t:ss(s.content).length>=ss(t.content).length?s:t}function As(t){const s=[];for(const r of t){const n=s.findIndex(o=>go(o,r));if(n>=0){s.splice(n,1,fl(s[n],r));continue}s.push(r)}return s}function la(t){return[...t].sort((s,r)=>{const n=rs(s),o=rs(r);return n&&o&&n!==o?n-o:0})}function da(t){return`${String((t==null?void 0:t.role)||"").toLowerCase()}:${ss(t==null?void 0:t.content).slice(0,100)}`}function ua(t,s){const r=t.filter(n=>String((n==null?void 0:n.role)||"").toLowerCase()==="user").slice();return s.filter(n=>{const o=r.findIndex(i=>go(i,n));return o>=0?(r.splice(o,1),!1):!0})}function xl(t,s){const r=new Set(s.map(n=>da(n)));return t.filter(n=>!r.has(da(n)))}const hl=60,bl=200;function gl(t={}){return t.isCliLike?bl:hl}function yl(t){return!t||typeof t!="object"?{}:"result"in t&&t.result&&typeof t.result=="object"?t.result:t}function vl(t){let s=2166136261;for(const r of t){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 pa(t,s){const r=t[t.length-1];if(!r)return"empty:";let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return["",t.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function yo(t){if(!t)return"";let s="";try{s=JSON.stringify(t.content??"")}catch{s=String(t.content??"")}return vl([String(t.id||""),String(t.index??""),String(t.role||""),String(t.receivedAt??t.timestamp??""),s])}function wl(t){return{knownMessageCount:t.length,lastMessageSignature:yo(t[t.length-1])}}function jl(t,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return t;case"append":return As([...t,...r]);case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??t.length),t.length));return As([...t.slice(0,n),...r])}case"full":default:return r}}const ma=60;function nn({activeConv:t,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,handleFocusAgent:o,isFocusingAgent:i,actionLogs:c,userName:d,showMetaChips:p=!1,scrollToBottomRequestNonce:f,isInputActive:m=!0}){var W,be,X,ue;const h=a.useRef(new Map),w=a.useRef(new Map),S=a.useRef(new Map),{sendCommand:I,sendData:u}=St(),b=Hs();Ks("ChatPane",{tabKey:t.tabKey,messageCount:t.messages.length,actionLogCount:c.length,isSendingChat:n});const v=et.useMemo(()=>ys(t),[t.status,t.connectionState]),l=a.useMemo(()=>ol(t,s),[t,s]),N=gl({isCliLike:l.isCli||l.isAcp}),A=a.useRef(new Map),k=a.useCallback(te=>(A.current.has(te)||A.current.set(te,{messages:[],offset:0,hasMore:!0,error:null,visibleLiveCount:N}),A.current.get(te)),[N]),x=a.useCallback((te,ae)=>{const fe=k(te);A.current.set(te,{...fe,...ae}),g(le=>le+1)},[k]),[,g]=a.useState(0),y=t.tabKey,j=k(y),E=j.messages,R=j.hasMore,K=j.error,D=w.current.get(y),V=t.messages.filter(te=>!!(te!=null&&te._localId)),_=D?As([...D,...V]):t.messages;a.useEffect(()=>{j.visibleLiveCount>=N||x(y,{visibleLiveCount:N})},[N,j.visibleLiveCount,y,x]);const C=Math.max(0,_.length-j.visibleLiveCount),T=Nr(t),z=mr(t),L=t.sessionId||"",$=t.providerSessionId||L,[H,se]=a.useState(!1);a.useEffect(()=>{const te=l.targetEntry;z&&(!te||te.providerControls===void 0||te.controlValues===void 0||l.isAcp&&(te.acpConfigOptions===void 0||te.acpModes===void 0))&&b(z,{minFreshMs:3e4}).catch(()=>{})},[z,l.isAcp,(W=l.targetEntry)==null?void 0:W.providerControls,(be=l.targetEntry)==null?void 0:be.controlValues,(X=l.targetEntry)==null?void 0:X.acpConfigOptions,(ue=l.targetEntry)==null?void 0:ue.acpModes,b]),a.useEffect(()=>{if(!z||!L||!u)return;const te=w.current.get(y)||[],ae=S.current.get(y),fe=ae&&ae.knownMessageCount?ae:wl(te),le=`daemon:${z}:session:${L}`;return Ot.subscribe({sendData:u},z,{type:"subscribe",topic:"session.chat_tail",key:le,params:{targetSessionId:L,historySessionId:$,knownMessageCount:fe.knownMessageCount,lastMessageSignature:fe.lastMessageSignature,...fe.knownMessageCount?{}:{tailLimit:ma}}},J=>{const pe=w.current.get(y)||[],ne=jl(pe,J),we=Math.max(ne.length,Number(J.totalMessages||0));S.current.set(y,{knownMessageCount:we,lastMessageSignature:typeof J.lastMessageSignature=="string"?J.lastMessageSignature:yo(ne[ne.length-1])}),pa(pe)!==pa(ne)&&(w.current.set(y,ne),Qt.record({interactionId:J.interactionId,kind:"dashboard.chat_tail_applied",topic:"session.chat_tail",payload:{sessionId:L,syncMode:J.syncMode,previousCount:pe.length,nextCount:ne.length}}),g(P=>P+1))})},[z,$,u,L,y]);const Y=a.useCallback(async()=>{if(H)return;const te=t.tabKey,ae=k(te);if(_.length>ae.visibleLiveCount){x(te,{visibleLiveCount:Math.min(_.length,ae.visibleLiveCount+ma),error:null});return}se(!0),x(te,{error:null});try{const fe=mr(t);if(!fe){x(te,{hasMore:!1});return}const le=jt(t),he=await I(fe,"chat_history",{agentType:le,offset:ae.offset,limit:30,targetSessionId:t.sessionId,historySessionId:t.providerSessionId||t.sessionId}),J=yl(he),pe=J.messages||[];if(pe.length>0){const ne=k(te);x(te,{messages:[...pe,...ne.messages],offset:ne.offset+pe.length,hasMore:!!J.hasMore})}else x(te,{hasMore:!!J.hasMore})}catch(fe){const le=(fe==null?void 0:fe.message)||"";le.includes("P2P not available")||le.includes("channel not open")||le.includes("P2P not connected")||le.includes("timeout")?x(te,{error:"Connection not ready — tap to retry"}):x(te,{hasMore:!1,error:"Failed to load history"})}finally{se(!1)}},[H,t,_.length,I,k,x]),{allMessages:ie,receivedAtMap:je}=a.useMemo(()=>{const te=C>0?_.slice(-j.visibleLiveCount):_;if(E.length===0){const he=la(As(te)),J={};return he.forEach((pe,ne)=>{const we=`${t.tabKey}:${ps(pe,ne)}`;let ge=rs(pe)||h.current.get(we)||0;ge||(ge=Date.now(),h.current.set(we,ge)),J[ps(pe,ne)]=ge}),{allMessages:he,receivedAtMap:J}}const ae=xl(E,te),fe=la(As([...ae,...te])),le={};return fe.forEach((he,J)=>{const pe=`${t.tabKey}:${ps(he,J)}`;let ne=rs(he)||h.current.get(pe)||0;ne||(ne=Date.now(),h.current.set(pe,ne)),le[ps(he,J)]=ne}),{allMessages:fe,receivedAtMap:le}},[t.tabKey,C,E,_,j.visibleLiveCount]),G=a.useMemo(()=>c.filter(te=>te.routeId===t.tabKey).sort((te,ae)=>te.timestamp-ae.timestamp),[c,t.tabKey]),oe=a.useMemo(()=>{if(_.length===0){if(t.connectionState==="connecting"||t.connectionState==="new")return e.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[e.jsx("div",{className:"connecting-logo-float",children:e.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:e.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),e.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[e.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",e.jsx("span",{className:"connecting-dots"})]}),e.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((v.isGenerating||t.status==="streaming")&&se(!1),t.status==="not_monitored")return e.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[e.jsx("div",{className:"text-3xl opacity-60",children:e.jsx(Rs,{size:28})}),e.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),e.jsx("button",{onClick:o,disabled:i,className:"btn btn-primary",children:i?"⌛ Switching...":e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(xs,{size:14})," Open ",T," Panel"]})}),e.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(t.status==="panel_hidden")return e.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[e.jsx("div",{className:"text-3xl opacity-60",children:e.jsx(ro,{size:28})}),e.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),e.jsx("button",{onClick:o,disabled:i,className:"btn btn-primary",children:i?"⌛ Opening...":e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(xs,{size:14})," Open ",T," Panel"]})}),e.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(t.status==="idle"&&!H)return e.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[e.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),e.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[t.connectionState,t.status,o,i,H,_.length,T,v.isGenerating]);return e.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[p&&e.jsx(bo,{conversation:t,className:"chat-pane-meta-row"}),e.jsx(Mc,{messages:ie,actionLogs:G,agentName:Os(t)||T||"Agent",userName:d,isCliMode:l.isCli||l.isAcp,isWorking:v.isGenerating,contextKey:t.tabKey,receivedAtMap:je,onLoadMore:Y,isLoadingMore:H,hasMoreHistory:R,hiddenLiveCount:C,loadError:K??void 0,emptyState:oe,scrollToBottomRequestNonce:f}),m&&!l.isCliTerminal&&(()=>{var te,ae,fe,le,he,J;return e.jsx(Hc,{routeId:t.routeId,sessionId:t.sessionId,hostIdeType:t.hostIdeType,providerType:l.providerType,displayLabel:l.displayLabel,controls:(te=l.targetEntry)==null?void 0:te.providerControls,controlValues:(ae=l.targetEntry)==null?void 0:ae.controlValues,serverModel:((fe=l.targetEntry)==null?void 0:fe.currentModel)||void 0,serverMode:((le=l.targetEntry)==null?void 0:le.currentPlan)||void 0,acpConfigOptions:l.isAcp?(he=l.targetEntry)==null?void 0:he.acpConfigOptions:void 0,acpModes:l.isAcp?(J=l.targetEntry)==null?void 0:J.acpModes:void 0})})(),!l.isCliTerminal&&e.jsx(Uc,{contextKey:t.tabKey,panelLabel:T,isSending:n,onSend:r,isActive:m})]})}let vo=es;function wo(){return vo()}class kl{constructor(){nt(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 jo=new kl;class Nl{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 tt=new Nl;function Sl(t){t.dashboardWS&&(jo=t.dashboardWS),t.connectionManager&&(tt=t.connectionManager),t.useDaemonsHook&&(vo=t.useDaemonsHook)}function Qe(t){return Nr(t)}function ns(t){return kn(t).join(" · ")}function ko(t){if(t.lastMessagePreview)return t.lastMessagePreview;const s=[...t.messages].reverse().find(n=>!(n!=null&&n._localId))||t.messages[t.messages.length-1],r=ss(s==null?void 0:s.content);return r||(t.title?t.title:ns(t)||"No messages yet")}function No(t,s){const{isReconnecting:r,isConnecting:n}=ys(t);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function Cl(t,s){const r=["Chat",...kn(t)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function Yt(t){return No(t)||ns(t)}function Il(t){return`${Qe(t)} · ${ko(t)}`}function Al(t){const s=jn(t)||jt(t);return`${Qe(t)} — ${Ze(s)}`}function Ml(t){return Os(t)||"CLI"}function So(t){return t.title||Os(t)||t.routeId}function Co(t){return t?`Remote · ${Qe(t)||t.workspaceName||"Session"}`:"Remote"}function Tl({activeConv:t,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:o=!1,isVisible:i=!0}){var $;const{ides:c}=es(),d=a.useRef(null),{sendCommand:p,sendData:f}=St(),[m,h]=a.useState(""),[w,S]=a.useState(!1),[I,u]=a.useState(1),b=a.useRef(!1),v=a.useRef(0),l=a.useRef(!1),N=a.useRef(""),A=a.useRef(null),k=a.useRef(!1),x=a.useRef(null),g=t.tabKey,y=t.sessionId||"",j=t.daemonId||(($=t.routeId)==null?void 0:$.split(":")[0])||t.routeId||"",E=c.find(H=>H.id===j&&H.type==="adhdev-daemon"),R=(E==null?void 0:E.terminalSizingMode)==="fit"?"fit":"measured",K=.6,D=1.15,V=()=>{if(typeof window>"u")return 1;const H=window.innerWidth||0;return H<=360?.68:H<=390?.74:H<=430?.82:H<=480?.9:1},_=()=>{var H,se;v.current=0,l.current=!1,N.current="",A.current=null,k.current=!1,x.current!==null&&(cancelAnimationFrame(x.current),x.current=null),S(!1),(se=(H=r.current)==null?void 0:H.reset)==null||se.call(H)},C=()=>{var H,se;v.current=0,l.current=!1,N.current="",A.current=null,k.current=!1,x.current!==null&&(cancelAnimationFrame(x.current),x.current=null),S(!0),(se=(H=r.current)==null?void 0:H.reset)==null||se.call(H)},T=()=>{var se;if(x.current=null,!i)return;const H=N.current;H&&(N.current="",(se=r.current)==null||se.write(H))},z=H=>{H&&(N.current+=H,i&&x.current===null&&(x.current=requestAnimationFrame(T)))},L=(H,se=0,Y,ie)=>{var je,G,oe,W,be;se>0&&v.current>=se||se===0&&l.current||(v.current=se,S(!0),typeof Y=="number"&&typeof ie=="number"&&Y>0&&ie>0&&((G=(je=r.current)==null?void 0:je.resize)==null||G.call(je,Y,ie)),(W=(oe=r.current)==null?void 0:oe.reset)==null||W.call(oe),H&&((be=r.current)==null||be.write(H)))};return a.useEffect(()=>{_()},[y]),a.useEffect(()=>{var se;if(!y)return;const H=((se=tt.onRuntimeEvent)==null?void 0:se.call(tt,y,Y=>{if(!(!Y||Y.sessionId!==y)){if(Y.type==="runtime_snapshot"){if(!i){A.current={text:Y.text||"",seq:Y.seq||0,cols:Y.cols,rows:Y.rows};return}L(Y.text||"",Y.seq||0,Y.cols,Y.rows);return}if(Y.type==="session_output"){l.current=!0,typeof Y.seq=="number"&&(v.current=Math.max(v.current,Y.seq)),w||S(!0),typeof Y.data=="string"&&z(Y.data);return}if(Y.type==="session_cleared"){if(!i){k.current=!0,N.current="",A.current=null;return}C()}}}))||(()=>{});return()=>{H()}},[j,y,r,i,w]),a.useEffect(()=>{var se,Y,ie;if(!y)return;j&&((se=tt.getState)==null?void 0:se.call(tt,j))==="connected"&&(S(!0),(Y=tt.requestRuntimeSnapshot)==null||Y.call(tt,j,y).catch(()=>{}));const H=(ie=tt.onStateChange)==null?void 0:ie.call(tt,(je,G)=>{var oe;je!==j||G!=="connected"||(S(!0),(oe=tt.requestRuntimeSnapshot)==null||oe.call(tt,j,y).catch(()=>{}))});return()=>{H==null||H()}},[j,y,r]),a.useEffect(()=>{s&&_()},[s,g,r]),a.useEffect(()=>{h("")},[t.tabKey]),a.useEffect(()=>{const H=()=>{b.current||u(V())};return H(),window.addEventListener("resize",H),()=>window.removeEventListener("resize",H)},[]),a.useEffect(()=>{var se;if(!i){(se=d.current)==null||se.blur();return}k.current&&(k.current=!1,C());const H=A.current;H&&(A.current=null,L(H.text,H.seq,H.cols,H.rows)),N.current&&x.current===null&&(x.current=requestAnimationFrame(T)),requestAnimationFrame(()=>{var Y;(Y=r.current)==null||Y.bumpResize()})},[i]),a.useEffect(()=>()=>{x.current!==null&&(cancelAnimationFrame(x.current),x.current=null)},[]),a.useEffect(()=>{const H=se=>{var ie;const Y=se.detail;Y!=null&&Y.sessionId&&Y.sessionId!==y||w&&((ie=r.current)==null||ie.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",H),()=>{window.removeEventListener("adhdev:fit-cli-terminal",H)}},[w,y,r]),e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[e.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[e.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{b.current=!0,u(H=>Math.max(K,Number((H-.1).toFixed(2))))},title:"Shrink terminal viewport",children:"-"}),e.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{b.current=!0,u(H=>Math.min(D,Number((H+.1).toFixed(2))))},title:"Increase terminal viewport",children:"+"})]}),e.jsx("div",{className:"w-full h-full overflow-auto rounded-lg",children:e.jsx("div",{style:{width:`${100/I}%`,height:`${100/I}%`,transform:`scale(${I})`,transformOrigin:"top left"},children:e.jsx(co,{ref:r,readOnly:!w||!i,sizingMode:R,onInput:H=>{w&&(f!=null&&f(j,{type:"pty_input",targetSessionId:y,data:H})||p(j,"pty_input",{targetSessionId:y,data:H}).catch(console.error))}})})}),!w&&e.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"})]}),e.jsx("div",{className:"px-3 py-2 bg-[var(--surface-primary)] border-t border-border-subtle shrink-0",children:e.jsxs("div",{className:"flex gap-2.5 items-center",children:[e.jsx("div",{className:"flex-1 relative",children:e.jsx("input",{ref:d,type:"text",placeholder:`Send message to ${Qe(t)}...`,value:m,disabled:!w||!i||o,onChange:H=>h(H.target.value),onPaste:H=>{const se=H.clipboardData.getData("text");se&&h(Y=>Y+se),H.preventDefault()},onKeyDown:H=>{if(H.key!=="Enter")return;if(H.nativeEvent.isComposing){H.preventDefault();return}H.preventDefault();const se=m.trim();!w||!se||o||(h(""),n(se))},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))"}})}),e.jsx("button",{onClick:()=>{const H=m.trim();!w||!H||o||(h(""),n(H))},disabled:!w||!i||!m.trim()||o,className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${m.trim()&&!o?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:m.trim()&&!o?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:m.trim()?"text-white":"text-text-muted",children:e.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})]})}function _l({wsStatus:t,showReconnected:s,loginUrl:r}){const n=t==="disconnected"||t==="reconnecting"||t==="offline"||t==="auth_failed",o=t==="auth_failed"?"red":t==="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 e.jsxs(e.Fragment,{children:[n&&e.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:[e.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5",style:{opacity:t==="auth_failed"?.6:1,animation:t==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:t==="auth_failed"?"grayscale(1)":void 0}}),t==="offline"&&"Network offline — waiting for connection...",t==="disconnected"&&"Reconnecting to server...",t==="reconnecting"&&"Reconnecting to server...",t==="auth_failed"&&(r?e.jsxs(e.Fragment,{children:["Session expired."," ",e.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — please restart the server.")]}),s&&t==="connected"&&e.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:[e.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})]})}function Pl({terminalBackend:t,isStandalone:s=!1,machineLabel:r,machineKey:n}){const o=a.useMemo(()=>!n||!t?null:`adhdev:terminal-backend-banner:dismissed:${n}:${t.backend}`,[n,t]),[i,c]=a.useState(!1);if(a.useEffect(()=>{if(!o){c(!1);return}try{c(localStorage.getItem(o)==="1")}catch{c(!1)}},[o]),!s||!t||t.backend!=="xterm"||i)return null;const d=(r==null?void 0:r.trim())||"This machine",p=()=>{if(o)try{localStorage.setItem(o,"1")}catch{}c(!0)};return e.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:[e.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[e.jsxs("span",{children:[d," is using `xterm` fallback."]}),e.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),e.jsx("button",{type:"button",onClick:p,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 Sn({mode:t,onChange:s,compact:r=!1}){const n=r?14:15;return e.jsx("button",{type:"button",onClick:()=>s(t==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:t==="chat"?"Switch to Terminal view":"Switch to Chat view",children:t==="chat"?e.jsx(wr,{size:n}):e.jsx(Kt,{size:n})})}function Ll(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){const s=Date.parse(t);if(Number.isFinite(s))return s}return 0}function Ht(t){const s=[...t.messages].reverse().find(r=>!(r!=null&&r._localId))||t.messages[t.messages.length-1];return t.lastMessageAt||Ll(s==null?void 0:s.receivedAt)||0}function an(t,s=0){return Ht(t)||t.lastUpdated||s||0}function Io(t){return Ht(t)||t.lastUpdated||0}function xr(t,s,r=Io){const n=r(s)-r(t);if(n!==0)return n;const o=(t.machineName||"").localeCompare(s.machineName||"");if(o!==0)return o;const i=t.displayPrimary.localeCompare(s.displayPrimary);if(i!==0)return i;const c=t.displaySecondary.localeCompare(s.displaySecondary);return c!==0?c:t.tabKey.localeCompare(s.tabKey)}function on(t){var r;const s=xt(t.status,{activeModal:(r=t.modalButtons)!=null&&r.length?{buttons:t.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function Rl(t){var s;return t.messages.length===0&&!((s=t.modalButtons)!=null&&s.length)&&!on(t)&&!t.title.trim()}function Dl(t){return t.length===0?null:[...t].sort((s,r)=>{const n=Number(on(r))-Number(on(s));if(n!==0)return n;const o=r.messages.length-s.messages.length;return o!==0?o:xr(s,r)})[0]||null}function Dt(t,s){const r=t.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=Dl(o);return n?i&&Rl(n)?i:n:i||r[0]||null}function fa({value:t}){return t?e.jsx("span",{className:"dashboard-header-shortcut-pill",children:t}):null}function xa({conversation:t,isAttention:s,shortcutIndex:r,onClick:n}){const o=kn(t),i=vn(Ht(t)),c=[...o,i].filter(Boolean);return e.jsxs("button",{type:"button",className:`dashboard-header-inbox-item ${s?"is-attention":""}`.trim(),onClick:n,children:[e.jsx("span",{className:"dashboard-header-inbox-item-title",children:Nr(t)}),(r||c.length>0)&&e.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[r?e.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",r]}):null,c.join(" · ")]})]})}function El({activeConv:t,agentCount:s,wsStatus:r,isConnected:n,conversations:o,onOpenHistory:i,onOpenRemote:c,onStopCli:d,activeCliViewMode:p,onSetCliViewMode:f,onOpenConversation:m,onHideConversation:h,hiddenConversations:w=[],onShowConversation:S,onShowAllHidden:I,onResetPanelsToMain:u,inboxOpen:b,onInboxOpenChange:v,hiddenOpen:l,onHiddenOpenChange:N,onOpenNewSession:A,actionShortcuts:k}){const{ides:x,p2pStates:g={}}=es(),y=!!t&&Xe(t)&&!Ve(t),j=!!t&&Ve(t),E=p||(t?xo(t)?"terminal":"chat":null),[R,K]=a.useState(!1),D=a.useRef(null),V=a.useRef(null),_=n?"#22c55e":r==="connected"?"#eab308":"#ef4444",C=n?"0 0 4px #22c55e80":r==="connected"?"0 0 4px #eab30880":"0 0 4px #ef444480",T=x.filter(X=>X.type==="adhdev-daemon"),z=a.useMemo(()=>Ws(x),[x]),L=Object.values(g),$=L.filter(X=>X==="connected").length,H=L.filter(X=>X==="connecting"||X==="new"||X==="checking").length,Y=r!=="connected"||T.length===0?null:H>0&&$===0?"P2P connecting...":$>0&&s===0?"Waiting for IDE...":null,ie=a.useMemo(()=>o.filter(X=>!Wc(X,o,z)),[o,z]),je=a.useMemo(()=>ie.filter(X=>Es(X,z).requiresAction).sort(xr),[ie,z]),G=a.useMemo(()=>ie.filter(X=>{const ue=(t==null?void 0:t.tabKey)===X.tabKey;return Es(X,z,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ue}).unread}).sort(xr),[t,ie,z]),oe=a.useMemo(()=>[...je,...G].slice(0,9),[je,G]),W=je.length+G.length;a.useEffect(()=>{if(!b)return;const X=ue=>{var te;(te=D.current)!=null&&te.contains(ue.target)||v(!1)};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[b,v]),a.useEffect(()=>{if(!l)return;const X=ue=>{var te;(te=V.current)!=null&&te.contains(ue.target)||N(!1)};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[l,N]),a.useEffect(()=>{if(!l&&!b)return;const X=ue=>{if(!ue.altKey)return;const te=ue.code.match(/^Digit([1-9])$/);if(!te)return;const ae=Number(te[1])-1,fe=l?w[ae]:void 0,le=b?oe[ae]:void 0,he=fe||le;if(he){if(ue.preventDefault(),ue.stopPropagation(),fe){S==null||S(fe),N(!1);return}m==null||m(he),v(!1)}};return window.addEventListener("keydown",X,!0),()=>window.removeEventListener("keydown",X,!0)},[w,l,b,oe,N,v,m,S]);const be=X=>{if(!X)return;const ue=o.find(te=>te.tabKey===X);ue&&(h==null||h(ue))};return e.jsxs("div",{className:"dashboard-header",children:[e.jsx("div",{className:"flex items-center gap-3",children:e.jsx("div",{className:"header-title-block",children:e.jsxs("div",{className:"header-title-row",children:[e.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[e.jsx(Kt,{size:18}),e.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),e.jsx("span",{className:"header-title-mobile",children:t?Qe(t):"Dashboard"}),e.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:e.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:_,boxShadow:C}})})]}),e.jsxs("div",{className:"header-subtitle flex items-center",children:[e.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:_,boxShadow:C}}),Y&&e.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",Y]}),A&&e.jsx("button",{type:"button",onClick:A,className:"btn btn-secondary btn-sm ml-2",title:"Start a new session","aria-label":"Start a new session",children:e.jsx(lc,{size:14})})]})]})})}),e.jsxs("div",{className:"flex gap-2 items-center",children:[t&&(y||j||!Ve(t))&&e.jsxs("div",{className:"dashboard-header-actions-group",children:[e.jsx("span",{className:"dashboard-header-action-target",title:ns(t)||Qe(t),children:Qe(t)}),(y||j)&&d&&e.jsxs(e.Fragment,{children:[y&&f&&E&&e.jsx(Sn,{mode:E,onChange:f,compact:!0}),e.jsx("button",{onClick:()=>d(t),className:"btn btn-secondary btn-sm",title:j?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:e.jsx(vt,{size:14})})]}),!Ve(t)&&e.jsx("button",{onClick:()=>i(t),className:"btn btn-secondary btn-sm",title:"Chat History",children:e.jsx(bn,{size:14})}),!y&&!Ve(t)&&e.jsx("button",{onClick:c,className:"btn btn-secondary btn-sm",title:"Remote Control",children:e.jsx(Nt,{size:14})})]}),e.jsxs("div",{className:"dashboard-header-inbox",ref:D,children:[e.jsxs("div",{className:`dashboard-header-hidden${R?" is-drop-target":""}`,ref:V,onDragEnter:X=>{X.dataTransfer.types.includes("text/tab-key")&&(X.preventDefault(),K(!0))},onDragOver:X=>{X.dataTransfer.types.includes("text/tab-key")&&(X.preventDefault(),X.dataTransfer.dropEffect="move",K(!0))},onDragLeave:X=>{X.currentTarget.contains(X.relatedTarget)||K(!1)},onDrop:X=>{const ue=X.dataTransfer.getData("text/tab-key");X.preventDefault(),K(!1),be(ue)},children:[e.jsxs("button",{type:"button",onClick:()=>N(!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:[e.jsx(no,{size:16}),w.length>0&&e.jsx("span",{className:"dashboard-header-hidden-badge",children:w.length})]}),l&&e.jsxs("div",{className:"dashboard-header-hidden-popover",children:[e.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),e.jsx(fa,{value:k==null?void 0:k.toggleHiddenTabs})]}),e.jsxs("div",{className:"dashboard-header-hidden-actions",children:[u&&e.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u,children:"Reset panels"}),w.length>0&&I&&e.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{I(),N(!1)},children:"Restore all"})]})]}),t&&h&&e.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>h(t),children:[e.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[e.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),e.jsx(fa,{value:k==null?void 0:k.hideCurrentTab})]}),e.jsx("span",{className:"dashboard-header-hidden-current-title",children:Qe(t)})]}),w.length>0?e.jsx("div",{className:"dashboard-header-hidden-list",children:w.map(X=>e.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{S==null||S(X),N(!1)},children:[e.jsx("span",{className:"dashboard-header-inbox-item-title",children:Qe(X)}),e.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[w.indexOf(X)<9?e.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",w.indexOf(X)+1]}):null,ns(X)]})]},X.tabKey))}):e.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),e.jsxs("button",{type:"button",onClick:()=>v(!b),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[e.jsx(jr,{size:16}),W>0&&e.jsx("span",{className:"dashboard-header-inbox-badge",children:W})]}),b&&e.jsxs("div",{className:"dashboard-header-inbox-popover",children:[je.length>0&&e.jsxs("div",{className:"dashboard-header-inbox-section",children:[e.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Needs attention"}),je.map(X=>e.jsx(xa,{conversation:X,isAttention:!0,shortcutIndex:oe.indexOf(X)>=0?oe.indexOf(X)+1:void 0,onClick:()=>{m==null||m(X),v(!1)}},X.tabKey))]}),G.length>0&&e.jsxs("div",{className:"dashboard-header-inbox-section",children:[e.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Task complete"}),G.map(X=>e.jsx(xa,{conversation:X,shortcutIndex:oe.indexOf(X)>=0?oe.indexOf(X)+1:void 0,onClick:()=>{m==null||m(X),v(!1)}},X.tabKey))]}),W===0&&e.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function $l(t){if(!t)return"";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(t))}catch{return new Date(t).toLocaleString()}}function Cn({activeConv:t,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:o=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,onClose:d,onNewChat:p,onSwitchSession:f,onRefreshHistory:m,onResumeSavedSession:h}){var v;const w=s.find(l=>l.id===t.routeId),S=(w==null?void 0:w.chats)||[],I=(v=w==null?void 0:w.activeChat)==null?void 0:v.id,u=Xe(t)&&!Ve(t),b=e.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-center justify-center",children:[e.jsx("div",{onClick:d,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),e.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:[e.jsxs("div",{className:"px-6 py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)]",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"m-0 text-lg font-extrabold",children:u?"Saved Sessions":"Chat History"}),e.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Al(t)})]}),e.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:e.jsx(vt,{size:16})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-3 bg-bg-primary",children:[!u&&e.jsx("button",{onClick:p,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),u?e.jsx(e.Fragment,{children:o.map(l=>{const N=t.providerSessionId===l.providerSessionId,A=N||!l.canResume||!!c;return e.jsxs("button",{type:"button",onClick:()=>{A||!h||h(l)},disabled:A,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${N?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${A?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:`font-bold text-sm mb-1 truncate ${N?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:l.title||"Untitled Session"}),e.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:l.providerSessionId})]}),e.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:$l(l.lastMessageAt)})]}),e.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:l.preview||"No saved preview yet"}),e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[e.jsxs("div",{className:"truncate",children:[l.workspace||"Workspace unknown",l.currentModel?` · ${l.currentModel}`:"",l.messageCount>0?` · ${l.messageCount} msgs`:""]}),e.jsx("div",{className:"shrink-0",children:N?"ACTIVE":l.canResume?c===l.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},l.id)})}):S.map(l=>e.jsxs("div",{onClick:()=>{f(t.routeId,l.id),d()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${I===l.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[e.jsx("div",{className:`font-bold text-sm mb-1 ${I===l.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:l.title||"Untitled Session"}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[l.id.substring(0,12),"..."]}),I===l.id&&e.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)&&e.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[e.jsx("div",{className:"text-3xl mb-3 opacity-60",children:e.jsx(pc,{size:32})}),e.jsx("div",{className:"text-[13px]",children:u?"No saved sessions found yet.":"No recent chat sessions found."})]}),u&&i&&e.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:e.jsx("div",{className:"text-[13px]",children:"Refreshing saved sessions…"})})]}),e.jsx("div",{className:"px-5 py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right",children:e.jsx("button",{onClick:m,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(gs,{size:13})," ",u?"Refresh Sessions":"Refresh History"]})})})]})]});return typeof document>"u"?b:Ls.createPortal(b,document.body)}const ha={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 Ao({toasts:t,onDismiss:s,onClickToast:r}){return e.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:t.map(n=>{const o=ha[n.type]||ha.info;return e.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:[e.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))`}}),e.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:e.jsx(vt,{size:14})}),e.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[e.jsx("div",{className:"flex items-center gap-2 pr-8",children:e.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})}),e.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&e.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((i,c)=>e.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 Bl=t=>t.transport==="pty"||t.transport==="acp"||t.transport==="cdp-page"?!0:t.daemonId!==t.id;function Kl(t){const s=t.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function Wl(t){return t.sessionId||t.instanceId||t.agentType}function Br(t,s){return t||s}function ba(t,s){const r=new Set,n=[];for(const o of s)if(o)for(const i of t[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 Mo(t=[]){const s={};for(const r of t)r.type==="adhdev-daemon"&&(s[r.id]=kt(r,{fallbackId:r.id}));return s}function To(t,s={}){var n,o;const r=t.daemonId||((n=t.id)==null?void 0:n.split(":")[0])||t.id;return{machineName:t.daemonId&&((o=s.machineNames)==null?void 0:o[t.daemonId])||void 0,connectionState:s.connectionStates?s.connectionStates[r]||s.defaultConnectionState||"new":s.defaultConnectionState}}function In(t,s,r={}){return Ol(t,s,To(t,r))}function Ol(t,s,r={}){var w,S,I,u,b,v;const n=[],o=r.machineName,i=r.connectionState,c=Kl(t),d=Ze(t.type),p=Array.isArray(t.childSessions)?t.childSessions.map(l=>{var N,A;return{sessionId:l.id,instanceId:l.id,providerSessionId:l.providerSessionId,transport:l.transport,agentType:l.providerType,agentName:l.providerName||Ze(l.providerType),status:l.status,title:l.title,lastMessagePreview:l.lastMessagePreview,lastMessageRole:l.lastMessageRole,lastMessageAt:l.lastMessageAt,lastMessageHash:l.lastMessageHash,messages:((N=l.activeChat)==null?void 0:N.messages)||[],activeModal:((A=l.activeChat)==null?void 0:A.activeModal)||void 0,unread:l.unread,lastSeenAt:l.lastSeenAt,lastUpdated:l.lastUpdated,inboxBucket:l.inboxBucket,surfaceHidden:l.surfaceHidden}}):[],f=Bl(t),m=t.activeChat||{title:""},h=m.title&&String(m.title).trim()?String(m.title).trim():"";if(f){const l=t.sessionId||t.instanceId,N=ra(t.type),A=(w=t.activeChat)==null?void 0:w.activeModal,k=A&&Array.isArray(A.buttons)&&A.buttons.length>0,x=xt((S=t.activeChat)==null?void 0:S.status,{activeModal:(I=t.activeChat)==null?void 0:I.activeModal})||xt((b=(u=t.agents)==null?void 0:u[0])==null?void 0:b.status)||"idle",g=t.activeChat||{title:"",messages:[]};let y=g.title&&String(g.title).trim()?String(g.title).trim():"";const j=(v=t.activeChat)==null?void 0:v.id,E=t.chats;if(j&&Array.isArray(E)&&E.length>0){const C=E.find(T=>T.id===j||T.id&&String(T.id)===String(j));C!=null&&C.title&&String(C.title).trim()&&(y=String(C.title).trim())}const R=(Xe(t)||Ve(t),t.type),K=(Xe(t)||Ve(t))&&na(y,N,R)?"":y,D=g.messages||[],V=ba(s,[t.id,l]),_=ua(D,V);n.push({routeId:t.id,sessionId:l,providerSessionId:t.providerSessionId,nativeSessionId:l,transport:t.transport,daemonId:t.daemonId||void 0,mode:Xe(t)?t.mode||"terminal":"chat",agentName:N,agentType:R,status:x,title:K,messages:[...D,..._],resume:t.resume,hostIdeType:!Xe(t)&&!Ve(t)?t.type:void 0,workspaceName:c,displayPrimary:c||K||(Xe(t)?t.mode==="chat"?N:"Terminal":N),displaySecondary:d,cdpConnected:t.cdpConnected,lastMessagePreview:t.lastMessagePreview,lastMessageRole:t.lastMessageRole,lastMessageAt:t.lastMessageAt,lastMessageHash:t.lastMessageHash,lastUpdated:t.lastUpdated,modalButtons:k?A.buttons:void 0,modalMessage:k?A.message:void 0,streamSource:"native",tabKey:Br(l,t.id),machineName:o,connectionState:i})}if(f&&(Xe(t)||Ve(t)))return n;for(const l of p){const N=l.activeModal&&Array.isArray(l.activeModal.buttons)&&l.activeModal.buttons.length>0,A=Jc(l),k=Wl(l),x=`${t.id}:${k}`,g=l.title&&String(l.title).trim()||"",y=na(g,l.agentName,l.agentType)?"":g,j=l.messages||[],E=ba(s,[x,l.sessionId,l.instanceId]),R=ua(j,E);(l.transport==="cdp-webview"||l.sessionId||l.providerSessionId||j.length>0||R.length>0||N||y||!["idle","panel_hidden","disconnected","not_monitored"].includes(A))&&n.push({routeId:t.id,sessionId:l.sessionId||l.instanceId,providerSessionId:l.providerSessionId,nativeSessionId:t.sessionId||t.instanceId,transport:l.transport||"cdp-webview",daemonId:t.daemonId||void 0,mode:"chat",agentName:l.agentName,agentType:l.agentType,status:A,title:y,messages:[...j,...R],hostIdeType:t.type,workspaceName:c,displayPrimary:c||h||y||d,displaySecondary:`${d} · ${l.agentName}`,cdpConnected:t.cdpConnected,lastMessagePreview:l.lastMessagePreview,lastMessageRole:l.lastMessageRole,lastMessageAt:l.lastMessageAt,lastMessageHash:l.lastMessageHash,lastUpdated:l.lastUpdated||t.lastUpdated,modalButtons:N?l.activeModal.buttons:void 0,modalMessage:N?l.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Br(l.sessionId||l.instanceId,x),machineName:o,connectionState:i})}return n.length===0&&n.push({routeId:t.id,sessionId:t.sessionId||t.instanceId,providerSessionId:t.providerSessionId,nativeSessionId:t.sessionId||t.instanceId,transport:t.transport,daemonId:t.daemonId||void 0,mode:"chat",agentName:ra(t.type),agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:t.type,workspaceName:c,displayPrimary:c||d,displaySecondary:d,cdpConnected:t.cdpConnected,lastUpdated:t.lastUpdated,streamSource:"native",tabKey:Br(t.sessionId||t.instanceId,t.id),connectionState:i}),n}function Hl(t){const s=t.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:t}}function Ul(t,s){const r=Hl(t);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const _o=[{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:"🏄"}],Po=[{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:"🧩"}],Lo=[{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:"🟠"}],zl=_o,Fl=Po,Vl=Lo,Ro="adhdev_notification_prefs",ga={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Gl(){try{const t=localStorage.getItem(Ro);if(t){const s=JSON.parse(t);return{...ga,...s}}}catch{}return{...ga}}function ql(t){try{localStorage.setItem(Ro,JSON.stringify(t))}catch{}}let $t=Gl(),or=[];function Yl(){or.forEach(t=>t())}function Xl(t){$t={...$t,...t},ql($t),Yl()}function Jl(){const[,t]=a.useState(0);a.useEffect(()=>{const r=()=>t(n=>n+1);return or.push(r),()=>{or=or.filter(n=>n!==r)}},[]);const s=a.useCallback(r=>{Xl(r)},[]);return[{...$t},s]}function Ms(t){if(!$t.globalEnabled)return!1;switch(t){case"disconnect":return $t.disconnectAlert;case"completion":return $t.completionAlert;case"approval":return $t.approvalAlert;case"browser":return $t.browserNotifications;default:return!0}}const Zl={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Ql(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Do(){return"Notification"in window&&Notification.permission==="granted"}let Vt=null;async function ed(){if(Vt!==null)return Vt;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Vt=!1,!1;const t=await navigator.serviceWorker.getRegistration();return t?(Vt=!!await t.pushManager.getSubscription(),Vt):(Vt=!1,!1)}catch{return Vt=!1,!1}}function cn(t,s,r){if(Do())try{const n=new Notification(t,{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 td(t,s={}){const r={...Zl,...s},n=a.useRef(new Map),o=a.useRef(0),i=a.useRef(null);a.useEffect(()=>{ed().then(d=>{i.current=d})},[]);const c=a.useCallback((d,p,f)=>{const m=Date.now();m-o.current<r.throttleMs||(o.current=m,cn(d,p,f))},[r.throttleMs]);a.useEffect(()=>{var d;if(!(!r.enabled||!Do())&&Ms("browser")&&i.current!==!0){if(document.hasFocus()){for(const p of t)n.current.set(p.id,xt(p.status,{activeModal:p.activeModal}));return}for(const p of t){const f=n.current.get(p.id),m=xt(p.status,{activeModal:p.activeModal}),h=p.name||p.id;if(r.onApproval&&Ms("approval")&&m==="waiting_approval"&&f!=="waiting_approval"){const w=((d=p.activeModal)==null?void 0:d.message)||"Action requires your approval";c(`🔔 ${h} — Approval needed`,w.slice(0,120),`approval-${p.id}`)}r.onComplete&&Ms("completion")&&mo(f)&&m==="idle"&&c(`✅ ${h} — Task complete`,"Agent has finished generating",`complete-${p.id}`),r.onError&&m==="error"&&f!=="error"&&c(`⚠️ ${h} — Error`,"Agent encountered an error",`error-${p.id}`),n.current.set(p.id,m)}}},[t,r.enabled,r.onApproval,r.onComplete,r.onError,c])}const sd=/^(run|approve|accept|yes|allow|always)/,rd=/^(run|approve|accept|yes|allow|always|proceed|save)/,nd=/^(reject|deny|delete|remove|abort|cancel|no)/;function An(t){return t.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function ad(t){const s=An(t).toLowerCase();return sd.test(s)?"primary":nd.test(s)?"danger":"default"}function od(t){return rd.test(An(t).toLowerCase())?"approve":"reject"}function id(t){return t.map((s,r)=>({label:An(s),variant:ad(s),action:od(s),button:s,buttonIndex:r}))}function cd(t,s){const r=t||"Approval requested",n=s!=null&&s.length?s.map(o=>`[${o}]`).join(" "):"[Approve] [Reject]";return`⚡ Approval requested: ${r}
31
- ${n}`}function ld(t,s,r){return s?`⚡ ${t}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function dd(t,s,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(t,s,"approve").catch(o=>n==null?void 0:n("approve",o))}},{label:"Decline",variant:"danger",onClick:()=>{r(t,s,"reject").catch(o=>n==null?void 0:n("reject",o))}}]}class ud{constructor(){nt(this,"dedupMap",new Map);nt(this,"DEDUP_WINDOW_MS",5e3);nt(this,"DEDUP_MAX_SIZE",50);nt(this,"DEDUP_CLEANUP_AGE_MS",1e4);nt(this,"toastCallbacks",[]);nt(this,"systemMessageCallbacks",[]);nt(this,"clearSystemMessageCallbacks",[]);nt(this,"resolveActionFn",null);nt(this,"viewRequestRespondFn",null);nt(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 I,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 p=s.targetSessionId?this.findOwningSession(s.targetSessionId):null,f=(p==null?void 0:p.type)||"";let m=Ze(f);const h=this.resolveOwningDaemon(s);if(h){const b=kt(h,{fallbackId:h.id});b&&(m=!f||f==="adhdev-daemon"?b:`${b}/${m}`)}let w="",S="info";if(s.event==="agent:generating_completed"){const b=s.duration?` (${s.duration}s)`:"";w=`✅ ${m} agent task completed${b}`,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(w=`⚡ ${m} approval needed`,S="warning",n&&!((I=s.modalButtons)!=null&&I.length)&&this.emitSystemMessage(n,{role:"system",timestamp:o,content:cd(s.modalMessage,s.modalButtons),_localId:`sys_approval_${o}`}),(u=s.modalButtons)!=null&&u.length&&this.resolveActionFn){const b=this.resolveActionRouteTarget(s);if(!b)return;const v=this.resolveActionFn,l=id(s.modalButtons).map(k=>({label:k.label,variant:k.variant,onClick:()=>{v(b,"resolve_action",{action:k.action,button:k.button,buttonIndex:k.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),N=ld(m,s.modalMessage,w),A=Date.now();this.emitToast({id:A,message:N,type:S,timestamp:A,targetKey:n||b,actions:l,duration:15e3}),w=""}}else if(s.event==="monitor:long_generating"){const b=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";w=`⚠️ ${m} agent is taking a long time${b}`,S="warning",Ms("browser")&&!document.hasFocus()&&cn(`⚠️ ${m} — Long Running`,`Agent has been generating for over ${b.replace(/[()]/g,"")}`,`long-${s.targetSessionId||s.daemonId||"daemon"}`)}else if(s.event==="team:view_request"){const b=s.requesterName||"A team member",v=s.requestId,l=s.orgId;if(w=`👁️ ${b} wants to view your session`,S="warning",v&&l&&this.viewRequestRespondFn){const N=Date.now(),A=dd(l,v,this.viewRequestRespondFn,(k,x)=>console.error(`[EventManager] ${k} view request failed:`,x));this.emitToast({id:N,message:w,type:S,timestamp:N,actions:A,duration:3e4}),w=""}Ms("browser")&&!document.hasFocus()&&cn("👁️ View Request",`${b} wants to view your session`,`view-request-${v}`)}else s.event==="team:view_request_approved"?(w="✅ View request approved",S="success"):s.event==="team:view_request_rejected"&&(w=`❌ ${s.targetName||"Team member"} declined your view request`,S="warning");if(w){const b=Date.now();this.emitToast({id:b,message:w,type:S,timestamp:b,targetKey:n||s.daemonId,duration:5e3})}}}const ht=new ud;function as(...t){return Bi(Ki(t))}function pd({icon:t,title:s,subtitle:r,badge:n,actions:o,className:i}){return e.jsxs("div",{className:as("dashboard-header",i),children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"header-title flex items-center gap-2",children:[e.jsx("span",{className:"flex items-center text-lg",children:t})," ",s,n&&e.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&&e.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),o&&e.jsx("div",{className:"flex gap-2",children:o})]})}function Eo({icon:t,title:s,subtitle:r,badge:n,actions:o,widthClassName:i="max-w-6xl",contentClassName:c,children:d}){return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(pd,{icon:t,title:s,subtitle:r,badge:n,actions:o}),e.jsx("div",{className:"page-content",children:e.jsx("div",{className:as("mx-auto flex w-full flex-col gap-4",i,c),children:d})})]})}function Pt({title:t,icon:s,description:r,accentColor:n,className:o,children:i}){return e.jsxs("div",{className:as("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:[(t||r)&&e.jsxs("div",{className:"mb-4",children:[t&&e.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[s&&e.jsx("span",{className:"mr-1.5",children:s}),t]}),r&&e.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),i]})}function $o({icon:t,title:s,description:r,action:n,className:o}){return e.jsxs("div",{className:as("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",o),children:[e.jsx("div",{className:"text-5xl mb-4 opacity-50",children:t}),e.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:s}),e.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const md={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"},fd={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function xd({variant:t,children:s,onDismiss:r,className:n}){return e.jsxs("div",{className:as("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",md[t],n),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:fd[t]}),e.jsx("span",{children:s})]}),r&&e.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}const hd={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"},bd={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function gd({status:t,label:s,className:r}){const n=s||t;return e.jsxs("span",{className:as("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",hd[t],r),children:[e.jsx("span",{className:as("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",bd[t])}),n]})}const ln="adhdev:themechange";function yd(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function ds(){try{const t=localStorage.getItem("theme");if(t==="dark"||t==="light"||t==="system")return t}catch{}return"system"}function us(t){return t==="system"?yd():t}function Bo(t){typeof document>"u"||(document.documentElement.setAttribute("data-theme",t),document.documentElement.style.colorScheme=t)}function ir(t,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(ln,{detail:{preference:t,theme:s}}))}function vd(){const t=ds(),s=us(t);Bo(s),ir(t,s)}function Mn(){const[t,s]=a.useState(ds),[r,n]=a.useState(()=>us(ds()));a.useEffect(()=>{Bo(r)},[r]),a.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),d=p=>{if(t==="system"){const f=p.matches?"light":"dark";n(f),ir("system",f)}};return c.addEventListener("change",d),()=>c.removeEventListener("change",d)},[t]),a.useEffect(()=>{const c=p=>{const f=p.detail||{},m=f.preference,h=f.theme;s(m==="dark"||m==="light"||m==="system"?m:ds()),n(h==="dark"||h==="light"?h:us(ds()))},d=p=>{if(p.key!=="theme")return;const f=ds(),m=us(f);s(f),n(m)};return window.addEventListener(ln,c),window.addEventListener("storage",d),()=>{window.removeEventListener(ln,c),window.removeEventListener("storage",d)}},[]);const o=a.useCallback(c=>{const d=us(c);s(c),n(d);try{localStorage.setItem("theme",c)}catch{}ir(c,d)},[]),i=a.useCallback(()=>{s(c=>{const d=c==="dark"?"light":c==="light"?"system":"dark",p=us(d);n(p);try{localStorage.setItem("theme",d)}catch{}return ir(d,p),d})},[]);return{theme:r,preference:t,setPreference:o,cycleTheme:i,isDark:r==="dark"}}const ya={dark:"Dark",light:"Light",system:"System"};function wd({collapsed:t}){const{preference:s,cycleTheme:r}=Mn(),n=s==="dark"?e.jsx(fc,{size:16}):s==="light"?e.jsx(mc,{size:16}):e.jsx(xc,{size:16});return e.jsxs("div",{className:`nav-item cursor-pointer ${t?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${ya[s]} (click to cycle)`,children:[e.jsx("span",{className:"nav-icon",children:n}),!t&&e.jsx("span",{className:"text-xs",children:ya[s]})]})}function qt({label:t,description:s,checked:r,disabled:n,onChange:o,extra:i}){return e.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[e.jsxs("div",{className:"pr-4",children:[e.jsx("div",{className:"font-medium text-sm",children:t}),e.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:s})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,e.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:[e.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))"}}),e.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 jd({onPrefChange:t}){const[s,r]=Jl(),n=(o,i)=>{r({[o]:i}),t==null||t(o,i)};return e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(jr,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:o=>n("globalEnabled",o)}),s.globalEnabled&&e.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Nt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:o=>n("browserNotifications",o)}),s.globalEnabled&&s.browserNotifications&&e.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(hc,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:o=>n("completionAlert",o)}),e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(bc,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:o=>n("approvalAlert",o)}),e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Rs,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:o=>n("disconnectAlert",o)})]}),!s.globalEnabled&&e.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function hr(t){const s=t.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function kd(t,s){const r=hr(t),n=hr(s);if(!r||!n)return t.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 Ko(t,s){const r=t.version||null;return t.versionMismatch===!0?!0:!r||!s?!1:r!==s}function Ts(t,s){if(t.versionUpdateRequired===!0)return!0;const r=t.version||null;if(!r||!s||r===s||kd(r,s)>=0)return!1;const n=hr(r),o=hr(s);return!n||!o?!1:n[0]!==o[0]||n[1]!==o[1]}function Nd(t){return!t||typeof t!="object"?{}:"result"in t&&t.result&&typeof t.result=="object"?t.result:t}function Kr(t,s){return t instanceof Error?t.message:s}function Sd({ides:t,emptyMessage:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o}){const i=t.filter(c=>c.type==="adhdev-daemon");return i.length===0?e.jsx($o,{icon:e.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||"Run 'adhdev-standalone' to connect a local daemon instance."}):e.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>e.jsx(Id,{ide:c,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o},c.id))})}function va({title:t,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 Ls.createPortal(e.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,children:e.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:[e.jsx("div",{className:"font-semibold text-sm mb-3",children:t}),e.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:s}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.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"}),e.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 Cd(t){const s=t.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...zl,...Fl,...Vl].find(o=>o.id===s||s.includes(o.id)||o.id.includes(s));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:t}}function Id({ide:t,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o}){var V,_;const[i,c]=a.useState("idle"),[d,p]=a.useState(""),[f,m]=a.useState(null),[h,w]=a.useState("idle"),[S,I]=a.useState(""),u=t.version||null,b=((V=t.machine)==null?void 0:V.platform)||((_=t.system)==null?void 0:_.platform)||"",v=kt(t,{fallbackId:t.id}),l=b==="win32"?"🪟":b==="darwin"?"🍎":"🐧",N=s.filter(C=>C.daemonId===t.id&&C.transport==="cdp-page"),A=s.filter(C=>C.daemonId===t.id&&C.transport==="pty"),k=s.filter(C=>C.daemonId===t.id&&C.transport==="acp"),x=t.p2p,g=async()=>{if(r){c("upgrading"),p("Starting upgrade...");try{const C=Nd(await r(t.id,"daemon_upgrade",{}));C.alreadyLatest?(c("done"),p(`Already on v${C.version||"latest"}.`)):C.upgraded||C.success?(c("done"),p(`Upgrade to v${C.version||"latest"} started. Daemon is restarting...`)):(c("error"),p(C.error||"Upgrade failed"))}catch(C){c("error"),p(Kr(C,"Connection lost during upgrade"))}}},y=async()=>{if(m(null),!!n){w("loading");try{await n(t.id),w("done"),I("Machine disconnected.")}catch(C){w("error"),I(Kr(C,"Failed to disconnect"))}}},j=async()=>{if(m(null),!!o){w("loading");try{await o(t.id),w("done"),I('Token revoked. Machine must restart "adhdev-standalone" to reconnect.')}catch(C){w("error"),I(Kr(C,"Failed to revoke token"))}}},E="0.8.50",R=Ko(t,E),K=Ts(t,E),D=N.length+A.length+k.length;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-xl",children:l}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:v}),e.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[e.jsxs("span",{children:[t.id.substring(0,12),"…"]}),u&&e.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${R?"":"bg-bg-secondary"}`,style:R?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",u,!R&&" ✓"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&R&&e.jsx("button",{onClick:g,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${E}`,children:i==="upgrading"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${K?"↑ Update now":`↑ Update${` to v${E}`}`}`}),n&&e.jsx("button",{onClick:()=>m("disconnect"),disabled:h==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),o&&e.jsx("button",{onClick:()=>m("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),e.jsx(gd,{status:t.status==="online"?"online":"error"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[x&&e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${x.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${x.state==="connecting"||x.state==="new"?"animate-pulse":""}`,style:x.state==="connecting"||x.state==="new"?{background:"var(--status-warning)"}:void 0}),e.jsxs("span",{className:"text-text-muted",children:["P2P ",x.state==="connected"?"connected":x.state==="connecting"||x.state==="new"?"connecting...":x.state||"off"]}),x.peers!==void 0&&x.peers>0&&e.jsxs("span",{className:"text-text-muted/60",children:["(",x.peers," peer",x.peers!==1?"s":"",")"]})]}),x&&D>0&&e.jsx("span",{className:"text-border-subtle",children:"·"}),D>0?e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[N.map(C=>{const T=Cd(C.type),z=C.cdpConnected;return e.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[e.jsx("span",{children:T.icon}),e.jsx("span",{children:T.name}),z!==void 0&&e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${z?"bg-green-400":"animate-pulse"}`,style:z?void 0:{background:"var(--status-warning)"},title:z?"CDP connected":"CDP connecting..."})]},C.id)}),A.map(C=>e.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[e.jsx("span",{children:"⌨️"}),e.jsx("span",{children:C.cliName||"CLI"})]},C.id)),k.map(C=>e.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[e.jsx("span",{children:"🔗"}),e.jsx("span",{children:C.cliName||"ACP"})]},C.id))]}):e.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(d||S)&&e.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||h==="error"?"text-red-400":i==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:S||d})]}),f==="disconnect"&&e.jsx(va,{title:"🔌 Disconnect Machine",message:`Disconnect "${v}" from ADHDev?
31
+ ${n}`}function ld(t,s,r){return s?`⚡ ${t}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function dd(t,s,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(t,s,"approve").catch(o=>n==null?void 0:n("approve",o))}},{label:"Decline",variant:"danger",onClick:()=>{r(t,s,"reject").catch(o=>n==null?void 0:n("reject",o))}}]}class ud{constructor(){nt(this,"dedupMap",new Map);nt(this,"DEDUP_WINDOW_MS",5e3);nt(this,"DEDUP_MAX_SIZE",50);nt(this,"DEDUP_CLEANUP_AGE_MS",1e4);nt(this,"toastCallbacks",[]);nt(this,"systemMessageCallbacks",[]);nt(this,"clearSystemMessageCallbacks",[]);nt(this,"resolveActionFn",null);nt(this,"viewRequestRespondFn",null);nt(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 I,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 p=s.targetSessionId?this.findOwningSession(s.targetSessionId):null,f=(p==null?void 0:p.type)||"";let m=Ze(f);const h=this.resolveOwningDaemon(s);if(h){const b=kt(h,{fallbackId:h.id});b&&(m=!f||f==="adhdev-daemon"?b:`${b}/${m}`)}let w="",S="info";if(s.event==="agent:generating_completed"){const b=s.duration?` (${s.duration}s)`:"";w=`✅ ${m} agent task completed${b}`,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(w=`⚡ ${m} approval needed`,S="warning",n&&!((I=s.modalButtons)!=null&&I.length)&&this.emitSystemMessage(n,{role:"system",timestamp:o,content:cd(s.modalMessage,s.modalButtons),_localId:`sys_approval_${o}`}),(u=s.modalButtons)!=null&&u.length&&this.resolveActionFn){const b=this.resolveActionRouteTarget(s);if(!b)return;const v=this.resolveActionFn,l=id(s.modalButtons).map(k=>({label:k.label,variant:k.variant,onClick:()=>{v(b,"resolve_action",{action:k.action,button:k.button,buttonIndex:k.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),N=ld(m,s.modalMessage,w),A=Date.now();this.emitToast({id:A,message:N,type:S,timestamp:A,targetKey:n||b,actions:l,duration:15e3}),w=""}}else if(s.event==="monitor:long_generating"){const b=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";w=`⚠️ ${m} agent is taking a long time${b}`,S="warning",Ms("browser")&&!document.hasFocus()&&cn(`⚠️ ${m} — Long Running`,`Agent has been generating for over ${b.replace(/[()]/g,"")}`,`long-${s.targetSessionId||s.daemonId||"daemon"}`)}else if(s.event==="team:view_request"){const b=s.requesterName||"A team member",v=s.requestId,l=s.orgId;if(w=`👁️ ${b} wants to view your session`,S="warning",v&&l&&this.viewRequestRespondFn){const N=Date.now(),A=dd(l,v,this.viewRequestRespondFn,(k,x)=>console.error(`[EventManager] ${k} view request failed:`,x));this.emitToast({id:N,message:w,type:S,timestamp:N,actions:A,duration:3e4}),w=""}Ms("browser")&&!document.hasFocus()&&cn("👁️ View Request",`${b} wants to view your session`,`view-request-${v}`)}else s.event==="team:view_request_approved"?(w="✅ View request approved",S="success"):s.event==="team:view_request_rejected"&&(w=`❌ ${s.targetName||"Team member"} declined your view request`,S="warning");if(w){const b=Date.now();this.emitToast({id:b,message:w,type:S,timestamp:b,targetKey:n||s.daemonId,duration:5e3})}}}const ht=new ud;function as(...t){return Bi(Ki(t))}function pd({icon:t,title:s,subtitle:r,badge:n,actions:o,className:i}){return e.jsxs("div",{className:as("dashboard-header",i),children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"header-title flex items-center gap-2",children:[e.jsx("span",{className:"flex items-center text-lg",children:t})," ",s,n&&e.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&&e.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),o&&e.jsx("div",{className:"flex gap-2",children:o})]})}function Eo({icon:t,title:s,subtitle:r,badge:n,actions:o,widthClassName:i="max-w-6xl",contentClassName:c,children:d}){return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(pd,{icon:t,title:s,subtitle:r,badge:n,actions:o}),e.jsx("div",{className:"page-content",children:e.jsx("div",{className:as("mx-auto flex w-full flex-col gap-4",i,c),children:d})})]})}function Pt({title:t,icon:s,description:r,accentColor:n,className:o,children:i}){return e.jsxs("div",{className:as("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:[(t||r)&&e.jsxs("div",{className:"mb-4",children:[t&&e.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[s&&e.jsx("span",{className:"mr-1.5",children:s}),t]}),r&&e.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),i]})}function $o({icon:t,title:s,description:r,action:n,className:o}){return e.jsxs("div",{className:as("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",o),children:[e.jsx("div",{className:"text-5xl mb-4 opacity-50",children:t}),e.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:s}),e.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const md={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"},fd={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function xd({variant:t,children:s,onDismiss:r,className:n}){return e.jsxs("div",{className:as("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",md[t],n),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:fd[t]}),e.jsx("span",{children:s})]}),r&&e.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}const hd={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"},bd={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function gd({status:t,label:s,className:r}){const n=s||t;return e.jsxs("span",{className:as("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",hd[t],r),children:[e.jsx("span",{className:as("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",bd[t])}),n]})}const ln="adhdev:themechange";function yd(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function ds(){try{const t=localStorage.getItem("theme");if(t==="dark"||t==="light"||t==="system")return t}catch{}return"system"}function us(t){return t==="system"?yd():t}function Bo(t){typeof document>"u"||(document.documentElement.setAttribute("data-theme",t),document.documentElement.style.colorScheme=t)}function ir(t,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(ln,{detail:{preference:t,theme:s}}))}function vd(){const t=ds(),s=us(t);Bo(s),ir(t,s)}function Mn(){const[t,s]=a.useState(ds),[r,n]=a.useState(()=>us(ds()));a.useEffect(()=>{Bo(r)},[r]),a.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),d=p=>{if(t==="system"){const f=p.matches?"light":"dark";n(f),ir("system",f)}};return c.addEventListener("change",d),()=>c.removeEventListener("change",d)},[t]),a.useEffect(()=>{const c=p=>{const f=p.detail||{},m=f.preference,h=f.theme;s(m==="dark"||m==="light"||m==="system"?m:ds()),n(h==="dark"||h==="light"?h:us(ds()))},d=p=>{if(p.key!=="theme")return;const f=ds(),m=us(f);s(f),n(m)};return window.addEventListener(ln,c),window.addEventListener("storage",d),()=>{window.removeEventListener(ln,c),window.removeEventListener("storage",d)}},[]);const o=a.useCallback(c=>{const d=us(c);s(c),n(d);try{localStorage.setItem("theme",c)}catch{}ir(c,d)},[]),i=a.useCallback(()=>{s(c=>{const d=c==="dark"?"light":c==="light"?"system":"dark",p=us(d);n(p);try{localStorage.setItem("theme",d)}catch{}return ir(d,p),d})},[]);return{theme:r,preference:t,setPreference:o,cycleTheme:i,isDark:r==="dark"}}const ya={dark:"Dark",light:"Light",system:"System"};function wd({collapsed:t}){const{preference:s,cycleTheme:r}=Mn(),n=s==="dark"?e.jsx(fc,{size:16}):s==="light"?e.jsx(mc,{size:16}):e.jsx(xc,{size:16});return e.jsxs("div",{className:`nav-item cursor-pointer ${t?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${ya[s]} (click to cycle)`,children:[e.jsx("span",{className:"nav-icon",children:n}),!t&&e.jsx("span",{className:"text-xs",children:ya[s]})]})}function qt({label:t,description:s,checked:r,disabled:n,onChange:o,extra:i}){return e.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[e.jsxs("div",{className:"pr-4",children:[e.jsx("div",{className:"font-medium text-sm",children:t}),e.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:s})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,e.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:[e.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))"}}),e.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 jd({onPrefChange:t}){const[s,r]=Jl(),n=(o,i)=>{r({[o]:i}),t==null||t(o,i)};return e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(jr,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:o=>n("globalEnabled",o)}),s.globalEnabled&&e.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Nt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:o=>n("browserNotifications",o)}),s.globalEnabled&&s.browserNotifications&&e.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(hc,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:o=>n("completionAlert",o)}),e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(bc,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:o=>n("approvalAlert",o)}),e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Rs,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:o=>n("disconnectAlert",o)})]}),!s.globalEnabled&&e.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function hr(t){const s=t.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function kd(t,s){const r=hr(t),n=hr(s);if(!r||!n)return t.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 Ko(t,s){const r=t.version||null;return t.versionMismatch===!0?!0:!r||!s?!1:r!==s}function Ts(t,s){if(t.versionUpdateRequired===!0)return!0;const r=t.version||null;if(!r||!s||r===s||kd(r,s)>=0)return!1;const n=hr(r),o=hr(s);return!n||!o?!1:n[0]!==o[0]||n[1]!==o[1]}function Nd(t){return!t||typeof t!="object"?{}:"result"in t&&t.result&&typeof t.result=="object"?t.result:t}function Kr(t,s){return t instanceof Error?t.message:s}function Sd({ides:t,emptyMessage:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o}){const i=t.filter(c=>c.type==="adhdev-daemon");return i.length===0?e.jsx($o,{icon:e.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||"Run 'adhdev-standalone' to connect a local daemon instance."}):e.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>e.jsx(Id,{ide:c,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o},c.id))})}function va({title:t,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 Ls.createPortal(e.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,children:e.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:[e.jsx("div",{className:"font-semibold text-sm mb-3",children:t}),e.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:s}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.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"}),e.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 Cd(t){const s=t.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...zl,...Fl,...Vl].find(o=>o.id===s||s.includes(o.id)||o.id.includes(s));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:t}}function Id({ide:t,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o}){var V,_;const[i,c]=a.useState("idle"),[d,p]=a.useState(""),[f,m]=a.useState(null),[h,w]=a.useState("idle"),[S,I]=a.useState(""),u=t.version||null,b=((V=t.machine)==null?void 0:V.platform)||((_=t.system)==null?void 0:_.platform)||"",v=kt(t,{fallbackId:t.id}),l=b==="win32"?"🪟":b==="darwin"?"🍎":"🐧",N=s.filter(C=>C.daemonId===t.id&&C.transport==="cdp-page"),A=s.filter(C=>C.daemonId===t.id&&C.transport==="pty"),k=s.filter(C=>C.daemonId===t.id&&C.transport==="acp"),x=t.p2p,g=async()=>{if(r){c("upgrading"),p("Starting upgrade...");try{const C=Nd(await r(t.id,"daemon_upgrade",{}));C.alreadyLatest?(c("done"),p(`Already on v${C.version||"latest"}.`)):C.upgraded||C.success?(c("done"),p(`Upgrade to v${C.version||"latest"} started. Daemon is restarting...`)):(c("error"),p(C.error||"Upgrade failed"))}catch(C){c("error"),p(Kr(C,"Connection lost during upgrade"))}}},y=async()=>{if(m(null),!!n){w("loading");try{await n(t.id),w("done"),I("Machine disconnected.")}catch(C){w("error"),I(Kr(C,"Failed to disconnect"))}}},j=async()=>{if(m(null),!!o){w("loading");try{await o(t.id),w("done"),I('Token revoked. Machine must restart "adhdev-standalone" to reconnect.')}catch(C){w("error"),I(Kr(C,"Failed to revoke token"))}}},E="0.8.51",R=Ko(t,E),K=Ts(t,E),D=N.length+A.length+k.length;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-xl",children:l}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:v}),e.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[e.jsxs("span",{children:[t.id.substring(0,12),"…"]}),u&&e.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${R?"":"bg-bg-secondary"}`,style:R?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",u,!R&&" ✓"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&R&&e.jsx("button",{onClick:g,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${E}`,children:i==="upgrading"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${K?"↑ Update now":`↑ Update${` to v${E}`}`}`}),n&&e.jsx("button",{onClick:()=>m("disconnect"),disabled:h==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),o&&e.jsx("button",{onClick:()=>m("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),e.jsx(gd,{status:t.status==="online"?"online":"error"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[x&&e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${x.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${x.state==="connecting"||x.state==="new"?"animate-pulse":""}`,style:x.state==="connecting"||x.state==="new"?{background:"var(--status-warning)"}:void 0}),e.jsxs("span",{className:"text-text-muted",children:["P2P ",x.state==="connected"?"connected":x.state==="connecting"||x.state==="new"?"connecting...":x.state||"off"]}),x.peers!==void 0&&x.peers>0&&e.jsxs("span",{className:"text-text-muted/60",children:["(",x.peers," peer",x.peers!==1?"s":"",")"]})]}),x&&D>0&&e.jsx("span",{className:"text-border-subtle",children:"·"}),D>0?e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[N.map(C=>{const T=Cd(C.type),z=C.cdpConnected;return e.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[e.jsx("span",{children:T.icon}),e.jsx("span",{children:T.name}),z!==void 0&&e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${z?"bg-green-400":"animate-pulse"}`,style:z?void 0:{background:"var(--status-warning)"},title:z?"CDP connected":"CDP connecting..."})]},C.id)}),A.map(C=>e.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[e.jsx("span",{children:"⌨️"}),e.jsx("span",{children:C.cliName||"CLI"})]},C.id)),k.map(C=>e.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[e.jsx("span",{children:"🔗"}),e.jsx("span",{children:C.cliName||"ACP"})]},C.id))]}):e.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(d||S)&&e.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||h==="error"?"text-red-400":i==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:S||d})]}),f==="disconnect"&&e.jsx(va,{title:"🔌 Disconnect Machine",message:`Disconnect "${v}" 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-standalone" on that machine
41
41
 
42
- Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:j,onCancel:()=>m(null)})]})}const Ad=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Md(){const{preference:t,setPreference:s}=Mn();return e.jsx("div",{className:"flex gap-2",children:Ad.map(r=>e.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 ${t===r.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:t===r.id?{color:"var(--accent-on-primary)"}:void 0,children:[e.jsx("span",{children:r.icon}),r.label]},r.id))})}function Td(t){const s=t.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 _d(t){return{r:parseInt(t.slice(1,3),16),g:parseInt(t.slice(3,5),16),b:parseInt(t.slice(5,7),16)}}function Wr(t){const s=t/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function wa(t){const{r:s,g:r,b:n}=_d(t);return .2126*Wr(s)+.7152*Wr(r)+.0722*Wr(n)}function ja(t,s){const r=wa(t),n=wa(s),o=Math.max(r,n),i=Math.min(r,n);return(o+.05)/(i+.05)}function Wo(t){const s=Td(t);if(!s)return"#111827";const r="#111827",n="#ffffff";return ja(s,r)>=ja(s,n)?r:n}const dn={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},un={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},Pd=[{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"}}}],Oo="adhdev-chat-theme",Ho="adhdev-chat-theme-custom";function cr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Oo)||"ember"}catch{return"ember"}}function Lt(t){try{const s=localStorage.getItem(Ho);if(s){const r=JSON.parse(s);return{...t==="dark"?dn:un,...r[t]}}}catch{}return t==="dark"?dn:un}function Ys(t,s){try{localStorage.setItem(Ho,JSON.stringify({dark:t,light:s}))}catch{}}function At(t,s){const r=parseInt(t.slice(1,3),16),n=parseInt(t.slice(3,5),16),o=parseInt(t.slice(5,7),16);return`rgba(${r}, ${n}, ${o}, ${s})`}function br(t,s){const r=Math.min(255,parseInt(t.slice(1,3),16)+s),n=Math.min(255,parseInt(t.slice(3,5),16)+s),o=Math.min(255,parseInt(t.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 Ld={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function _s(t,s){var o;const r=(o=Ld[t])==null?void 0:o[s];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",br(r,24)),n.style.setProperty("--accent-on-primary",Wo(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${br(r,18)})`),n.style.setProperty("--border-accent",At(r,.35)),n.style.setProperty("--nav-active-bg",At(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${At(r,.06)}`)}function Xt(t){const s=document.documentElement;s.style.setProperty("--bg-primary",t.bgPrimary),s.style.setProperty("--bg-secondary",t.bgSecondary),s.style.setProperty("--bg-card",At(t.surfacePrimary,.92)),s.style.setProperty("--surface-primary",t.surfacePrimary),s.style.setProperty("--surface-secondary",t.bgSecondary),s.style.setProperty("--bg-glass",At(t.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",At(t.borderSubtle,.25)),s.style.setProperty("--text-primary",t.textPrimary),s.style.setProperty("--text-secondary",t.textSecondary),s.style.setProperty("--text-muted",t.textMuted),s.style.setProperty("--border-subtle",At(t.borderSubtle,.5)),s.style.setProperty("--border-default",At(t.borderDefault,.5)),s.style.setProperty("--accent-primary",t.accentColor),s.style.setProperty("--accent-primary-light",br(t.accentColor,30)),s.style.setProperty("--accent-on-primary",Wo(t.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${t.accentColor}, ${br(t.accentColor,40)})`),s.style.setProperty("--border-accent",At(t.accentColor,.35)),s.style.setProperty("--nav-active-bg",At(t.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${t.accentColor}, 0 0 12px ${At(t.accentColor,.06)}`),s.style.setProperty("--chat-user-bg",t.userBubble),s.style.setProperty("--chat-user-color",t.userText),s.style.setProperty("--chat-user-radius",`${t.bubbleRadius}px ${t.bubbleRadius}px 4px ${t.bubbleRadius}px`),s.style.setProperty("--chat-assistant-bg",t.assistantBubble),s.style.setProperty("--chat-assistant-color",t.assistantText),s.style.setProperty("--chat-assistant-radius",`${t.bubbleRadius}px ${t.bubbleRadius}px ${t.bubbleRadius}px 4px`),s.style.setProperty("--chat-assistant-border",`1px solid ${At(t.accentColor,.12)}`),s.style.setProperty("--chat-container-bg",t.containerBg),s.style.setProperty("--dashboard-pane-bg",t.containerBg),s.style.setProperty("--chat-thought-accent",t.accentColor),s.style.setProperty("--chat-tool-accent",t.accentColor),s.style.setProperty("--chat-action-color",t.accentColor),s.style.setProperty("--chat-send-bg",t.sendButton),s.style.setProperty("--chat-input-border",t.inputBorder)}function Tn(){const t=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=>t.style.removeProperty(r))}function Rd(t){try{localStorage.setItem(Oo,t)}catch{}if(document.documentElement.setAttribute("data-chat-theme",t),t==="custom"){const s=Jt()?"dark":"light";Xt(Lt(s))}else Tn(),_s(t,Jt()?"dark":"light")}function Dd(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const t=cr();if(document.documentElement.setAttribute("data-chat-theme",t),t==="custom"){const s=Jt()?"dark":"light";Xt(Lt(s))}else Tn(),_s(t,Jt()?"dark":"light")}function Jt(){const t=document.documentElement.getAttribute("data-theme");return t?t==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function ft({label:t,value:s,onChange:r}){return e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[e.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:t}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[e.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}}),e.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 js({title:t,children:s}){return e.jsxs("div",{style:{marginBottom:14},children:[e.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:t}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s})]})}function Ed({dark:t,onColorsChange:s}){const r=t?"dark":"light",[n,o]=a.useState(()=>Lt(r));a.useEffect(()=>{o(Lt(r))},[r]);const i=a.useCallback((c,d)=>{o(p=>{const f={...p,[c]:d},h=Lt(r==="dark"?"light":"dark");return r==="dark"?Ys(f,h):Ys(h,f),Xt(f),s(f),f})},[r,s]);return e.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[e.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",e.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[t?"🌙 Dark":"☀️ Light"," mode"]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs(js,{title:"App Background",children:[e.jsx(ft,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),e.jsx(ft,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),e.jsx(ft,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),e.jsxs(js,{title:"App Text",children:[e.jsx(ft,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),e.jsx(ft,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),e.jsx(ft,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),e.jsxs(js,{title:"Borders & Accent",children:[e.jsx(ft,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),e.jsx(ft,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),e.jsx(ft,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),e.jsxs("div",{children:[e.jsxs(js,{title:"Chat Bubbles",children:[e.jsx(ft,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),e.jsx(ft,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),e.jsx(ft,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),e.jsx(ft,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),e.jsxs(js,{title:"Chat Layout",children:[e.jsx(ft,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),e.jsx(ft,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),e.jsx(ft,{label:"Input border",value:n.inputBorder,onChange:c=>i("inputBorder",c)}),e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[e.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[e.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)"}}),e.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),e.jsx("button",{onClick:()=>{const c=t?dn:un,p=Lt(t?"light":"dark");t?Ys(c,p):Ys(p,c),o(c),Xt(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 $d(){const[t,s]=a.useState(cr),[r,n]=a.useState(!0),[o,i]=a.useState(()=>Lt("dark"));a.useEffect(()=>{n(Jt());const p=new MutationObserver(()=>{const h=Jt();n(h);const w=cr();w==="custom"?Xt(Lt(h?"dark":"light")):_s(w,h?"dark":"light")});p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const f=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const h=Jt();n(h);const w=cr();w==="custom"?Xt(Lt(h?"dark":"light")):_s(w,h?"dark":"light")};return f.addEventListener("change",m),()=>{p.disconnect(),f.removeEventListener("change",m)}},[]),a.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?Xt(Lt(r?"dark":"light")):(Tn(),_s(t,r?"dark":"light"))},[t,r]),a.useEffect(()=>{i(Lt(r?"dark":"light"))},[r]);const c=p=>{s(p),Rd(p)},d=[...Pd,{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 e.jsxs("div",{children:[e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:d.map(p=>{const f=t===p.id,m=r?p.preview.dark:p.preview.light,h=p.id==="honey"||p.id==="ember"?"#1a1a1a":p.id==="custom"?o.userText:"#fff";return e.jsxs("button",{onClick:()=>c(p.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:[e.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[e.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:"Hello! How can I help?"}),e.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.userBubble,color:h},children:"Fix the bug please"}),e.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:"On it! ✨"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[f&&e.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-bold text-text-primary",children:p.id==="custom"?"🎨 Custom":p.name}),e.jsx("div",{className:"text-[10px] text-text-muted",children:p.description})]})]})]},p.id)})}),t==="custom"&&e.jsx(Ed,{dark:r,onColorsChange:p=>i(p)})]})}const Uo="adhdev_mobileDashboardMode_v1";function zo(){try{return localStorage.getItem(Uo)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Bd(t){try{localStorage.setItem(Uo,t)}catch{}}function Kd(){const[t,s]=a.useState(!0);return a.useEffect(()=>{s(zo()==="chat")},[]),e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Kt,{size:15})," Mobile Inbox (Chat Mode)"]}),description:t?"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:t,onChange:r=>{s(r),Bd(r?"chat":"workspace")},extra:e.jsx("span",{className:"text-[11px] text-text-muted",children:t?"Chat mode":"Workspace"})})}function Wd(t,s,r){return{...t||{},id:s,type:(t==null?void 0:t.type)||"adhdev-daemon",status:(t==null?void 0:t.status)||"online",timestamp:r.timestamp,platform:r.machine.platform,machine:{...(t==null?void 0:t.machine)||{},...r.machine}}}function Od(t,s){const{sendData:r}=St(),{injectEntries:n,getIdes:o}=pr(),i=Array.from(new Set(t.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(p=>Ot.subscribe({sendData:r},p,{type:"subscribe",topic:"machine.runtime",key:`machine:${p}`,params:{intervalMs:s==null?void 0:s.intervalMs}},f=>{const m=o().find(w=>w.id===p),h=Wd(m,p,f);n([h])}));return()=>{d.forEach(p=>p())}},[i,o,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}const Hd=4e3;function Fo(t,s){const{sendData:r}=St(),[n,o]=a.useState(null),[i,c]=a.useState(!1);return a.useEffect(()=>{if(!t){o(null),c(!1);return}if(!(s!=null&&s.enabled)||!r){c(!1);return}o(null),c(!0);let d=null;const p=Ot.subscribe({sendData:r},t,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${t}`,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 p.initialSendAccepted?d=setTimeout(()=>{c(!1)},Hd):c(!1),()=>{d&&clearTimeout(d),p()}},[t,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 Ud(t){return t.daemonId||(t.routeId.includes(":")?t.routeId.split(":")[0]||null:t.routeId||null)}function Vo(t){const{sendData:s}=St(),[r,n]=a.useState({});return a.useEffect(()=>{const o=Ud(t);if(!o||!t.sessionId||!s){n({});return}const i=Ot.subscribe({sendData:s},o,{type:"subscribe",topic:"session.modal",key:`daemon:${o}:session-modal:${t.sessionId}`,params:{targetSessionId:t.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),Qt.record({interactionId:c.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:t.sessionId,status:c.status,modalButtonCount:Array.isArray(c.modalButtons)?c.modalButtons.length:0}})});return()=>{i()}},[t.daemonId,t.routeId,t.sessionId,s]),r}const Go="adhdev_hiddenTabs";function zd(){try{const t=localStorage.getItem(Go);if(t)return new Set(JSON.parse(t))}catch{}return new Set}function cs(t){try{localStorage.setItem(Go,JSON.stringify([...t]))}catch{}}function Fd(){const[t,s]=a.useState(zd),r=a.useCallback(f=>{s(m=>{const h=new Set(m);return h.has(f)?h.delete(f):h.add(f),cs(h),h})},[]),n=a.useCallback(f=>{s(m=>{if(m.has(f))return m;const h=new Set(m);return h.add(f),cs(h),h})},[]),o=a.useCallback(f=>{s(m=>{if(!m.has(f))return m;const h=new Set(m);return h.delete(f),cs(h),h})},[]),i=a.useCallback(()=>{s(f=>{if(f.size===0)return f;const m=new Set;return cs(m),m})},[]),c=a.useCallback((f,m)=>{s(h=>{const w=new Set(h);for(const S of m)w.add(S);return cs(w),w})},[]),d=a.useCallback((f,m)=>{s(h=>{const w=new Set(h);for(const S of m)w.delete(S);return cs(w),w})},[]),p=a.useCallback(f=>t.has(f),[t]);return{hiddenTabs:t,toggleTab:r,hideTab:n,showTab:o,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:d,isHidden:p}}function Vd({visibleConversations:t,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){a.useEffect(()=>{Ql()},[]);const o=a.useMemo(()=>t.map(i=>({id:i.tabKey,name:So(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[t]);return td(o),a.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(d=>{const p=Date.now(),f={};for(const[m,h]of Object.entries(d))p-h<5e3&&(f[m]=h);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 p=d.filter(f=>f.timestamp>c).slice(-100);return p.length===d.length?d:p})},6e4);return()=>clearInterval(i)},[n]),null}function Gd(t){const s=t.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 Xs(t,s){if(t.length!==s.length)return!1;for(let r=0;r<t.length;r+=1)if(t[r]!==s[r])return!1;return!0}function qd(t,s){const r=Date.now();return t.map(n=>{const o=s[n.tabKey];return o&&r-o<5e3?{...n,messages:[],title:""}:n})}function Yd(t,s){const r=[],n=t.sessionId||t.instanceId;r.push({key:t.id,ref:s[t.id]}),n&&r.push({key:n,ref:s[n]});for(const o of t.childSessions||[]){const i=o.id||o.providerType,c=`${t.id}:${i}`;r.push({key:c,ref:s[c]}),r.push({key:o.id,ref:s[o.id]})}return r}function Xd(t,s){if(t.length!==s.length)return!1;for(let r=0;r<t.length;r+=1)if(t[r].key!==s[r].key||t[r].ref!==s[r].ref)return!1;return!0}function Jd(t){return[...t.messages].reverse().find(s=>!(s!=null&&s._localId))||t.messages[t.messages.length-1]}function Zd(t){const s=Jd(t);if(!s)return`empty:${t.messages.length}`;if(s.id)return`id:${String(s.id)}`;if(s._localId)return`local:${String(s._localId)}`;const r=String(s.role||""),n=ss(s.content).slice(0,240);return`${t.messages.length}:${r}:${n}`}function Qd({ides:t,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:o}){const i=a.useRef([]),c=a.useRef([]),d=a.useRef([]),p=a.useRef([]),f=a.useMemo(()=>{const x=Gd(t);return Xs(i.current,x)?i.current:(i.current=x,x)},[t]),m=a.useMemo(()=>Mo(t),[t]),h=a.useRef(new Map),w=a.useRef(new Map),S=a.useMemo(()=>{const x=new Map,g=[];for(const R of f){const{connectionState:K="new",machineName:D}=To(R,{machineNames:m,connectionStates:s,defaultConnectionState:"new"}),V=Yd(R,r),_=h.current.get(R.id);if(_&&_.ide===R&&_.connectionState===K&&_.machineName===D&&Xd(_.localRefs,V)){x.set(R.id,_),g.push(..._.conversations);continue}const C=In(R,r,{machineNames:m,connectionStates:s,defaultConnectionState:"new"}),T={ide:R,connectionState:K,machineName:D,localRefs:V,conversations:C};x.set(R.id,T),g.push(...C)}h.current=x;const y=new Map,j=R=>{const K=Zd(R),D=w.current.get(R.tabKey);if(D&&D.signature===K)return y.set(R.tabKey,D),D.timestamp;const V={signature:K,timestamp:Io(R)||(D==null?void 0:D.timestamp)||0};return y.set(R.tabKey,V),V.timestamp},E=[...g].sort((R,K)=>xr(R,K,j));return w.current=y,E},[f,r,s,m]),I=a.useMemo(()=>{const x=qd(S,n);return Xs(c.current,x)?c.current:(c.current=x,x)},[S,n]),u=a.useMemo(()=>{const x=new Map,g=Array.from(new Set(I.map(y=>y.routeId)));for(const y of g){const j=Dt(I,y);j&&x.set(y,j)}return x},[I]),b=a.useMemo(()=>{const x=new Map;for(const g of I)if(g.sessionId&&x.set(g.sessionId,g),g.streamSource==="native"&&g.sessionId){const y=u.get(g.routeId);y&&x.set(g.sessionId,y)}return x},[I,u]),v=a.useMemo(()=>{const x=new Map;for(const g of I)g.sessionId&&x.set(g.sessionId,g),x.set(g.routeId,u.get(g.routeId)||g),x.set(g.tabKey,g);return x},[I,u]),l=a.useCallback(x=>{if(x)return b.get(x)},[b]),N=a.useCallback(x=>{if(x)return v.get(x)},[v]),A=a.useMemo(()=>{const x=I.filter(g=>!o.has(g.tabKey));return Xs(d.current,x)?d.current:(d.current=x,x)},[I,o]),k=a.useMemo(()=>{const x=A.map(g=>g.tabKey);return Xs(p.current,x)?p.current:(p.current=x,x)},[A]);return{chatIdes:f,conversations:I,visibleConversations:A,visibleTabKeys:k,resolveConversationBySessionId:l,resolveConversationByTarget:N}}function eu({isMobile:t,urlActiveTab:s,resolveConversationBySessionId:r,setSearchParams:n}){const o=a.useMemo(()=>{var d;return t||!s?null:((d=r(s))==null?void 0:d.tabKey)??null},[t,r,s]),i=a.useMemo(()=>{var d;return!t||!s?null:((d=r(s))==null?void 0:d.tabKey)??null},[t,r,s]),c=a.useCallback(()=>{s&&n(d=>{const p=new URLSearchParams(d);return p.delete("activeTab"),p},{replace:!0})},[n,s]);return{requestedDesktopTabKey:o,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function tu({ides:t,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:o}){a.useEffect(()=>{ht.setIdes(t)},[t]),a.useEffect(()=>{ht.setResolveAction((i,c,d)=>{s(i,c,d).catch(()=>{})})},[s]),a.useEffect(()=>{const i=ht.onToast(p=>{r(m=>m.some(w=>w.message===p.message&&p.timestamp-w.timestamp<3e3)?m:[...m.slice(-4),{id:p.id,message:p.message,type:p.type,timestamp:p.timestamp,targetKey:p.targetKey,actions:p.actions}]);const f=p.duration||5e3;setTimeout(()=>r(m=>m.filter(h=>h.id!==p.id)),f)}),c=ht.onSystemMessage((p,f)=>{var S,I;const m=o(p),h=(S=f._localId)==null?void 0:S.startsWith("sys_approval_"),w=!!(m&&(m.status==="waiting_approval"||(I=m.modalButtons)!=null&&I.length||m.modalMessage));h&&w||n(u=>({...u,[p]:[...u[p]||[],f]}))}),d=ht.onClearSystemMessage((p,f)=>{n(m=>{var h;return(h=m[p])!=null&&h.length?{...m,[p]:m[p].filter(w=>{var S;return!(w.role==="system"&&((S=w._localId)!=null&&S.startsWith(f)))})}:m})});return()=>{i(),c(),d()}},[r,n]),a.useEffect(()=>{const i=jo.on("status_event",c=>{ht.handleRawEvent(c,"ws")});return()=>{i()}},[]),a.useEffect(()=>{var c;const i=d=>{var b;const p=d.data;if((p==null?void 0:p.type)!=="notification_action"||typeof p.action!="string"||!p.action.startsWith("approval_")||!(p.daemonId||p.targetSessionId||p.targetKey))return;const f=p.targetSessionId||p.targetKey||p.daemonId,m=o(f),h=(m==null?void 0:m.routeId)||p.daemonId;if(!h)return;const w=Number(p.buttonIndex),S=p.button||((b=m==null?void 0:m.modalButtons)==null?void 0:b[w])||"Approve",I=String(S).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),u=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(I);s(h,"resolve_action",{action:u?"approve":"reject",button:S,...Number.isFinite(w)&&{buttonIndex:w},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...p.targetSessionId&&{targetSessionId:p.targetSessionId}}).catch(v=>console.error("[SW Action] approval failed:",v))};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 su="adhdev_dashboardLayout_v1",ru="adhdev_dashboardDockview_v1",nu="adhdev_dashboardDockviewHiddenRestore_v1",ks={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function _n(t,s){try{const r=localStorage.getItem(t);return r?JSON.parse(r):s}catch{return s}}function qo(t){return t<768?"mobile":t<1280?"desktop-narrow":"desktop-wide"}function Yo(t){return`${su}:${t}`}function au(t){const s=Yo(t);return _n(s,null)}function ou(t,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=Yo(t);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function Xo(t){return`${ru}:${t}`}function iu(t){const s=Xo(t);return _n(s,null)}function cu(t,s){try{const r=Xo(t);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Jo(t){return`${nu}:${t}`}function lu(t){const s=Jo(t);return _n(s,{})}function du(t,s){try{const r=Jo(t);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function uu(){return{groupAssignments:[...ks.groupAssignments],focusedGroup:ks.focusedGroup,groupActiveTabIds:{...ks.groupActiveTabIds},groupTabOrders:{...ks.groupTabOrders},groupSizes:[...ks.groupSizes]}}function pu(){const[t]=a.useState(()=>qo(typeof window<"u"?window.innerWidth:1280)),[s,r]=a.useState(()=>new Map),[n,o]=a.useState(0),[i,c]=a.useState({}),[d,p]=a.useState({}),[f,m]=a.useState([]),[h,w]=a.useState(()=>typeof window<"u"&&window.innerWidth<768),[S,I]=a.useState(!1),u=a.useCallback(()=>{if(S)return;const b=au(t)??uu();r(new Map(b.groupAssignments)),o(b.focusedGroup),c(b.groupActiveTabIds),p(b.groupTabOrders),m(b.groupSizes),I(!0)},[S,t]);return a.useEffect(()=>{S&&ou(t,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:d,groupSizes:f})},[S,t,s,n,i,d,f]),a.useEffect(()=>{const b=window.matchMedia("(max-width: 767px)"),v=l=>w(l.matches);return b.addEventListener("change",v),()=>b.removeEventListener("change",v)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:o,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:d,setGroupTabOrders:p,groupSizes:f,setGroupSizes:m,isMobile:h,hasHydratedStoredLayout:S,hydrateStoredLayout:u}}function mu(t,s){if(!Array.isArray(t)||t.length!==1||!s)return!1;const r=t[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 fu({urlActiveTab:t,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:o,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:d,setSearchParams:p,historyModalOpen:f,activeConv:m,isRefreshingHistory:h,ides:w,handleRefreshHistory:S}){const I=a.useRef(!1),u=a.useRef(!1),b=a.useRef(null),v=a.useRef(!1);a.useEffect(()=>{if(!t||I.current||s.length===0)return;if(!o){i();return}const l=r(t);if(!l)return;const N=n.get(l.tabKey)??0;c(A=>({...A,[N]:l.tabKey})),d(N),I.current=!0,u.current=!0,b.current!=null&&(window.clearTimeout(b.current),b.current=null),p(A=>{const k=new URLSearchParams(A);return k.delete("activeTab"),k},{replace:!0})},[t,s,r,n,o,i,c,d,p]),a.useEffect(()=>{if(!(u.current||o)&&s.length!==0){if(!t){i(),u.current=!0;return}if(I.current){u.current=!0;return}if(b.current==null)return b.current=window.setTimeout(()=>{b.current=null,!(u.current||o)&&(i(),u.current=!0)},1500),()=>{b.current!=null&&(window.clearTimeout(b.current),b.current=null)}}},[t,s.length,o,i]),a.useEffect(()=>{if(!f){v.current=!1;return}if(!m||v.current||h)return;const l=w.find(N=>N.id===m.routeId);l&&(!l.chats||l.chats.length===0||mu(l.chats,m))&&(v.current=!0,S())},[f,m,h,w,S]),a.useEffect(()=>{if(!m)return;let l=null,N=0,A=-1,k=0;const x=()=>{l=null;const g=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(j=>j.offsetParent!==null);if(g.length===0){N<18&&(N+=1,l=requestAnimationFrame(x));return}let y=0;for(const j of g)j.scrollTop=j.scrollHeight,y+=j.scrollHeight;y===A?k+=1:(k=0,A=y),N+=1,!(k>=2||N>=18)&&(l=requestAnimationFrame(x))};return l=requestAnimationFrame(x),()=>{l!=null&&cancelAnimationFrame(l)}},[m==null?void 0:m.tabKey])}function xu({isMobile:t,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:o,conversations:i,ides:c,resolveConversationByTarget:d}){const[p,f]=a.useState(null),[m,h]=a.useState(null),w=a.useMemo(()=>{if(t||!n)return null;const v=d(n);return v&&!Xe(v)&&!Ve(v)?v:null},[t,n,d]),S=a.useMemo(()=>{const v=p==null?void 0:p.routeId;if(!v)return null;const l=p!=null&&p.tabKey?i.find(N=>N.tabKey===p.tabKey):o?i.find(N=>N.tabKey===o):null;return(l==null?void 0:l.routeId)===v?l:Dt(i,v)},[i,p,o]),I=a.useMemo(()=>{if(S)return c.find(v=>v.id===S.routeId)},[c,S]);a.useEffect(()=>{w&&(f({routeId:w.routeId,tabKey:aa(w)}),h(w),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,w]);const u=a.useCallback(v=>{v&&(f({routeId:v.routeId,tabKey:aa(v)}),h(v))},[]),b=a.useCallback(()=>{f(null),h(null)},[]);return{remoteDialogConv:S,remoteDialogIdeEntry:I,remoteDialogActiveConv:m,setRemoteDialogActiveConv:h,openRemoteDialog:u,closeRemoteDialog:b}}function fs(t){if(!t)return{};const s=t.sessionId?{targetSessionId:t.sessionId}:{};return t.sessionId?s:Xe(t)||Ve(t)?{agentType:jt(t)}:t.streamSource==="agent-stream"?{agentType:jt(t)}:s}function Bs(t){return t?mr(t):""}function Ns(t,s){t(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function Or(t,s){if(!Array.isArray(t)||t.length!==1||!s)return!1;const r=t[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 ka({sendDaemonCommand:t,activeConv:s,chats:r,updateRouteChats:n,setToasts:o,setLocalUserMessages:i,setClearedTabs:c}){const[d,p]=a.useState(!1),[f,m]=a.useState(!1),h=a.useCallback(async u=>{try{await t("standalone","launch_ide",{ideType:u,enableCdp:!0})}catch(b){console.error("Launch failed",b)}},[t]),w=a.useCallback(async(u,b)=>{try{const v=u||(s==null?void 0:s.daemonId)||"",l=await t(v,"switch_chat",{id:b,sessionId:b,...fs(s)}),N=l==null?void 0:l.result;if((l==null?void 0:l.success)===!0||N==="switched"||N==="switched-by-title")return;N===!1||N==="not_found"?Ns(o,"⚠️ Session tab not found — try refreshing history"):typeof N=="string"&&N.startsWith("error:")?Ns(o,`⚠️ Switch error: ${N}`):Ns(o,"⚠️ Session switch failed")}catch(v){console.error("Switch failed",v),Ns(o,`❌ Switch failed: ${v.message||"connection error"}`)}},[s,t,o]),S=a.useCallback(async()=>{if(!(!s||d)){p(!0);try{const u=Bs(s);await t(u,"new_chat",{...fs(s)}),c(b=>({...b,[s.tabKey]:Date.now()})),i(b=>({...b,[s.tabKey]:[]}))}catch(u){console.error("New chat failed",u)}finally{p(!1)}}},[s,d,t,c,i]),I=a.useCallback(async()=>{var u,b;if(!(!s||f)){m(!0);try{const v=Bs(s),l=async()=>t(v,"list_chats",{forceExpand:!0,...fs(s)});let N=await l(),A=(N==null?void 0:N.chats)||((u=N==null?void 0:N.result)==null?void 0:u.chats);Or(A,s)&&(await new Promise(k=>setTimeout(k,450)),N=await l(),A=(N==null?void 0:N.chats)||((b=N==null?void 0:N.result)==null?void 0:b.chats)),N!=null&&N.success&&Array.isArray(A)&&(n(s.routeId,A),Or(A,s)&&!Or(r,s)&&Ns(o,"⚠️ History dialog did not fully open — try once more"))}catch(v){console.error("Refresh history failed",v)}finally{m(!1)}}},[s,r,f,t,n,o]);return{isCreatingChat:d,isRefreshingHistory:f,handleLaunchIde:h,handleSwitchSession:w,handleNewChat:S,handleRefreshHistory:I}}function hu(t,s){if(t.size!==s.size)return!1;for(const[r,n]of t)if(s.get(r)!==n)return!1;return!0}function bu(t,s){return t.length!==s.length?!1:t.every((r,n)=>r===s[n])}function Na(t,s){const r=Object.keys(t),n=Object.keys(s);return r.length!==n.length?!1:r.every(o=>s[Number(o)]===t[Number(o)])}function Js(t,s){const r=new Set(s),n=s.length>0?[0]:[];for(const[c,d]of t)!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 t){if(!r.has(c)||d<=0)continue;const p=o[d];typeof p=="number"&&p>0&&i.set(c,p)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:o,usedGroups:n}}function Sa(t,s){const r={};for(const[n,o]of Object.entries(t)){const i=s[Number(n)];typeof i=="number"&&(r[i]=o)}return r}function gu(t,s,r){if(s.length===0)return 0;if(typeof r[t]=="number")return r[t];const n=[...s].reverse().find(o=>o<t)??s[0];return r[n]??0}function yu(t,s,r){if(s.length<=1)return[];const n=s.map(c=>t[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 Ca(t,s){const r={};for(const[n,o]of Object.entries(t)){const i=Number(n);r[i>=s?i+1:i]=o}return r}function Ia(t){return Array(t).fill(100/t)}function vu({groupAssignments:t,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:o,groupSizes:i,setGroupSizes:c,isMobile:d,visibleConversations:p,visibleTabKeys:f}){const m=a.useRef(null),h=a.useMemo(()=>Js(t,f),[t,f]),w=h.assignments,S=a.useMemo(()=>d?1:h.groupCount,[h.groupCount,d]),I=S>1,u=a.useCallback((k,x)=>{s(g=>{const y=new Map(Js(g,f).assignments);return x===0?y.delete(k):y.set(k,x),y}),n(g=>({...g,[x]:k})),r(x)},[s,f,n,r]),b=a.useCallback(k=>{s(x=>{const g=Js(x,f).assignments,y=new Map;for(const[j,E]of g)E!==k&&(E>k?y.set(j,E-1):y.set(j,E));return y}),c(x=>{if(x.length<=1)return[];const g=[...x];g.splice(k,1);const y=g.reduce((j,E)=>j+E,0);return y>0?g.map(j=>j/y*100):[]}),r(0)},[s,f,c,r]),v=a.useCallback((k,x)=>{x.preventDefault();const g=m.current;if(!g)return;const y=x.clientX,j=g.offsetWidth,E=i.length===S?[...i]:Ia(S),R=D=>{const _=(D.clientX-y)/j*100,C=[...E];C[k]=Math.max(15,E[k]+_),C[k+1]=Math.max(15,E[k+1]-_),c(C)},K=()=>{document.removeEventListener("mousemove",R),document.removeEventListener("mouseup",K),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",R),document.addEventListener("mouseup",K)},[i,S,c]),l=a.useCallback((k,x,g)=>{if(S>=4)return;const y=g==="left"?x:x+1;s(j=>{const E=Js(j,f).assignments,R=new Map;for(const K of p){const D=E.get(K.tabKey)??0,V=D>=y?D+1:D;V>0&&R.set(K.tabKey,V)}return y>0&&R.set(k,y),R}),c(j=>{const E=j.length===S?[...j]:Ia(S),R=E[x]??100/S,K=Math.max(15,R/2),D=Math.max(15,R/2),V=[...E];V[x]=K,V.splice(y,0,D);const _=V.reduce((C,T)=>C+T,0);return V.map(C=>C/_*100)}),n(j=>{const E=Ca(j,y);return E[y]=k,E}),o(j=>{const E=Ca(j,y);return E[y]=[k],E}),r(y)},[S,s,f,p,c,n,o,r]);a.useEffect(()=>{hu(t,w)||s(w)},[t,w,s]),a.useEffect(()=>{const{mapping:k,usedGroups:x}=h;n(g=>{const y=Sa(g,k);return Na(g,y)?g:y}),o(g=>{const y=Sa(g,k);return Na(g,y)?g:y}),r(g=>{const y=d?0:gu(g,x,k);return g===y?g:y}),c(g=>{const y=d?[]:yu(g,x,h.groupCount);return bu(g,y)?g:y})},[h,d,n,o,r,c]);const N=a.useMemo(()=>{const k=Array.from({length:S},()=>[]);for(const x of p){const g=w.get(x.tabKey)??0,y=Math.min(g,S-1);k[y].push(x)}return k},[p,w,S]),A=a.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:m,normalizedGroupAssignments:w,numGroups:S,isSplitMode:I,groupedConvs:N,moveTabToGroup:u,closeGroup:b,handleResizeStart:v,splitTabRelative:l,clearAllSplits:A}}function wu({ides:t,sendDaemonCommand:s}){const r="0.8.50",n=a.useMemo(()=>t.filter(m=>m.type!=="adhdev-daemon"?!1:Ko(m,r)).sort((m,h)=>Number(Ts(h,r))-Number(Ts(m,r))),[r,t]),o=a.useMemo(()=>n.some(m=>Ts(m,r)),[r,n]),[i,c]=a.useState(!1),[d,p]=a.useState({}),f=a.useCallback(async m=>{var h,w;p(S=>({...S,[m]:"upgrading"}));try{const S=await s(m,"daemon_upgrade",{});(h=S==null?void 0:S.result)!=null&&h.upgraded||(w=S==null?void 0:S.result)!=null&&w.success?p(I=>({...I,[m]:"done"})):p(I=>({...I,[m]:"error"}))}catch{p(S=>({...S,[m]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:o,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:f}}function Aa(t){return!t||typeof t!="object"?t:t.result&&typeof t.result=="object"?t.result:t}function Pn(t){return t instanceof Error?t.message:String(t||"")}function Ma(t){const s=Pn(t).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Ta(t,s){const r=Pn(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${t}** failed — button not found`:`⚠️ **${t}** failed — ${r}`:`⚠️ **${t}** unavailable`}function Sr({sendDaemonCommand:t,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:o}){const[i,c]=a.useState(!1),[d,p]=a.useState(!1),f=a.useRef(!1),m=a.useRef(null),h=a.useCallback(async u=>{if(!s)return;const b=u.trim();if(!b||f.current)return;const v=s.tabKey,l=Date.now(),N=m.current;if(N&&N.tabKey===v&&N.message===b&&l-N.timestamp<2e3)return;f.current=!0,p(!0),m.current={tabKey:v,message:b,timestamp:l};const A=`${l}-${Math.random().toString(36).slice(2,8)}`,k={role:"user",content:b,timestamp:l,_localId:A},x=!(Xe(s)||Ve(s));x&&r(g=>({...g,[v]:[...g[v]||[],k]}));try{const g=Bs(s);if(!g)return;const y=await t(g,"send_chat",{message:b,...fs(s)}),j=Aa(y);if(x&&(j!=null&&j.deduplicated||(j==null?void 0:j.sent)===!1)){r(E=>({...E,[v]:(E[v]||[]).filter(R=>R._localId!==A)}));return}if((j==null?void 0:j.success)===!1)throw new Error((j==null?void 0:j.error)||"Send failed");setTimeout(()=>{const E=Date.now()-6e4;r(R=>{const K=R[v];if(!K)return R;const D=K.filter(V=>V.timestamp>E);return D.length===K.length?R:{...R,[v]:D}})},6e4)}catch(g){const y=Pn(g);y.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",y):console.error("Send failed",g),x&&r(j=>({...j,[v]:(j[v]||[]).filter(E=>E._localId!==A)}))}finally{f.current=!1,p(!1)}},[s,t,r]),w=a.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await t(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(u){console.error("Relaunch failed",u)}},[s,t]),S=a.useCallback(async u=>{if(s)try{const v=(s.modalButtons||[]).indexOf(u),l=u.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),N=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(l),A=Bs(s);if(!A)return;const k=await t(A,"resolve_action",{button:u,action:N?"approve":"reject",...v>=0&&{buttonIndex:v},...fs(s)}),x=Aa(k);x.success||n(g=>[...g,{routeId:s.tabKey,text:Ta(u,x==null?void 0:x.error),timestamp:Date.now()}])}catch(b){Ma(b)||console.error("[ModalButton] Error:",b),n(v=>[...v,{routeId:s.tabKey,text:Ma(b)?Ta(u,b):`❌ **${u}** error`,timestamp:Date.now()}])}},[s,t,n]),I=a.useCallback(async()=>{if(!(!s||i)){c(!0);try{await t(s.routeId,"focus_session",{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(u){console.error("Focus agent failed",u)}finally{c(!1)}}},[s,i,t]);return{isSendingChat:d,isFocusingAgent:i,handleSendChat:h,handleRelaunch:w,handleModalButton:S,handleFocusAgent:I}}const Ln=a.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:o,terminalRef:i,handleModalButton:c,handleRelaunch:d,handleSendChat:p,isSendingChat:f,handleFocusAgent:m,isFocusingAgent:h,actionLogs:w,userName:S,scrollToBottomRequestNonce:I,isInputActive:u=!0}){const b=Vo(s),v=b.status||b.modalMessage||b.modalButtons?{...s,...b.status?{status:b.status}:{},...b.modalMessage!==void 0?{modalMessage:b.modalMessage}:{},...b.modalButtons!==void 0?{modalButtons:b.modalButtons}:{}}:s;return e.jsxs(e.Fragment,{children:[e.jsx(po,{activeConv:v,onModalButton:c}),v.transport!=="pty"&&v.transport!=="acp"&&v.cdpConnected===!1?e.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:e.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:[e.jsx("span",{className:"text-sm",children:e.jsx(ts,{size:14})}),e.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),e.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,v.transport==="pty"?e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{display:n?"flex":"none",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:e.jsx(Tl,{activeConv:v,clearToken:r,terminalRef:i,handleSendChat:p,isSendingChat:f,isVisible:n})}),!n&&e.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:e.jsx(nn,{activeConv:v,ideEntry:o,handleSendChat:p,isSendingChat:f,handleFocusAgent:m,isFocusingAgent:h,actionLogs:w,userName:S,scrollToBottomRequestNonce:I,isInputActive:u})})]}):e.jsx(nn,{activeConv:v,ideEntry:o,handleSendChat:p,isSendingChat:f,handleFocusAgent:m,isFocusingAgent:h,actionLogs:w,userName:S,scrollToBottomRequestNonce:I,isInputActive:u})]})},(t,s)=>t.activeConv===s.activeConv&&t.isCliTerminal===s.isCliTerminal&&t.ideEntry===s.ideEntry&&t.terminalRef===s.terminalRef&&t.handleModalButton===s.handleModalButton&&t.handleRelaunch===s.handleRelaunch&&t.handleSendChat===s.handleSendChat&&t.isSendingChat===s.isSendingChat&&t.handleFocusAgent===s.handleFocusAgent&&t.isFocusingAgent===s.isFocusingAgent&&t.actionLogs===s.actionLogs&&t.userName===s.userName&&t.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&t.isInputActive===s.isInputActive);function ju({selectedConversation:t,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:o,userName:i,isSendingChat:c,isFocusingAgent:d,onBack:p,onOpenNativeConversation:f,onOpenMachine:m,onOpenHistory:h,onOpenRemote:w,onHideConversation:S,onStopCli:I,cliViewMode:u,onSetCliViewMode:b,handleSendChat:v,handleFocusAgent:l,handleModalButton:N,handleRelaunch:A}){const k=a.useRef(null),x=Xe(t)&&!s,g=x&&u==="terminal",y=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`flex items-center justify-between gap-3 ${y} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[e.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[e.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:e.jsx(xn,{size:18})}),e.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[e.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:Qe(t)}),e.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:e.jsx(bo,{conversation:t,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>f(t),onOpenMachine:()=>m(t)})})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[x&&u&&e.jsx(Sn,{mode:u,onChange:b,compact:!0}),x&&I&&e.jsx("button",{onClick:()=>{I(t)},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:e.jsx(vt,{size:14})}),e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>h(t),type:"button",children:e.jsx(bn,{size:14})}),!s&&!x&&e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>w(t),type:"button",children:e.jsx(Nt,{size:14})}),S&&e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(t),type:"button",title:"Close chat",children:e.jsx(vt,{size:14})})]})]}),e.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:e.jsx(Ln,{activeConv:t,clearToken:0,isCliTerminal:g,ideEntry:n,terminalRef:k,handleModalButton:N,handleRelaunch:A,handleSendChat:v,isSendingChat:c,handleFocusAgent:l,isFocusingAgent:d,actionLogs:o,userName:i})})]})}const Hr={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 ku(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Zo(){const[t,s]=a.useState("unix"),[r,n]=a.useState("powershell"),[o,i]=a.useState(!1),c=t==="unix"?"unix":r;a.useEffect(()=>{s(ku())},[]);const d=a.useCallback(()=>{navigator.clipboard.writeText(Hr[c].cmd).catch(()=>{}),i(!0),setTimeout(()=>i(!1),2e3)},[c]);return e.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:[e.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[e.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${t==="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"}),e.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${t==="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"})]}),t==="windows"&&e.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[e.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"}),e.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"})]}),e.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:d,title:"Click to copy",children:[e.jsx("span",{className:"text-text-muted select-none",children:Hr[c].prompt}),e.jsx("span",{className:"flex-1 break-all",children:Hr[c].cmd}),e.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:o?"✓":"📋"})]}),e.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",e.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function Qo({section:t,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:Nt},{key:"chats",label:"Chats",icon:Kt}];return e.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:e.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=t===n;return e.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:[e.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:e.jsx(i,{size:15})}),e.jsx("span",{children:o})]},n)})})})}function Zs({title:t,className:s=""}){return e.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${s}`,children:e.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:t})})}function ls({children:t,className:s=""}){return e.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:t})}function Ss({icon:t,title:s,subtitle:r,children:n}){return e.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:[e.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:t}),e.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:s}),e.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function Qs({item:t,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:p,isConnecting:f}=ys(t.conversation),m=Qe(t.conversation),h=ns(t.conversation),w=No(t.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",I=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",b=c?"text-text-muted":"text-text-secondary",v=c?"text-text-secondary opacity-80":"text-text-muted",l=c?"text-text-muted opacity-80":"text-text-muted",N="text-[color:var(--status-warning)]";return e.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(t.conversation),type:"button",children:[o||i?e.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,e.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${I}`,style:o?{color:"var(--accent-on-primary)"}:void 0,children:r(m)}),e.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${u}`,children:m}),!i&&e.jsx("span",{className:`text-[11px] font-medium shrink-0 ${l}`,children:uo(t.timestamp)})]}),e.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${b}`,children:[h,p?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1 opacity-50",children:"·"}),e.jsx("span",{className:`${N} animate-pulse`,children:"Reconnecting…"})]}):f?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1 opacity-50",children:"·"}),e.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):w==="Action needed"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1 opacity-50",children:"·"}),e.jsx("span",{className:N,children:"Action needed"})]})]}),e.jsx("div",{className:`mt-0.5 truncate text-[13px] ${v}`,children:t.preview})]}),o&&!d&&e.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),d&&e.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&&e.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"})]},t.conversation.tabKey)}function _a({size:t=32,label:s}){return e.jsxs("div",{className:"flex flex-col items-center gap-2.5",children:[e.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:t,height:t}}),s&&e.jsx("div",{className:"text-xs font-semibold text-accent-primary-light tracking-tight",children:s})]})}function Nu({section:t,attentionItems:s,unreadItems:r,workingItems:n,completedItems:o,hiddenConversations:i,machineCards:c,getAvatarText:d,onOpenConversation:p,onShowConversation:f,onShowAllHidden:m,onOpenNewSession:h,onOpenMachine:w,onOpenSettings:S,onSectionChange:I,wsStatus:u="connected",isStandalone:b=!1}){const v=u==="disconnected"||u==="reconnecting"||u==="offline"||u==="auth_failed",l=c.length>0,N=s.length>0||r.length>0||n.length>0||o.length>0,A=t==="machines"?"Machines":"Chats",k=b?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",x=b?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]";return e.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[e.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${k}`,children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:A}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[t==="chats"&&(s.length>0||r.length>0)&&e.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:[e.jsx(jr,{size:13}),e.jsx("span",{children:s.length+r.length})]}),e.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:e.jsx(vr,{size:18})})]})]})}),e.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] ${x}`,children:[t==="machines"&&e.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:v?e.jsx(Ss,{icon:e.jsx(_a,{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?e.jsx(Ss,{icon:e.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:b?"Waiting for your daemon":"Connect your first machine",subtitle:b?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install the ADHDev daemon on your machine, then it will show up here.",children:!b&&e.jsx("div",{className:"w-full max-w-[360px] mt-4",children:e.jsx(Zo,{})})}):e.jsx(ls,{children:c.map((g,y)=>e.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${y>0?"border-t border-border-subtle/70":""}`,onClick:()=>w(g.id),type:"button",children:[e.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(g.label)}),e.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:g.label}),e.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:g.unread>0?e.jsxs("span",{className:"text-accent-primary",children:[g.unread," new"]}):g.total>0?`${g.total} chats`:"Idle"})]}),e.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:g.subtitle}),g.total>0?e.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[g.total," chat",g.total!==1?"s":"",g.unread>0?` · ${g.unread} unread`:""]}):e.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},g.id))})}),t==="chats"&&s.length>0&&e.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[e.jsx(Zs,{title:"Needs attention",className:"mb-0"}),e.jsx(ls,{children:s.map((g,y)=>e.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:e.jsx(Qs,{item:g,type:"needs_attention",getAvatarText:d,onOpenConversation:p})},g.conversation.tabKey))})]}),t==="chats"&&r.length>0&&e.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[e.jsx(Zs,{title:"Task complete",className:"mb-0 mt-2"}),e.jsx(ls,{children:r.map((g,y)=>e.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:e.jsx(Qs,{item:g,type:"task_complete",getAvatarText:d,onOpenConversation:p})},g.conversation.tabKey))})]}),t==="chats"&&n.length>0&&e.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[e.jsx(Zs,{title:"Working now",className:"mb-0 mt-2"}),e.jsx(ls,{children:n.map((g,y)=>e.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:e.jsx(Qs,{item:g,type:"working",getAvatarText:d,onOpenConversation:p})},g.conversation.tabKey))})]}),t==="chats"&&e.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[o.length>0&&e.jsx(Zs,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),o.length>0?e.jsx(ls,{children:o.map((g,y)=>e.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:e.jsx(Qs,{item:g,type:"earlier",getAvatarText:d,onOpenConversation:p})},g.conversation.tabKey))}):N?e.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):v?e.jsx(Ss,{icon:e.jsx(_a,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):l?e.jsx(Ss,{icon:e.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:e.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."}):e.jsx(Ss,{icon:e.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."})]}),t==="chats"&&i.length>0&&e.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[e.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:[e.jsx("span",{children:"Hidden"}),e.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:m,children:"Restore all"})]}),e.jsx(ls,{className:"bg-bg-secondary/25",children:i.map((g,y)=>e.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 ${y>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(g),type:"button",children:[e.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(Qe(g))}),e.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:Qe(g)}),e.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),e.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:ns(g)}),e.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},g.tabKey))})]})]}),t==="chats"&&h&&e.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:h,"aria-label":"Start new session",children:e.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),e.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),e.jsx(Qo,{section:t,onSectionChange:I})]})}function Su(t){const s=t.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 Cr(t,s=[]){if(t==="win32"){for(const r of s){if(typeof r!="string")continue;const n=Su(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 Cu(t){const s=t.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 Ir(t,s,r){const n=await t(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=(p,f)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${f}`:p==="/"||p==="\\"?`${i}${f}`:`${p.replace(/[\\/]+$/,"")}${i}${f}`,d=Array.isArray(n==null?void 0:n.files)?n.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:c(o,p.name)})).sort((p,f)=>p.name.localeCompare(f.name)):[];return{path:o,directories:d}}function Ar({title:t,description:s,currentPath:r,directories:n,busy:o=!1,error:i="",confirmLabel:c="Use this folder",onClose:d,onNavigate:p,onConfirm:f}){const[m,h]=a.useState(r);a.useEffect(()=>{h(r)},[r]);const w=Cu(r),S=m.trim();return e.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:e.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:[e.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:t}),e.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),e.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:e.jsx(vt,{size:16})})]}),e.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[e.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:()=>{!w||o||p(w)},disabled:!w||o,children:[e.jsx(xn,{size:15}),"Parent"]}),e.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"text",value:m,onChange:I=>h(I.target.value),onKeyDown:I=>{I.key!=="Enter"||!S||o||(I.preventDefault(),p(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"}),e.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||p(S)},disabled:!S||o,children:"Go"})]})]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:o?e.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):i?e.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):n.length===0?e.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):e.jsx("div",{className:"p-3",children:n.map(I=>e.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:()=>p(I.path),children:[e.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:e.jsx(xs,{size:17})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:I.name}),e.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:I.path})]})]},I.path))})}),e.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-4 border-t border-border-subtle bg-bg-secondary",children:[e.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:d,children:"Cancel"}),e.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 Rn({title:t,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:o,onWorkspaceChange:i,confirmLabel:c="Launch",busy:d=!1,showArgsInput:p,argsValue:f,onArgsChange:m,showModelInput:h,modelValue:w,onModelChange:S,historyProviderNode:I,onConfirm:u,onCancel:b}){const v=n==null?void 0:n.find(l=>l.key===o);return e.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:e.jsxs("div",{className:"w-full max-w-lg rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:t}),e.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),e.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:b,"aria-label":"Close launch confirmation",children:e.jsx(vt,{size:16})})]}),e.jsxs("div",{className:"px-5 py-4 flex flex-col gap-3",children:[n&&n.length>0&&i&&e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),e.jsx("select",{value:o||"",onChange:l=>i(l.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:n.map(l=>e.jsx("option",{value:l.key,children:l.label},l.key))}),(v==null?void 0:v.description)&&e.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:v.description})]}),I,r.map(l=>e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:l.label}),e.jsx("div",{className:"text-sm text-text-primary break-all",children:l.value})]},`${l.label}:${l.value}`)),h&&S&&e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),e.jsx("input",{type:"text",value:w||"",onChange:l=>S(l.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),p&&m&&e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),e.jsx("input",{type:"text",value:f||"",onChange:l=>m(l.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-4 border-t border-border-subtle bg-bg-secondary",children:[e.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:b,disabled:d,children:"Cancel"}),e.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:u,disabled:d,children:[e.jsx(gn,{size:14}),d?"Launching…":c]})]})]})})}function Pa(t,s){return s||t.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||t}function Zt(t){const{machine:s,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:o=!0}=t,i=[];o&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const p of s.workspaces||[])i.push({key:`saved:${p.id}`,label:`${p.id===s.defaultWorkspaceId?"⭐ ":""}${Pa(p.path,p.label)}`,description:p.path,workspaceId:p.id,workspacePath:p.path});const c=(r==null?void 0:r.trim())||"",d=c?(s.workspaces||[]).find(p=>p.path===c):null;if(c&&!d&&i.push({key:`custom:${c}`,label:Pa(c),description:c,workspaceId:null,workspacePath:c}),n){const p=`saved:${n}`;if(i.some(f=>f.key===p))return{options:i,selectedKey:p}}return d?{options:i,selectedKey:`saved:${d.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function Ur(t,s,r){return t?"ide":s>0?"cli":r>0?"acp":null}function Iu({selectedMachineEntry:t,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:o,onListSavedSessions:i}){var ye,F,me,Ce;const c=Hs(),[d,p]=a.useState(!1),f=(((ye=t.detectedIdes)==null?void 0:ye.length)||0)>0,m=a.useMemo(()=>(t.workspaces||[]).map(xe=>({id:xe.id,path:xe.path,label:xe.label})),[t]),h=t.defaultWorkspaceId||null,[w,S]=a.useState(h||((F=m[0])==null?void 0:F.id)||""),[I,u]=a.useState(""),[b,v]=a.useState(""),[l,N]=a.useState([]),[A,k]=a.useState(!1),[x,g]=a.useState(""),[y,j]=a.useState(!1),[E,R]=a.useState(Ur(f,s.length,r.length)),K=a.useRef(null),[D,V]=a.useState(null),_=a.useRef("__home__"),[C,T]=a.useState("__home__"),[z,L]=a.useState(""),[$,H]=a.useState(""),[se,Y]=a.useState(""),[ie,je]=a.useState([]),[G,oe]=a.useState(!1),[W,be]=a.useState(!1),X=a.useRef(null);a.useEffect(()=>{(!t.workspaces||!t.availableProviders||!t.detectedIdes||!t.recentLaunches)&&c(t.id,{minFreshMs:3e4}).catch(()=>{})},[c,t]);const ue=w==="__custom__"?I.trim():((me=m.find(xe=>xe.id===w))==null?void 0:me.path)||"",te=w==="__custom__"&&!!ue&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),ae=w!=="__custom__"&&((Ce=m.find(xe=>xe.id===w))==null?void 0:Ce.path)||"",fe=a.useCallback(async xe=>{k(!0),g("");try{const Le=await o(xe);v(Le.path),u(Le.path),N(Le.directories)}catch(Le){g(Le instanceof Error?Le.message:"Could not load folder")}finally{k(!1)}},[o]),le=a.useCallback(()=>{var Le,Be;S("__custom__"),j(!0);const xe=Cr(t.platform,[I.trim(),ae,(Le=m.find(Fe=>Fe.id===h))==null?void 0:Le.path,(Be=m[0])==null?void 0:Be.path]);fe(xe)},[I,h,fe,ae,t.platform,m]),he=a.useCallback(xe=>{if(xe!=null&&xe.workspaceId){S(xe.workspaceId),u("");return}if(xe!=null&&xe.workspacePath){S("__custom__"),u(xe.workspacePath);return}S(""),u("")},[]),J=a.useCallback(xe=>{if(S(xe),xe==="__custom__"){le();return}u("")},[le]),pe=a.useCallback(xe=>{S("__custom__"),u(xe)},[]),ne=a.useCallback((xe,Le)=>{K.current=Le,_.current=xe.selectedWorkspaceKey||"__home__",T(xe.selectedWorkspaceKey||"__home__"),L(xe.initialArgs||""),H(xe.initialModel||""),Y(""),je([]),V(xe),xe.providerType&&i&&(oe(!0),i(xe.providerType).then(Be=>je(Be||[])).catch(Be=>console.warn("Failed to load saved sessions",Be)).finally(()=>oe(!1)))},[i]),we=a.useCallback(()=>{K.current&&(be(!0),K.current().finally(()=>{K.current=null,be(!1),V(null)}))},[]),ge=a.useCallback(()=>{K.current=null,V(null)},[]),P=a.useCallback(xe=>{_.current=xe,T(xe)},[]);return a.useEffect(()=>{var xe;X.current!==t.id&&(X.current=t.id,S(h||((xe=m[0])==null?void 0:xe.id)||"__custom__"),u(""),v(""),N([]),g(""),j(!1),R(Ur(f,s.length,r.length)))},[r.length,s.length,h,f,t.id,m]),a.useEffect(()=>{var xe;w!=="__custom__"&&(w&&m.some(Le=>Le.id===w)||S(h||((xe=m[0])==null?void 0:xe.id)||"__custom__"))},[h,w,m]),a.useEffect(()=>{E==="ide"&&f||E==="cli"&&s.length>0||E==="acp"&&r.length>0||R(Ur(f,s.length,r.length))},[E,r.length,s.length,f]),{showAllRecent:d,setShowAllRecent:p,hasIdeOptions:f,workspaceRows:m,defaultWorkspaceId:h,workspaceChoice:w,customWorkspacePath:I,browseCurrentPath:b,browseDirectories:l,browseBusy:A,browseError:x,browseDialogOpen:y,activeLauncherKind:E,launchConfirm:D,launchConfirmWorkspaceKeyRef:_,launchConfirmWorkspaceKey:C,launchConfirmArgs:z,launchConfirmModel:$,launchConfirmResumeId:se,launchConfirmSavedSessions:ie,launchConfirmSessionsLoading:G,launchConfirmBusy:W,resolvedWorkspacePath:ue,canCreateMissingWorkspace:te,openBrowseDialog:le,loadBrowsePath:fe,handleWorkspaceChoiceChange:J,chooseCustomWorkspacePath:pe,setCustomWorkspacePath:u,setBrowseDialogOpen:j,setActiveLauncherKind:R,openLaunchConfirm:ne,handleConfirmLaunch:we,closeLaunchConfirm:ge,setWorkspaceSelectionFromOption:he,setLaunchConfirmWorkspaceKeyAndSync:P,setLaunchConfirmArgs:L,setLaunchConfirmModel:H,setLaunchConfirmResumeId:Y}}function Au({selectedMachineEntry:t,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:o,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:d,isStandalone:p,section:f,showBottomNav:m,onBack:h,onSectionChange:w,onOpenConversation:S,onOpenRecent:I,onOpenMachineDetails:u,onMachineUpgrade:b,onLaunchDetectedIde:v,onAddWorkspace:l,onBrowseDirectory:N,onLaunchWorkspaceProvider:A,onListSavedSessions:k}){const x=C=>C==="ide"?"IDE":C==="cli"?"CLI":"ACP",g=r.slice(0,4),y=s.slice(0,3),j=Iu({selectedMachineEntry:t,cliProviders:n,acpProviders:o,machineAction:d,onBrowseDirectory:N,onListSavedSessions:k}),E=a.useMemo(()=>g.map(C=>({key:`recent-launch:${C.id}`,primary:C.label,secondary:`${x(C.kind)}${C.subtitle?` · ${C.subtitle}`:""}`,onClick:()=>{const{options:T,selectedKey:z}=Zt({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspacePath:C.workspace});j.openLaunchConfirm({title:`Launch ${C.label}?`,description:"Recent launches require one more confirmation before they run.",confirmLabel:"Launch",workspaceOptions:T,selectedWorkspaceKey:z,details:[{label:"Mode",value:x(C.kind)},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]},async()=>{const L=T.find($=>$.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption(L),await I({...C,workspace:(L==null?void 0:L.workspacePath)??null})})}})),[j,I,g]),R=a.useMemo(()=>y.map(C=>({key:`recent-chat:${C.conversation.tabKey}`,primary:Qe(C.conversation),secondary:Cl(C.conversation,{timestampLabel:C.timestamp?uo(C.timestamp):null}),unread:C.unread,onClick:()=>S(C.conversation)})),[S,y]),K=j.showAllRecent?E:E.slice(0,4),D=E.length>0,V=R.length>0,_=p?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:`flex items-center justify-between gap-3 ${_} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:e.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[e.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:h,type:"button","aria-label":"Back",children:e.jsx(xn,{size:18})}),e.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[e.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:kt(t,{fallbackId:t.id})}),e.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[t.platform||"machine",t.version?` · v${t.version}`:""]})]})]})}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[V&&e.jsxs("section",{className:"flex flex-col gap-0",children:[e.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),e.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:R.map(C=>e.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:[e.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))})]}),D&&e.jsxs("section",{className:"flex flex-col gap-0",children:[e.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),e.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:K.map(C=>e.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:[e.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))}),E.length>4&&e.jsx("div",{className:"flex justify-center px-4 pt-2",children:e.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>j.setShowAllRecent(C=>!C),children:j.showAllRecent?"Show fewer":`Show ${E.length-4} more`})})]}),(j.hasIdeOptions||n.length>0||o.length>0)&&e.jsxs("section",{className:"flex flex-col gap-0",children:[e.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),e.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:e.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:[e.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),e.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),e.jsx("select",{value:j.workspaceChoice,onChange:C=>j.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:j.workspaceRows.length>0?e.jsxs(e.Fragment,{children:[j.workspaceRows.map(C=>e.jsxs("option",{value:C.id,children:[C.id===j.defaultWorkspaceId?"⭐ ":"",kr(C.path,C.label)||C.path]},C.id)),e.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):e.jsx("option",{value:"__custom__",children:"Select workspace…"})}),j.workspaceChoice==="__custom__"&&e.jsxs("div",{className:"flex flex-col gap-2.5",children:[e.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.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:e.jsx(xs,{size:17})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),e.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:j.resolvedWorkspacePath||j.browseCurrentPath||"No folder selected yet."})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-secondary text-[12px] font-bold",onClick:j.openBrowseDialog,children:"Select workspace…"}),e.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-accent-primary/30 bg-accent-primary/10 text-text-primary text-[12px] font-bold disabled:opacity-40",onClick:()=>{j.resolvedWorkspacePath&&l(j.resolvedWorkspacePath)},disabled:!j.resolvedWorkspacePath||j.browseBusy,children:"Save as workspace"})]})]}),j.resolvedWorkspacePath&&e.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[j.hasIdeOptions&&e.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${j.activeLauncherKind==="ide"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>j.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&e.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${j.activeLauncherKind==="cli"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>j.setActiveLauncherKind("cli"),children:"CLI"}),o.length>0&&e.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${j.activeLauncherKind==="acp"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>j.setActiveLauncherKind("acp"),children:"ACP"})]}),j.activeLauncherKind&&e.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[e.jsx("div",{className:"text-xs font-bold text-text-secondary",children:j.activeLauncherKind==="ide"?"Choose an IDE":j.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),e.jsx("div",{className:"grid grid-cols-1 gap-2",children:j.activeLauncherKind==="ide"?(t.detectedIdes||[]).slice(0,6).map(C=>e.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:T,selectedKey:z}=Zt({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspaceId:j.workspaceChoice!=="__custom__"?j.workspaceChoice:null,currentWorkspacePath:j.resolvedWorkspacePath});j.openLaunchConfirm({title:`Launch ${C.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:T,selectedWorkspaceKey:z,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:C.name}]},async()=>{const L=T.find($=>$.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption(L),v(C.type,{workspacePath:(L==null?void 0:L.workspacePath)??null})})},children:[e.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:C.name}),e.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath||"Use selected workspace"})]},C.type)):(j.activeLauncherKind==="cli"?n:o).map(C=>e.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 T=j.activeLauncherKind==="cli"?"cli":"acp",{options:z,selectedKey:L}=Zt({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspaceId:j.workspaceChoice!=="__custom__"?j.workspaceChoice:null,currentWorkspacePath:j.resolvedWorkspacePath});j.openLaunchConfirm({title:`Launch ${C.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${T.toUpperCase()}`,workspaceOptions:z,selectedWorkspaceKey:L,details:[{label:"Mode",value:T.toUpperCase()},{label:"Provider",value:C.displayName}],showArgsInput:!0,showModelInput:T==="acp",initialArgs:"",initialModel:"",providerType:C.type},async()=>{const $=z.find(H=>H.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption($),A(T,C.type,{workspaceId:($==null?void 0:$.workspaceId)??null,workspacePath:($==null?void 0:$.workspacePath)??null,args:j.launchConfirmArgs,model:j.launchConfirmModel,resumeSessionId:j.launchConfirmResumeId||null})})},children:[e.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[C.icon?`${C.icon} `:"",C.displayName]}),e.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath||"Use selected workspace"})]},C.type))})]}),d.message&&e.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,j.canCreateMissingWorkspace&&e.jsx("div",{className:"mt-2",children:e.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(j.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),e.jsxs("section",{className:"flex flex-col gap-0",children:[e.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),e.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[i&&e.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:b,children:[e.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),e.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:[e.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),j.browseDialogOpen&&e.jsx(Ar,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:j.browseCurrentPath,directories:j.browseDirectories,busy:j.browseBusy,error:j.browseError,confirmLabel:"Use this folder",onClose:()=>j.setBrowseDialogOpen(!1),onNavigate:C=>{j.loadBrowsePath(C)},onConfirm:C=>{j.chooseCustomWorkspacePath(C),j.setBrowseDialogOpen(!1)}}),j.launchConfirm&&e.jsx(Rn,{title:j.launchConfirm.title,description:j.launchConfirm.description,details:j.launchConfirm.details,workspaceOptions:j.launchConfirm.workspaceOptions,selectedWorkspaceKey:j.launchConfirmWorkspaceKey,onWorkspaceChange:j.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:j.launchConfirm.confirmLabel,busy:j.launchConfirmBusy,showArgsInput:j.launchConfirm.showArgsInput,argsValue:j.launchConfirmArgs,onArgsChange:j.setLaunchConfirmArgs,showModelInput:j.launchConfirm.showModelInput,modelValue:j.launchConfirmModel,onModelChange:j.setLaunchConfirmModel,historyProviderNode:j.launchConfirm.providerType&&(j.launchConfirmSessionsLoading||j.launchConfirmSavedSessions.length>0)&&e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume from history"}),j.launchConfirmSessionsLoading&&e.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),e.jsxs("select",{value:j.launchConfirmResumeId,onChange:C=>j.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:j.launchConfirmBusy||j.launchConfirmSessionsLoading,children:[e.jsx("option",{value:"",children:"Start a new session"}),j.launchConfirmSavedSessions.map(C=>e.jsxs("option",{value:C.providerSessionId,disabled:!C.canResume,children:[C.title||C.providerSessionId," ",C.canResume?"":"(workspace missing)"]},C.providerSessionId))]})]}),onConfirm:j.handleConfirmLaunch,onCancel:j.closeLaunchConfirm}),m&&e.jsx(Qo,{section:f,onSectionChange:w})]})}function ei(t){var r;const s=((r=t.p2p)==null?void 0:r.state)||"";return s==="connected"?"Connected":s==="connecting"||s==="new"||s==="checking"?"Connecting":"Offline"}function Mu(t,s){if(!t)return[];const r=t.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===t.id).map(n=>{var i,c,d,p,f;const o=$s(n)?"cli":ms(n)?"acp":"ide";return{id:`${o}:${n.type}:${n.workspace||""}`,label:((i=n.activeChat)==null?void 0:i.title)||($s(n)?n.cliName||n.type:ms(n)&&n.cliName||n.type),kind:o,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:ms(n)?n.currentModel||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,currentModel:n.currentModel,timestamp:((f=(p=(d=(c=n.activeChat)==null?void 0:c.messages)==null?void 0:d.at)==null?void 0:p.call(d,-1))==null?void 0:f.timestamp)||0}}).sort((n,o)=>o.timestamp-n.timestamp).map(({timestamp:n,...o})=>o)}function Tu(t,s){const r=new Map;for(const n of s){const o=zt(n.conversation),i=r.get(o);i?i.push(n):r.set(o,[n])}return t.map(n=>{const o=r.get(n.id)||[],i=[...o].sort((h,w)=>w.timestamp-h.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,d=rn(n),p=o.filter(h=>h.unread||h.requiresAction).length,f=ei(n),m=[n.platform||"machine",f].filter(Boolean);return{id:n.id,label:kt(n,{fallbackId:n.id}),subtitle:m.join(" · "),unread:p,total:o.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:d,preview:c?Il(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 er(t,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] ${t}`,s)}catch{}}function _u({conversations:t,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:o,screen:i,liveSessionInboxState:c,sendDaemonCommand:d,requestedActiveTabKey:p,onRequestedActiveTabConsumed:f,requestedMachineId:m,onRequestedMachineConsumed:h,requestedMobileSection:w,onRequestedMobileSectionConsumed:S,setSelectedTabKey:I,setScreen:u,setSelectedMachineId:b,setSection:v,setMachineBackTarget:l,resetMachineAction:N}){const A=a.useRef(null),k=a.useCallback(x=>{if(!(x!=null&&x.sessionId))return;const g=Ds(x,c),y=Math.max(Date.now(),Ht(x),g.lastUpdated||0);er("mark_read:start",{tabKey:x.tabKey,sessionId:x.sessionId,displayPrimary:Qe(x),inboxBucket:g.inboxBucket,unread:g.unread,lastSeenAt:g.lastSeenAt,lastUpdated:g.lastUpdated,activityAt:Ht(x),readAt:y}),d(zt(x)||x.routeId,"mark_session_seen",{sessionId:x.sessionId,seenAt:y}).then(j=>{er("mark_read:result",{tabKey:x.tabKey,sessionId:x.sessionId,result:j})}).catch(j=>{er("mark_read:error",{tabKey:x.tabKey,sessionId:x.sessionId,error:j instanceof Error?j.message:String(j)})})},[c,d]);return a.useEffect(()=>{var g;if(!n){u("inbox"),I(((g=t[0])==null?void 0:g.tabKey)||null),A.current=null;return}if(i!=="chat"){A.current=null;return}const x=`${n.tabKey}:${n.sessionId||""}`;A.current!==x&&(A.current=x,k(n))},[t,k,i,n,u,I]),a.useEffect(()=>{if(!p)return;const x=t.find(g=>g.tabKey===p);x&&(I(x.tabKey),u("chat"),f==null||f())},[t,f,p,u,I]),a.useEffect(()=>{if(!m)return;const x=s.find(g=>g.id===m);x&&(b(x.id),N(),v("machines"),l("inbox"),u("machine"),h==null||h())},[s,h,m,N,l,u,v,b]),a.useEffect(()=>{w&&(v(w),u("inbox"),S==null||S())},[S,w,u,v]),a.useEffect(()=>{const x=r.filter(g=>g.inboxBucket==="task_complete"||g.unread);x.length!==0&&er("inbox_state",{screen:i,selectedTabKey:o,items:x.map(g=>{const y=Ds(g.conversation,c);return{liveState:y,tabKey:g.conversation.tabKey,sessionId:g.conversation.sessionId,displayPrimary:Qe(g.conversation),serverBucket:y.inboxBucket,computedBucket:g.inboxBucket,serverUnread:y.unread,computedUnread:g.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,activityAt:Ht(g.conversation)}})})},[r,c,i,o]),{markConversationRead:k}}function Pu(t){if(!t)return"";const s=String(t);return s.includes(":")&&s.split(":")[0]||s}function La(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Lu(t){return(t instanceof Error?t.message:String(t||"")).includes("P2P command timeout")}function Ru({sendDaemonCommand:t,navigate:s,ides:r,conversations:n}){const[o,i]=a.useState("idle"),[c,d]=a.useState(""),[p,f]=a.useState(null),m=a.useCallback(()=>{i("idle"),d(""),f(null)},[]),h=a.useCallback(async(l,N,A)=>{var k;try{i("loading"),d(`Launching ${N}…`);const x={ideType:N,enableCdp:!0};(k=A==null?void 0:A.workspacePath)!=null&&k.trim()&&(x.workspace=A.workspacePath.trim()),await t(l,"launch_ide",x),i("done"),d(`${N} launch requested`)}catch(x){i("error"),d(x instanceof Error?x.message:"Launch IDE failed"),console.error("Launch IDE failed",x)}},[t]),w=a.useCallback(async(l,N,A)=>{if(N.trim())try{i("loading"),d(A!=null&&A.createIfMissing?"Creating folder…":"Saving workspace…");const k=await t(l,"workspace_add",{path:N.trim(),createIfMissing:(A==null?void 0:A.createIfMissing)===!0});if(k!=null&&k.success){i("done"),d(A!=null&&A.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")}},[t]),S=a.useCallback(async l=>{var N,A,k,x,g,y;try{i("loading"),d("Starting daemon upgrade…");const j=await t(l,"daemon_upgrade",{});if((N=j==null?void 0:j.result)!=null&&N.alreadyLatest){i("done"),d(`Already on v${((A=j==null?void 0:j.result)==null?void 0:A.version)||"latest"}.`);return}if((k=j==null?void 0:j.result)!=null&&k.upgraded||(x=j==null?void 0:j.result)!=null&&x.success){i("done"),d(`Upgrade to v${((g=j==null?void 0:j.result)==null?void 0:g.version)||"latest"} started. Daemon is restarting…`);return}i("error"),d(((y=j==null?void 0:j.result)==null?void 0:y.error)||"Upgrade failed")}catch(j){i("error"),d(j instanceof Error?j.message:"Upgrade failed")}},[t]),I=a.useCallback(async(l,N,A,k)=>{var y,j,E;const x=Date.now(),g={machineId:l,kind:N,providerType:A,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:x};try{i("loading"),d(`Launching ${A}…`),f(g);const R={cliType:A};(y=k==null?void 0:k.workspacePath)!=null&&y.trim()?R.dir=k.workspacePath.trim():k!=null&&k.workspaceId&&(R.workspaceId=k.workspaceId),k!=null&&k.resumeSessionId&&(R.resumeSessionId=k.resumeSessionId),(j=k==null?void 0:k.args)!=null&&j.trim()&&(R.cliArgs=k.args.trim().split(/\s+/).filter(Boolean)),(E=k==null?void 0:k.model)!=null&&E.trim()&&(R.initialModel=k.model.trim());const K=await t(l,"launch_cli",R),D=(K==null?void 0:K.result)||K,V=(D==null?void 0:D.sessionId)||(D==null?void 0:D.id);if(K!=null&&K.success&&V){f(null),i("done"),d(`${A} launched`),s(`/dashboard?activeTab=${encodeURIComponent(V)}`);return}if(K!=null&&K.success){i("loading"),d(`${A} launch requested — waiting for session…`);return}f(null),i("error"),d((K==null?void 0:K.error)||(D==null?void 0:D.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(R){if(Lu(R)){i("loading"),d(`${A} launch requested — waiting for session…`);return}f(null),i("error"),d(R instanceof Error?R.message:`Could not launch ${N.toUpperCase()} workspace`)}},[s,t]),u=a.useCallback(async(l,N)=>{try{const A=await t(l,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),k=(A==null?void 0:A.result)??A;return Array.isArray(k==null?void 0:k.sessions)?k.sessions:[]}catch(A){return console.error("Failed to list saved sessions on mobile:",A),[]}},[t]),b=a.useCallback(async(l,N)=>Ir(t,l,N),[t]);a.useEffect(()=>{var k;if(!p)return;const l=La(p.workspacePath),N=r.find(x=>{var K,D,V,_;if(!x||x.type==="adhdev-daemon"||Pu(x.daemonId||x.id)!==p.machineId||(x.transport==="acp"?"acp":x.transport==="pty"?"cli":null)!==p.kind||String(x.agentType||x.type||"")!==p.providerType)return!1;const E=String(x.providerSessionId||"");if(p.resumeSessionId&&E)return E===p.resumeSessionId;if(l){const C=La(x.workspace||x.runtimeWorkspaceLabel);return C?C===l:!1}return Number(x.lastUpdated||x._lastUpdate||x.timestamp||((_=(V=(D=(K=x.activeChat)==null?void 0:K.messages)==null?void 0:D.at)==null?void 0:V.call(D,-1))==null?void 0:_.timestamp)||0)>=p.startedAt-5e3});if(!N)return;const A=typeof N.sessionId=="string"&&N.sessionId?N.sessionId:typeof N.instanceId=="string"&&N.instanceId?N.instanceId:(k=n.find(x=>x.routeId===N.id))==null?void 0:k.sessionId;A&&(f(null),i("done"),d(`${p.providerType} launched`),s(`/dashboard?activeTab=${encodeURIComponent(A)}`))},[n,r,s,p]),a.useEffect(()=>{if(!p)return;const l=window.setTimeout(()=>{f(N=>!N||N.startedAt!==p.startedAt?N:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(l)},[p]);const v=a.useCallback(async(l,N)=>{if(N.kind==="ide"&&N.providerType){await h(l,N.providerType,{workspacePath:N.workspace||null});return}(N.kind==="cli"||N.kind==="acp")&&N.providerType&&await I(l,N.kind,N.providerType,{workspacePath:N.workspace||null,resumeSessionId:N.providerSessionId||null})},[h,I]);return{machineAction:{state:o,message:c},resetMachineAction:m,handleLaunchDetectedIde:h,handleAddWorkspace:w,handleMachineUpgrade:S,handleLaunchWorkspaceProvider:I,handleListSavedSessions:u,handleBrowseDirectory:b,handleOpenRecent:v}}function Du({conversations:t,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:o,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:d,setSection:p,setMachineBackTarget:f}){const m=a.useCallback(v=>{i(v.tabKey),c("chat"),n(v)},[n,c,i]),h=a.useCallback(v=>{const l=t.find(N=>N.routeId===v.routeId&&N.streamSource==="native");l&&(i(l.tabKey),c("chat"),n(l))},[t,n,c,i]),w=a.useCallback(()=>{n(s),c("inbox")},[n,s,c]),S=a.useCallback((v,l="inbox")=>{d(v),o(),p("machines"),f(l),c("machine")},[o,f,c,p,d]),I=a.useCallback(v=>{const l=zt(v);l&&S(l,"chat")},[S]),u=a.useCallback(()=>{o(),c(r)},[r,o,c]),b=a.useCallback(v=>{p(v),c("inbox")},[c,p]);return{openConversation:m,openNativeConversation:h,backFromConversation:w,openMachine:S,openConversationMachine:I,backFromMachine:u,changeMachineSection:b}}function Eu(t){const s=t.trim();return s?s[0].toUpperCase():"?"}function $u(t){const s=t instanceof Error?t.message:String(t||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function tr(t){return[...t].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Bu({conversations:t,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:d,userName:p,requestedActiveTabKey:f,onRequestedActiveTabConsumed:m,requestedMachineId:h,onRequestedMachineConsumed:w,requestedMobileSection:S,onRequestedMobileSectionConsumed:I,onOpenHistory:u,onOpenRemote:b,onStopCli:v,wsStatus:l,isConnected:N,onShowHiddenConversation:A,onShowAllHiddenConversations:k,onHideConversation:x,onOpenNewSession:g}){const[y,j]=a.useState(()=>{var F;return((F=t[0])==null?void 0:F.tabKey)||null}),[E,R]=a.useState(()=>t[0]?"chat":"inbox"),[K,D]=a.useState("chats"),[V,_]=a.useState(null),[C,T]=a.useState("inbox"),z=bs(),L="0.8.50",$=a.useMemo(()=>t.find(F=>F.tabKey===y)||t[0]||null,[t,y]),H=a.useMemo(()=>$?r.find(F=>F.id===$.routeId):void 0,[r,$]),se=a.useMemo(()=>!$||Ve($)||!Xe($)?null:hs($),[$]),Y=a.useMemo(()=>r.filter(F=>F.type==="adhdev-daemon").sort(wn),[r]),ie=a.useMemo(()=>Y.find(F=>F.id===V)||null,[Y,V]),je=a.useMemo(()=>Ws(r),[r]),G=Sr({sendDaemonCommand:o,activeConv:$||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:d}),oe=Ru({sendDaemonCommand:o,navigate:z,ides:r,conversations:t}),W=a.useMemo(()=>t.map(F=>{const me=E==="chat"&&($==null?void 0:$.tabKey)===F.tabKey,Ce=Es(F,je,{hideOpenTaskCompleteUnread:!0,isOpenConversation:me}),xe=Ht(F),Le=ko(F);return{conversation:F,timestamp:xe,preview:Le,unread:Ce.unread,requiresAction:Ce.requiresAction,isWorking:Ce.isWorking,inboxBucket:Ce.inboxBucket}}),[t,je,E,$]),{markConversationRead:be}=_u({conversations:t,machineEntries:Y,items:W,selectedConversation:$,selectedTabKey:y,screen:E,liveSessionInboxState:je,sendDaemonCommand:o,requestedActiveTabKey:f,onRequestedActiveTabConsumed:m,requestedMachineId:h,onRequestedMachineConsumed:w,requestedMobileSection:S,onRequestedMobileSectionConsumed:I,setSelectedTabKey:j,setScreen:R,setSelectedMachineId:_,setSection:D,setMachineBackTarget:T,resetMachineAction:oe.resetMachineAction}),X=Du({conversations:t,selectedConversation:$,machineBackTarget:C,markConversationRead:be,resetMachineAction:oe.resetMachineAction,setSelectedTabKey:j,setScreen:R,setSelectedMachineId:_,setSection:D,setMachineBackTarget:T}),ue=a.useMemo(()=>tr(W.filter(F=>F.requiresAction)),[W]),te=a.useMemo(()=>tr(W.filter(F=>F.unread&&!F.requiresAction)),[W]),ae=a.useMemo(()=>tr(W.filter(F=>!F.unread&&!F.requiresAction&&F.isWorking)),[W]),fe=a.useMemo(()=>tr(W.filter(F=>!F.unread&&!F.requiresAction&&!F.isWorking)),[W]),le=a.useMemo(()=>ie?W.filter(F=>zt(F.conversation)===ie.id):[],[W,ie]),he=a.useMemo(()=>Mu(ie,r),[r,ie]),J=(ie==null?void 0:ie.version)||null,pe=!!ie&&!!J&&!0&&J!==L,ne=a.useMemo(()=>(ie==null?void 0:ie.availableProviders)||[],[ie]),we=a.useMemo(()=>ne.filter(F=>F.category==="cli"&&F.installed!==!1).map(F=>({type:F.type,displayName:F.displayName||F.type,icon:F.icon})),[ne]),ge=a.useMemo(()=>ne.filter(F=>F.category==="acp"&&F.installed!==!1).map(F=>({type:F.type,displayName:F.displayName||F.type,icon:F.icon})),[ne]),P=a.useMemo(()=>Tu(Y,W),[W,Y]),ye=a.useCallback(async F=>{ie&&await oe.handleOpenRecent(ie.id,F)},[oe,ie]);return e.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:E==="chat"&&$?e.jsx(ju,{selectedConversation:$,isAcp:Ve($),isStandalone:d,selectedIdeEntry:H,actionLogs:n,userName:p,isSendingChat:G.isSendingChat,isFocusingAgent:G.isFocusingAgent,handleModalButton:G.handleModalButton,handleRelaunch:G.handleRelaunch,onBack:X.backFromConversation,onOpenNativeConversation:X.openNativeConversation,onOpenMachine:X.openConversationMachine,onHideConversation:x,onOpenHistory:u,onOpenRemote:b,onStopCli:v,cliViewMode:se,onSetCliViewMode:async F=>{if($&&se!==F)try{await o(zt($)||$.routeId,"set_cli_view_mode",{targetSessionId:$.sessionId,cliType:jt($),mode:F})}catch(me){$u(me)?console.warn("Skipped CLI view mode switch:",me instanceof Error?me.message:String(me)):console.error("Failed to switch CLI view mode:",me)}},handleSendChat:G.handleSendChat,handleFocusAgent:G.handleFocusAgent}):E==="machine"&&ie?e.jsx(Au,{selectedMachineEntry:ie,selectedMachineConversations:le,selectedMachineRecentLaunches:he,cliProviders:we,acpProviders:ge,selectedMachineNeedsUpgrade:pe,appVersion:L,machineAction:oe.machineAction,isStandalone:d,section:K,showBottomNav:C==="inbox",onBack:X.backFromMachine,onSectionChange:X.changeMachineSection,onOpenConversation:X.openConversation,onOpenRecent:ye,onOpenMachineDetails:()=>z(`/machines/${ie.id}`),onMachineUpgrade:()=>oe.handleMachineUpgrade(ie.id),onLaunchDetectedIde:(F,me)=>oe.handleLaunchDetectedIde(ie.id,F,me),onAddWorkspace:(F,me)=>oe.handleAddWorkspace(ie.id,F,me),onBrowseDirectory:F=>oe.handleBrowseDirectory(ie.id,F),onLaunchWorkspaceProvider:(F,me,Ce)=>oe.handleLaunchWorkspaceProvider(ie.id,F,me,Ce),onListSavedSessions:F=>oe.handleListSavedSessions(ie.id,F)}):e.jsx(Nu,{section:K,attentionItems:ue,unreadItems:te,workingItems:ae,completedItems:fe,hiddenConversations:s,machineCards:P,getAvatarText:Eu,onOpenConversation:X.openConversation,onShowConversation:A,onShowAllHidden:k,onOpenNewSession:g,onOpenMachine:X.openMachine,onOpenSettings:()=>z("/settings"),onSectionChange:D,wsStatus:l,isConnected:N,isStandalone:d})})}function zr(t,s){return!!(t<4&&s&&window.innerWidth>=768)}function Ku({conversations:t,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:o,onClearPreviewOrder:i}){const c=a.useRef(0),[d,p]=a.useState(!1),[f,m]=a.useState(null),h=a.useCallback(()=>{c.current=0,p(!1),m(null)},[]);a.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const w=a.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,p(!0))},[]),S=a.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!zr(s,r)){m("merge");return}const v=b.currentTarget.getBoundingClientRect(),l=b.clientX-v.left,N=v.width/3;l<N?m("split-left"):l>N*2?m("split-right"):m("merge")},[s,r]),I=a.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,p(!1),m(null))},[]),u=a.useCallback(b=>{c.current=0,p(!1);const v=b.dataTransfer.getData("text/tab-key"),l=v?t.some(A=>A.tabKey===v):!1,N=f;if(m(null),i(),!!v){if(b.preventDefault(),N==="split-left"&&zr(s,r)){r==null||r(v,"split-left");return}if(N==="split-right"&&zr(s,r)){r==null||r(v,"split-right");return}if(l){o(v);return}n==null||n(v)}},[t,f,s,r,n,o,i]);return{dragOver:d,dropAction:f,resetDragState:h,handleDragEnter:w,handleDragOver:S,handleDragLeave:I,handleDrop:u}}function Wu(t,s){const r=new Set(s.map(i=>i.tabKey)),n=t.filter(i=>r.has(i)),o=s.filter(i=>!t.includes(i.tabKey)).map(i=>i.tabKey);return[...n,...o]}function Ou({conversations:t,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:o}){const[i,c]=a.useState(s??null),[d,p]=a.useState(r??[]),[f,m]=a.useState(null),h=a.useRef(null),w=a.useRef(null),S=a.useRef(n),I=a.useRef(o);a.useEffect(()=>{S.current=n},[n]),a.useEffect(()=>{I.current=o},[o]),a.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),a.useEffect(()=>{p(g=>{const y=Wu(g,t);return y.length===g.length&&y.every((j,E)=>j===g[E])?g:y})},[t]);const u=a.useMemo(()=>{const g=f??d;if(g.length===0)return t;const y=new Map(g.map((j,E)=>[j,E]));return[...t].sort((j,E)=>{const R=y.get(j.tabKey)??999,K=y.get(E.tabKey)??999;return R-K})},[t,f,d]);a.useEffect(()=>{var y,j;if(u.length===0){i!==null&&(c(null),(y=S.current)==null||y.call(S,null));return}if(i&&u.some(E=>E.tabKey===i))return;const g=u[0].tabKey;g!==i&&(c(g),(j=S.current)==null||j.call(S,g))},[u,i]);const b=a.useMemo(()=>u.find(g=>g.tabKey===i),[u,i]),v=a.useCallback(g=>{var y;c(g),(y=S.current)==null||y.call(S,g)},[]),l=a.useCallback((g,y,j)=>{p(E=>{var V;const R=E.filter(_=>_!==g),K=R.indexOf(y);if(K<0)return E;const D=j==="left"?K:K+1;return R.splice(D,0,g),(V=I.current)==null||V.call(I,R),R}),m(null)},[]),N=a.useCallback((g,y,j)=>{const R=(d.length>0?d:t.map(V=>V.tabKey)).filter(V=>V!==g),K=R.indexOf(y);if(K<0)return;const D=j==="left"?K:K+1;R.splice(D,0,g),h.current=R,m(R)},[d,t]),A=a.useCallback(()=>{var y;const g=h.current;g&&(p(g),(y=I.current)==null||y.call(I,g))},[]),k=a.useCallback(()=>{h.current=null,m(null)},[]),x=a.useCallback(g=>{p(y=>{var E;const j=y.filter(R=>R!==g);return j.push(g),(E=I.current)==null||E.call(I,j),j})},[]);return{activeTabId:i,activeConv:b,sortedConversations:u,previewOrderRef:h,draggingTabRef:w,selectTab:v,handleTabReorder:l,updatePreviewOrder:N,commitPreviewOrder:A,clearPreviewOrder:k,moveTabToEnd:x,setDraggingTabKey:g=>{w.current=g}}}function Hu({dropAction:t,canSplit:s}){return e.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[e.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:t==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:t==="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:e.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"})}),e.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:t==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:t==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:e.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"})}),e.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:t==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:t==="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:e.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 Dn({conversationsCount:t,isSplitMode:s,isStandalone:r,hasRegisteredMachines:n=!1,detectedIdes:o,handleLaunchIde:i}){const c=!r&&!n,d=r?"Waiting for your daemon":n?"No conversations yet":"Connect your first machine",p=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 the ADHDev daemon and link your dashboard to start.";return t===0&&!s&&o&&i?e.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[e.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:e.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),e.jsxs("div",{className:"text-center max-w-lg",children:[e.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:d}),e.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:p}),c&&e.jsx(Zo,{}),r&&o.length>0&&e.jsxs("div",{className:"flex flex-col gap-3 items-center",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wider text-text-muted",children:"Detected IDEs"}),e.jsx("div",{className:"flex flex-wrap gap-2.5 justify-center mt-1",children:o.map(f=>e.jsxs("button",{className:"btn btn-sm bg-accent/10 border border-accent/25 text-accent text-xs font-medium px-4 py-2.5 rounded-lg cursor-pointer flex items-center gap-2 transition-all hover:bg-accent/20 hover:scale-105 active:scale-95",onClick:()=>i(f.type),children:[e.jsx(oo,{size:14,className:"opacity-70"})," Open ",f.name]},f.type))})]}),c&&e.jsx("div",{className:"mt-8",children:e.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 →"})})]})]}):e.jsx("div",{className:"text-sm text-text-muted opacity-50",children:s?"Move a tab here to view":"No active agent"})}const ti="adhdev-tab-shortcuts";function si(){try{return JSON.parse(localStorage.getItem(ti)||"{}")}catch{return{}}}function ri({enabled:t=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const o=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=a.useState(()=>si()),[d,p]=a.useState(null),f=a.useCallback(h=>{const w=[];return h.metaKey&&w.push(o?"⌘":"Meta"),h.ctrlKey&&w.push("Ctrl"),h.altKey&&w.push(o?"⌥":"Alt"),h.shiftKey&&w.push(o?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(w.push(h.key.length===1?h.key.toUpperCase():h.key),w.join("+"))},[o]),m=a.useCallback(h=>{c(h);try{localStorage.setItem(ti,JSON.stringify(h))}catch{}},[]);return a.useEffect(()=>{if(!t||!d)return;const h=w=>{if(w.preventDefault(),w.stopPropagation(),w.key==="Escape"){p(null);return}const S=f(w);if(!S)return;const I={...i};for(const[u,b]of Object.entries(I))b===S&&delete I[u];I[d]=S,m(I),p(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[t,d,i,m,f]),a.useEffect(()=>{if(!t)return;const h=w=>{if(!(!w.ctrlKey&&!w.metaKey&&!w.altKey)){for(const[S,I]of Object.entries(i))if(s.includes(S)&&f(w)===I){w.preventDefault(),r(),n(S);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[t,i,s,r,n,f]),{isMac:o,tabShortcuts:i,shortcutListening:d,setShortcutListening:p,saveShortcuts:m}}const Uu=a.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:o,shortcut:i,conversationKeys:c,draggingTabRef:d,onFocus:p,onSelectTab:f,onConversationActivated:m,onPreviewReorder:h,onReorderTab:w,onCommitPreviewOrder:S,onClearPreviewOrder:I,onDragStateReset:u,onDragTabKeyChange:b,onReceiveTab:v,onOpenContextMenu:l,longPressTimer:N,isGroupActive:A}){const k=ys(s),x=k.isGenerating?"agent-tab-generating":k.isWaiting?"agent-tab-waiting":"",g=k.isReconnecting,y=a.useCallback(T=>{d.current=s.tabKey,b(s.tabKey),T.dataTransfer.setData("text/tab-key",s.tabKey),T.dataTransfer.effectAllowed="move"},[s.tabKey,d,b]),j=a.useCallback(()=>{d.current=null,b(null),S(),I(),u()},[d,b,S,I,u]),E=a.useCallback(T=>{const z=d.current;if(!(!z||z===s.tabKey)&&T.dataTransfer.types.includes("text/tab-key")){T.preventDefault(),T.stopPropagation();const L=T.currentTarget.getBoundingClientRect(),$=T.clientX<L.left+L.width/2?"left":"right";h(z,s.tabKey,$)}},[s.tabKey,d,h]),R=a.useCallback(T=>{T.preventDefault(),T.stopPropagation();const z=T.dataTransfer.getData("text/tab-key");if(z&&z!==s.tabKey){const L=T.currentTarget.getBoundingClientRect(),$=T.clientX<L.left+L.width/2?"left":"right";c.includes(z)?w(z,s.tabKey,$):v&&v(z)}I()},[s.tabKey,c,w,v,I]),K=a.useCallback(T=>{T.stopPropagation(),p(),f(s.tabKey),m(s)},[s,m,p,f]),D=a.useCallback(T=>{T.preventDefault(),l(T.clientX,T.clientY,s.tabKey)},[s.tabKey,l]),V=a.useCallback(T=>{const z=T.touches[0];N.current=setTimeout(()=>{l(z.clientX,z.clientY,s.tabKey)},600)},[s.tabKey,N,l]),_=a.useCallback(()=>{N.current&&clearTimeout(N.current)},[N]),C=["adhdev-dockview-tab",x,r&&"is-active",A&&"is-group-active",g&&"is-reconnecting"].filter(Boolean).join(" ");return e.jsxs("div",{"data-tabkey":s.tabKey,className:C,draggable:!0,onDragStart:y,onDragEnd:j,onDragOver:E,onDrop:R,onClick:K,onContextMenu:D,onTouchStart:V,onTouchEnd:_,onTouchMove:_,style:{cursor:"pointer",opacity:n?.4:void 0},children:[o&&e.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),e.jsx("div",{className:"adhdev-dockview-tab-status",children:k.isGenerating?e.jsx("div",{className:"tab-spinner"}):k.isWaiting?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):g?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):k.isConnecting?e.jsx("div",{className:"tab-connecting-spinner"}):s.connectionState==="connected"?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):e.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),e.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[e.jsx("span",{className:"adhdev-dockview-tab-primary",title:Qe(s),children:Qe(s)}),e.jsx("span",{className:"adhdev-dockview-tab-meta",children:g?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Yt(s)}):k.isConnecting?e.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[Yt(s),e.jsx("span",{className:"connecting-dots"})]}):Yt(s)})]}),i&&e.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})]})},(t,s)=>t.conv===s.conv&&t.isActive===s.isActive&&t.isDraggedTab===s.isDraggedTab&&t.isTaskCompleteUnread===s.isTaskCompleteUnread&&t.shortcut===s.shortcut&&t.conversationKeys===s.conversationKeys&&t.isGroupActive===s.isGroupActive);function zu({conversations:t,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:o,onFocus:i,onSelectTab:c,onConversationActivated:d,onPreviewReorder:p,onReorderTab:f,onCommitPreviewOrder:m,onClearPreviewOrder:h,onDragStateReset:w,onDragTabKeyChange:S,onReceiveTab:I,onHideTab:u,isGroupActive:b,allowTabShortcuts:v=!0}){const[l,N]=a.useState(null),A=a.useRef(null),k=a.useRef(null),x=a.useMemo(()=>t.map(D=>D.tabKey),[t]);Ks("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:t.length,ctxMenuTab:(l==null?void 0:l.tabKey)||null});const{isMac:g,tabShortcuts:y,shortcutListening:j,setShortcutListening:E,saveShortcuts:R}=ri({enabled:v,sortedTabKeys:t.map(D=>D.tabKey),onFocus:i,onSelectTab:c});a.useEffect(()=>{if(!l)return;const D=V=>{const _=document.querySelector("[data-pane-context-menu]");_&&_.contains(V.target)||N(null)};return window.addEventListener("mousedown",D,!0),()=>window.removeEventListener("mousedown",D,!0)},[l]),a.useEffect(()=>{const D=k.current;if(!D)return;const V=_=>{Math.abs(_.deltaY)>Math.abs(_.deltaX)&&(_.preventDefault(),D.scrollLeft+=_.deltaY)};return D.addEventListener("wheel",V,{passive:!1}),()=>D.removeEventListener("wheel",V)},[]);const K=a.useCallback((D,V,_)=>{N({x:D,y:V,tabKey:_})},[]);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:e.jsxs("div",{ref:k,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none"},children:[t.map(D=>e.jsx(Uu,{conv:D,isActive:s===D.tabKey,isDraggedTab:o.current===D.tabKey,isTaskCompleteUnread:n.has(D.tabKey),shortcut:v?y[D.tabKey]:void 0,conversationKeys:x,draggingTabRef:o,onFocus:i,onSelectTab:c,onConversationActivated:d,onPreviewReorder:p,onReorderTab:f,onCommitPreviewOrder:m,onClearPreviewOrder:h,onDragStateReset:w,onDragTabKeyChange:S,onReceiveTab:I,onOpenContextMenu:K,longPressTimer:A,isGroupActive:b},D.tabKey)),t.length===0&&e.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),l&&e.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:[v&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:D=>{D.stopPropagation(),E(l.tabKey),N(null)},children:["⌨ ",y[l.tabKey]?`Change shortcut (${y[l.tabKey]})`:"Set shortcut"]}),y[l.tabKey]&&e.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 D={...y};delete D[l.tabKey],R(D),N(null)},children:"✕ Remove shortcut"})]}),u&&e.jsxs(e.Fragment,{children:[v&&e.jsx("div",{className:"border-t border-border-subtle my-1"}),e.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),N(null)},children:"🚫 Hide from Dashboard"})]})]}),v&&j&&e.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:()=>E(null),children:e.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:D=>D.stopPropagation(),children:[e.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),e.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",g?"⌘+1":"Ctrl+1",", ",g?"⌥+A":"Alt+A",")"]}),e.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),e.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function Fu({conversations:t,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:d,hasRegisteredMachines:p,userName:f,groupIndex:m,onFocus:h,isSplitMode:w,numGroups:S,onMoveTab:I,onReceiveTab:u,style:b,detectedIdes:v,handleLaunchIde:l,onActiveTabChange:N,initialActiveTabId:A,initialTabOrder:k,onTabOrderChange:x,onHideTab:g,isFocused:y,allowTabShortcuts:j=!0}){const{sendCommand:E}=St(),R=a.useRef(null),{activeTabId:K,activeConv:D,sortedConversations:V,draggingTabRef:_,selectTab:C,handleTabReorder:T,updatePreviewOrder:z,commitPreviewOrder:L,clearPreviewOrder:$,moveTabToEnd:H,setDraggingTabKey:se}=Ou({conversations:t,initialActiveTabId:A,initialTabOrder:k,onActiveTabChange:N,onTabOrderChange:x}),Y=Sr({sendDaemonCommand:o,activeConv:D,setLocalUserMessages:i,setActionLogs:c,isStandalone:d}),{dragOver:ie,dropAction:je,resetDragState:G,handleDragEnter:oe,handleDragOver:W,handleDragLeave:be,handleDrop:X}=Ku({conversations:t,numGroups:S,onMoveTab:I,onReceiveTab:u,onOwnTabDrop:H,onClearPreviewOrder:$}),ue=D&&!Ve(D)&&hs(D)==="terminal",te=a.useMemo(()=>D?s.find(J=>J.id===D.routeId):void 0,[s,D]),ae=a.useMemo(()=>D?n.filter(J=>J.routeId===D.tabKey):[],[n,D]),fe=a.useMemo(()=>Ws(s),[s]),le=a.useMemo(()=>new Set(V.filter(J=>Kc(J,fe,{isOpenConversation:J.tabKey===K})).map(J=>J.tabKey)),[K,fe,V]);Ks("PaneGroup",{groupIndex:m,conversationCount:t.length,activeTabId:K,dragOver:ie});const he=a.useCallback(J=>{J.streamSource==="agent-stream"&&J.agentType&&E(J.routeId,"focus_session",{agentType:J.agentType,...J.sessionId&&{targetSessionId:J.sessionId}}).catch(()=>{})},[E]);return e.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:h,style:{...b,outline:ie?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[e.jsx(zu,{conversations:V,activeTabId:K,groupIndex:m,numGroups:S,unreadTabKeys:le,draggingTabRef:_,onFocus:h,onSelectTab:C,onConversationActivated:he,onPreviewReorder:z,onReorderTab:T,onCommitPreviewOrder:L,onClearPreviewOrder:$,onDragStateReset:G,onDragTabKeyChange:se,onMoveTab:I,onReceiveTab:u,onHideTab:g,isGroupActive:y??!1,allowTabShortcuts:j}),e.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:oe,onDragOver:W,onDragLeave:be,onDrop:X,children:[ie&&e.jsx(Hu,{dropAction:je,canSplit:!!(S<4&&I)}),D?e.jsx(Ln,{activeConv:D,clearToken:r[D.tabKey]||0,isCliTerminal:!!ue,ideEntry:te,terminalRef:R,handleModalButton:Y.handleModalButton,handleRelaunch:Y.handleRelaunch,handleSendChat:Y.handleSendChat,isSendingChat:Y.isSendingChat,handleFocusAgent:Y.handleFocusAgent,isFocusingAgent:Y.isFocusingAgent,actionLogs:ae,userName:f,isInputActive:!w||!!y}):e.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:e.jsx(Dn,{conversationsCount:t.length,isSplitMode:w,isStandalone:d,hasRegisteredMachines:p,detectedIdes:v,handleLaunchIde:l})})]})]})}function Vu({containerRef:t,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:o,clearedTabs:i,ides:c,actionLogs:d,sendDaemonCommand:p,setLocalUserMessages:f,setActionLogs:m,isStandalone:h,hasRegisteredMachines:w,userName:S,focusedGroup:I,setFocusedGroup:u,moveTabToGroup:b,splitTabRelative:v,closeGroup:l,handleResizeStart:N,detectedIdes:A,handleLaunchIde:k,groupActiveTabIds:x,setGroupActiveTabIds:g,groupTabOrders:y,setGroupTabOrders:j,toggleHiddenTab:E,allowTabShortcuts:R=!0}){return e.jsx("div",{ref:t,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:o.map((K,D)=>{const V=s&&n.length===r?`${n[D]}%`:void 0;return e.jsxs(et.Fragment,{children:[s&&D>0&&e.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:_=>N(D-1,_),onDoubleClick:()=>l(D),title:"Drag to resize · Double-click to merge",children:e.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),e.jsx(Fu,{style:s?{flexBasis:V??`${100/r}%`,flexGrow:V?0:1,flexShrink:V?0:1}:void 0,conversations:K,clearedTabs:i,ides:c,actionLogs:d,sendDaemonCommand:p,setLocalUserMessages:f,setActionLogs:m,isStandalone:h,hasRegisteredMachines:w,userName:S,groupIndex:D,isFocused:s&&I===D,onFocus:()=>u(D),isSplitMode:s,numGroups:r,onMoveTab:(_,C)=>{C==="left"&&D>0?b(_,D-1):C==="right"&&D<r-1?b(_,D+1):C==="split-left"&&r<4?v(_,D,"left"):C==="split-right"&&r<4&&v(_,D,"right")},onReceiveTab:_=>b(_,D),detectedIdes:D===0?A:void 0,handleLaunchIde:D===0?k:void 0,onActiveTabChange:_=>g(C=>(C[D]??null)===(_??null)?C:{...C,[D]:_}),initialActiveTabId:x[D],initialTabOrder:y[D],onTabOrderChange:_=>j(C=>{const T=C[D]||[];return T.length===_.length&&T.every((z,L)=>z===_[L])?C:{...C,[D]:_}}),onHideTab:E,allowTabShortcuts:R})]},D)})})}function ni({doId:t,targetSessionId:s,connState:r,viewMode:n}){const[o,i]=a.useState(null),[c,d]=a.useState(null);a.useEffect(()=>t?tt.onScreenshot("ide-page",(m,h)=>{if(m!==t)return;const w=new FileReader;w.onload=()=>i(w.result),w.readAsDataURL(h)}):void 0,[t]),a.useEffect(()=>{r!=="connected"&&i(null)},[r]),a.useEffect(()=>{var m;return t?((m=tt.onStatus)==null?void 0:m.call(tt,(h,w)=>{h===t&&w!=null&&w.screenshotUsage&&d(w.screenshotUsage)}))||(()=>{}):void 0},[t]),a.useEffect(()=>{i(null)},[t,s]),a.useEffect(()=>{const f=t?tt.get(t):null;if(!(!f||r!=="connected"))return n!=="chat"&&s?f.startScreenshots(s):f.stopScreenshots(s),()=>{f.stopScreenshots(s)}},[n,r,s,t]);const p=a.useCallback(async(f,m)=>{const h=t?tt.get(t):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(f,m,s)},[t,r,s]);return{connScreenshot:o,screenshotUsage:c,handleRemoteAction:p}}const ai="adhdev-dashboard-action-shortcuts",Gu=1200,qu={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Yu(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function Je(t,s){switch(t){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 oi(t){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:Je("openShortcutHelp",t)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:Je("hideCurrentTab",t)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:Je("toggleHiddenTabs",t)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:Je("openHistoryForActiveTab",t)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:Je("openRemoteForActiveTab",t)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:Je("floatActiveTab",t)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:Je("popoutActiveTab",t)},{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",t)},{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",t)},{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",t)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:Je("focusLeftPane",t)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:Je("focusRightPane",t)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:Je("focusUpPane",t)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:Je("focusDownPane",t)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:Je("moveActiveTabToLeftPane",t)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:Je("moveActiveTabToRightPane",t)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:Je("moveActiveTabToUpPane",t)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:Je("moveActiveTabToDownPane",t)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:Je("triggerPrimaryApprovalAction",t)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:Je("triggerSecondaryApprovalAction",t)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:Je("triggerTertiaryApprovalAction",t)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:Je("setActiveTabShortcut",t)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:Je("selectPreviousGroupTab",t)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:Je("selectNextGroupTab",t)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:Je("toggleCliView",t)}]}function pn(t){if(!(t instanceof HTMLElement))return!1;if(t.isContentEditable)return!0;const s=t.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function gr(t){const s=Object.fromEntries(oi(t).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(ai)||"{}"),n={...s,...r};for(const[o,i]of Object.entries(qu))n[o]===i&&(n[o]=s[o]);return n}catch{return s}}function ii(t){return t===" "?"Space":t==="Escape"?"Esc":t==="ArrowLeft"?"←":t==="ArrowRight"?"→":t==="ArrowUp"?"↑":t==="ArrowDown"?"↓":t.length===1?t.toUpperCase():t}function Xu({enabled:t=!0,onTrigger:s}){const r=Yu(),[n,o]=a.useState(()=>gr(r)),[i,c]=a.useState(null),[d,p]=a.useState([]),f=a.useRef({parts:[],timer:null}),m=a.useCallback(u=>{const b=[];return u.metaKey&&b.push(r?"⌘":"Meta"),u.ctrlKey&&b.push("Ctrl"),u.altKey&&b.push(r?"⌥":"Alt"),u.shiftKey&&u.key.length!==1&&b.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(u.key)?null:(b.push(ii(u.key)),b.join("+"))},[r]),h=a.useCallback(u=>{o(u);try{localStorage.setItem(ai,JSON.stringify(u))}catch{}},[]);a.useEffect(()=>{const u=gr(r),b=Object.entries(n),v=Object.entries(u);b.length===v.length&&b.every(([l,N])=>u[l]===N)||h(u)},[n,r,h]);const w=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}},Gu))},[]);a.useEffect(()=>{if(!i)return;const u=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){c(null),p([]);return}const v=m(b);if(!v)return;const N=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(v);if(d.length===0&&N){p([v]);return}const k=[...d,v].slice(0,2).join(" "),x={...n};for(const[g,y]of Object.entries(x))y===k&&delete x[g];x[i]=k,h(x),c(null),p([])};return window.addEventListener("keydown",u,!0),()=>window.removeEventListener("keydown",u,!0)},[n,m,h,i,d]),a.useEffect(()=>{if(!t||i)return;const u=b=>{if(b.defaultPrevented)return;const v=m(b);if(!v)return;const l=b.metaKey||b.ctrlKey||b.altKey;if(pn(b.target)&&!l)return;const N=f.current.parts,A=l?[v]:[...N.slice(-1),v].slice(-2),k=A.join(" "),x=A[A.length-1],g=Object.entries(n).filter(([,K])=>!!K),y=g.find(([,K])=>K===k);if(y){b.preventDefault(),w(),s(y[0]);return}if(g.some(([,K])=>K.startsWith(`${k} `))){b.preventDefault(),f.current.parts=A,S();return}const E=g.find(([,K])=>K===x);if(E){b.preventDefault(),w(),s(E[0]);return}if(g.some(([,K])=>K.startsWith(`${x} `))){b.preventDefault(),f.current.parts=[x],S();return}w()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[n,S,t,m,s,w,i]),a.useEffect(()=>()=>w(),[w]);const I=a.useMemo(()=>oi(r),[r]);return{isMac:r,actionDefinitions:I,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:d,setShortcutListening:c,setShortcutListeningDraft:p,saveShortcuts:h}}const ci=a.createContext(null);function Mr(){const t=a.useContext(ci);if(!t)throw new Error("DashboardDockviewContext missing");return t}function lr(t){return Qe(t)||t.tabKey}function Ju(t){return`remote:${t}`}function Wt(t){return t.startsWith("remote:")}function Ra(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Fr(t){var r,n,o,i,c;const s=t==null?void 0:t.defaultView;if(s)try{s.focus(),(n=(r=t==null?void 0:t.body)==null?void 0:r.focus)==null||n.call(r),(i=(o=t==null?void 0:t.documentElement)==null?void 0:o.focus)==null||i.call(o),(c=s.requestAnimationFrame)==null||c.call(s,()=>{var d,p;try{s.focus(),(p=(d=t==null?void 0:t.body)==null?void 0:d.focus)==null||p.call(d)}catch{}})}catch{}}function sr(t,s){t.classList.remove(en.className,tn.className),t.classList.add(s==="light"?en.className:tn.className)}function Da(t){return t?Array.from(new Set(t.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 Zu(t){const[,s]=a.useState(0);a.useEffect(()=>{const r=()=>s(o=>o+1),n=[t.api.onDidActiveGroupChange(r),t.api.onDidTitleChange(r),t.api.onDidGroupChange(r),t.containerApi.onDidActivePanelChange(r)];return()=>{for(const o of n)o.dispose()}},[t.api,t.containerApi])}function Qu(t,s,r){var d;const n=[s];let o;for(const p of n){let f;for(const m of p){const h=t.addPanel({id:m.tabKey,component:"conversation",title:lr(m),params:{kind:"conversation",tabKey:m.tabKey},...f?{position:{referencePanel:f,direction:"within"},inactive:!0}:o?{position:{referencePanel:o,direction:"right"},inactive:!0}:{}});f||(f=h.id)}o=f??o}const i=r??((d=s[0])==null?void 0:d.tabKey)??null;if(!i)return;const c=t.getPanel(i);c&&c.group.model.openPanel(c)}function Ea(t,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...t.panels])Wt(n.id)||r.has(n.id)||t.removePanel(n);for(const n of s){const o=t.getPanel(n.tabKey);if(o){o.update({params:{tabKey:n.tabKey}}),o.title!==lr(n)&&o.api.setTitle(lr(n));continue}t.addPanel({id:n.tabKey,component:"conversation",title:lr(n),params:{kind:"conversation",tabKey:n.tabKey},...t.activePanel?{position:{referencePanel:t.activePanel.id,direction:"within"},inactive:!0}:t.panels[0]?{position:{referencePanel:t.panels[0].id,direction:"within"},inactive:!0}:{}})}}function $a(t,s,r){var p,f;const n=r?Ju(r):null;for(const m of[...t.panels])Wt(m.id)&&(!n||m.id!==n)&&t.removePanel(m);if(!r||!n)return;const o=Dt(s,r);if(!o&&t.totalPanels===0)return;const i=t.getPanel(n),c=Co(o);if(i){i.title!==c&&i.api.setTitle(c);return}const d=(o==null?void 0:o.tabKey)??((p=t.activePanel)==null?void 0:p.id)??((f=t.panels.find(m=>!Wt(m.id)))==null?void 0:f.id);t.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...d?{position:{referencePanel:d,direction:"right"},inactive:!0}:{}})}function ep({params:t,api:s}){var h;const r=Mr(),n=a.useRef(null),[o,i]=a.useState(s.isActive),c=r.conversationsByTabKey.get(t.tabKey),d=Sr({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});a.useEffect(()=>{i(s.isActive);const w=[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 w)S.dispose()}},[s]);const p=a.useMemo(()=>c?r.ides.find(w=>w.id===c.routeId):void 0,[r.ides,c]),f=a.useMemo(()=>c?r.actionLogs.filter(w=>w.routeId===c.tabKey):[],[r.actionLogs,c]);if(!c)return e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:e.jsx(Dn,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,detectedIdes:r.detectedIdes,handleLaunchIde:r.handleLaunchIde})});const m=!Ve(c)&&hs(c)==="terminal";return e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:e.jsx(Ln,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:m,ideEntry:p,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:((h=r.scrollToBottomRequest)==null?void 0:h.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:o})})}function tp({params:t}){var p;const s=Mr(),r=a.useMemo(()=>Dt([...s.conversationsByTabKey.values()],t.routeId),[s.conversationsByTabKey,t.routeId]),n=a.useMemo(()=>s.ides.find(f=>f.id===t.routeId),[s.ides,t.routeId]),o=(r==null?void 0:r.daemonId)||((p=r==null?void 0:r.routeId)==null?void 0:p.split(":")[0])||t.routeId.split(":")[0]||t.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:d}=ni({doId:o,targetSessionId:r?Nn(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?e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:e.jsx(lo,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:c,transportType:r.transport,onAction:d})}):e.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 sp(){const t=Mr();return e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:e.jsx(Dn,{conversationsCount:0,isSplitMode:!1,isStandalone:t.isStandalone,hasRegisteredMachines:t.hasRegisteredMachines,detectedIdes:t.detectedIdes,handleLaunchIde:t.handleLaunchIde})})}function rp(t){var S,I;Zu(t);const s=Mr(),r=a.useCallback(u=>{"button"in u&&u.button!==0||t.api.setActive()},[t.api]);if(t.params.kind==="remote"){const u=Dt([...s.conversationsByTabKey.values()],t.params.routeId),b=((S=t.api.group.activePanel)==null?void 0:S.id)===t.api.id,v=t.api.isGroupActive;return e.jsxs("div",{className:`adhdev-dockview-tab${b?" is-active":""}${v?" is-group-active":""}`,title:t.api.title||"Remote","data-tab-key":(u==null?void 0:u.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[e.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:e.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),e.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[e.jsx("div",{className:"adhdev-dockview-tab-primary",children:t.api.title||"Remote"}),e.jsx("div",{className:"adhdev-dockview-tab-meta",children:u!=null&&u.machineName?e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"Live remote view"}),e.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),e.jsx("span",{className:"adhdev-dockview-tab-machine",children:u.machineName})]}):e.jsx("span",{children:"Live remote view"})})]})]})}const n=s.conversationsByTabKey.get(t.params.tabKey);if(!n)return e.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":t.params.tabKey||"",children:e.jsx("div",{className:"adhdev-dockview-tab-copy",children:e.jsx("div",{className:"adhdev-dockview-tab-primary",children:t.api.title||t.params.tabKey})})});const o=((I=t.api.group.activePanel)==null?void 0:I.id)===t.api.id,i=t.api.isGroupActive,c=Es(n,s.liveSessionInboxState,{isOpenConversation:o}),d=c.isReconnecting,p=c.isConnecting,f=c.isGenerating,m=c.isWaiting,h=c.unread,w=s.tabShortcuts[n.tabKey];return e.jsxs("div",{className:`adhdev-dockview-tab${o?" is-active":""}${i?" is-group-active":""}${d?" is-reconnecting":""}`,title:Qe(n),"data-tab-key":t.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:u=>{var b;u.preventDefault(),r(u),s.openTabContextMenu({x:u.clientX,y:u.clientY,tabKey:n.tabKey,sourceDocument:((b=u.target)==null?void 0:b.ownerDocument)??document})},children:[h&&e.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),e.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:f?e.jsx("div",{className:"tab-spinner"}):m?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):d?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):p?e.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):e.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),e.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[e.jsx("div",{className:"adhdev-dockview-tab-primary",children:Qe(n)}),e.jsx("div",{className:"adhdev-dockview-tab-meta",children:d?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Yt(n)}):p?e.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Yt(n)}):e.jsx("span",{children:Yt(n)})})]}),w&&e.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:w,children:w})]})}function np({visibleConversations:t,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:d,hasRegisteredMachines:p,initialDataLoaded:f,userName:m,detectedIdes:h,handleLaunchIde:w,toggleHiddenTab:S,actionShortcuts:I,registerActionHandlers:u,onActiveTabChange:b,requestedActiveTabKey:v,requestedRemoteIdeId:l,onRequestedActiveTabConsumed:N,scrollToBottomRequest:A}){var wt,bt,Tt;const{theme:k}=Mn(),{sendCommand:x}=St(),g=a.useRef(null),y=a.useRef(null),j=a.useRef(!1),E=a.useRef(!1),R=a.useRef(!1),K=a.useRef(null),D=a.useRef([]),[V,_]=a.useState(null),[C,T]=a.useState(!1),[z,L]=a.useState(!1),[$,H]=a.useState(0),se=a.useRef(null),Y=a.useMemo(()=>qo(typeof window<"u"?window.innerWidth:1280),[]),ie=a.useRef(typeof window>"u"?{}:lu(Y)),je=a.useMemo(()=>new Map(t.map(B=>[B.tabKey,B])),[t]),G=a.useMemo(()=>Ws(r),[r]),oe=a.useCallback(()=>{var B;(B=g.current)==null||B.focus()},[]),W=a.useCallback(B=>{const U=document,q=B.document;for(const Z of U.querySelectorAll('link[rel="stylesheet"]')){const Ie=q.createElement("link");Ie.rel="stylesheet",Ie.href=Z.href,Z.crossOrigin&&(Ie.crossOrigin=Z.crossOrigin),q.head.appendChild(Ie)}for(const Z of U.querySelectorAll("style")){const Ie=q.createElement("style");Ie.textContent=Z.textContent,q.head.appendChild(Ie)}const O=[];for(const Z of U.styleSheets)try{for(const Ie of Z.cssRules)Ie instanceof CSSStyleRule&&(Ie.selectorText===":root"||Ie.selectorText==="html")&&O.push(Ie.cssText)}catch{}if(O.length>0){const Z=q.createElement("style");Z.textContent=O.join(`
42
+ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:j,onCancel:()=>m(null)})]})}const Ad=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Md(){const{preference:t,setPreference:s}=Mn();return e.jsx("div",{className:"flex gap-2",children:Ad.map(r=>e.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 ${t===r.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:t===r.id?{color:"var(--accent-on-primary)"}:void 0,children:[e.jsx("span",{children:r.icon}),r.label]},r.id))})}function Td(t){const s=t.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 _d(t){return{r:parseInt(t.slice(1,3),16),g:parseInt(t.slice(3,5),16),b:parseInt(t.slice(5,7),16)}}function Wr(t){const s=t/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function wa(t){const{r:s,g:r,b:n}=_d(t);return .2126*Wr(s)+.7152*Wr(r)+.0722*Wr(n)}function ja(t,s){const r=wa(t),n=wa(s),o=Math.max(r,n),i=Math.min(r,n);return(o+.05)/(i+.05)}function Wo(t){const s=Td(t);if(!s)return"#111827";const r="#111827",n="#ffffff";return ja(s,r)>=ja(s,n)?r:n}const dn={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},un={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},Pd=[{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"}}}],Oo="adhdev-chat-theme",Ho="adhdev-chat-theme-custom";function cr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Oo)||"ember"}catch{return"ember"}}function Lt(t){try{const s=localStorage.getItem(Ho);if(s){const r=JSON.parse(s);return{...t==="dark"?dn:un,...r[t]}}}catch{}return t==="dark"?dn:un}function Ys(t,s){try{localStorage.setItem(Ho,JSON.stringify({dark:t,light:s}))}catch{}}function At(t,s){const r=parseInt(t.slice(1,3),16),n=parseInt(t.slice(3,5),16),o=parseInt(t.slice(5,7),16);return`rgba(${r}, ${n}, ${o}, ${s})`}function br(t,s){const r=Math.min(255,parseInt(t.slice(1,3),16)+s),n=Math.min(255,parseInt(t.slice(3,5),16)+s),o=Math.min(255,parseInt(t.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 Ld={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function _s(t,s){var o;const r=(o=Ld[t])==null?void 0:o[s];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",br(r,24)),n.style.setProperty("--accent-on-primary",Wo(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${br(r,18)})`),n.style.setProperty("--border-accent",At(r,.35)),n.style.setProperty("--nav-active-bg",At(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${At(r,.06)}`)}function Xt(t){const s=document.documentElement;s.style.setProperty("--bg-primary",t.bgPrimary),s.style.setProperty("--bg-secondary",t.bgSecondary),s.style.setProperty("--bg-card",At(t.surfacePrimary,.92)),s.style.setProperty("--surface-primary",t.surfacePrimary),s.style.setProperty("--surface-secondary",t.bgSecondary),s.style.setProperty("--bg-glass",At(t.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",At(t.borderSubtle,.25)),s.style.setProperty("--text-primary",t.textPrimary),s.style.setProperty("--text-secondary",t.textSecondary),s.style.setProperty("--text-muted",t.textMuted),s.style.setProperty("--border-subtle",At(t.borderSubtle,.5)),s.style.setProperty("--border-default",At(t.borderDefault,.5)),s.style.setProperty("--accent-primary",t.accentColor),s.style.setProperty("--accent-primary-light",br(t.accentColor,30)),s.style.setProperty("--accent-on-primary",Wo(t.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${t.accentColor}, ${br(t.accentColor,40)})`),s.style.setProperty("--border-accent",At(t.accentColor,.35)),s.style.setProperty("--nav-active-bg",At(t.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${t.accentColor}, 0 0 12px ${At(t.accentColor,.06)}`),s.style.setProperty("--chat-user-bg",t.userBubble),s.style.setProperty("--chat-user-color",t.userText),s.style.setProperty("--chat-user-radius",`${t.bubbleRadius}px ${t.bubbleRadius}px 4px ${t.bubbleRadius}px`),s.style.setProperty("--chat-assistant-bg",t.assistantBubble),s.style.setProperty("--chat-assistant-color",t.assistantText),s.style.setProperty("--chat-assistant-radius",`${t.bubbleRadius}px ${t.bubbleRadius}px ${t.bubbleRadius}px 4px`),s.style.setProperty("--chat-assistant-border",`1px solid ${At(t.accentColor,.12)}`),s.style.setProperty("--chat-container-bg",t.containerBg),s.style.setProperty("--dashboard-pane-bg",t.containerBg),s.style.setProperty("--chat-thought-accent",t.accentColor),s.style.setProperty("--chat-tool-accent",t.accentColor),s.style.setProperty("--chat-action-color",t.accentColor),s.style.setProperty("--chat-send-bg",t.sendButton),s.style.setProperty("--chat-input-border",t.inputBorder)}function Tn(){const t=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=>t.style.removeProperty(r))}function Rd(t){try{localStorage.setItem(Oo,t)}catch{}if(document.documentElement.setAttribute("data-chat-theme",t),t==="custom"){const s=Jt()?"dark":"light";Xt(Lt(s))}else Tn(),_s(t,Jt()?"dark":"light")}function Dd(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const t=cr();if(document.documentElement.setAttribute("data-chat-theme",t),t==="custom"){const s=Jt()?"dark":"light";Xt(Lt(s))}else Tn(),_s(t,Jt()?"dark":"light")}function Jt(){const t=document.documentElement.getAttribute("data-theme");return t?t==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function ft({label:t,value:s,onChange:r}){return e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[e.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:t}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[e.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}}),e.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 js({title:t,children:s}){return e.jsxs("div",{style:{marginBottom:14},children:[e.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:t}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s})]})}function Ed({dark:t,onColorsChange:s}){const r=t?"dark":"light",[n,o]=a.useState(()=>Lt(r));a.useEffect(()=>{o(Lt(r))},[r]);const i=a.useCallback((c,d)=>{o(p=>{const f={...p,[c]:d},h=Lt(r==="dark"?"light":"dark");return r==="dark"?Ys(f,h):Ys(h,f),Xt(f),s(f),f})},[r,s]);return e.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[e.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",e.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[t?"🌙 Dark":"☀️ Light"," mode"]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs(js,{title:"App Background",children:[e.jsx(ft,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),e.jsx(ft,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),e.jsx(ft,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),e.jsxs(js,{title:"App Text",children:[e.jsx(ft,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),e.jsx(ft,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),e.jsx(ft,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),e.jsxs(js,{title:"Borders & Accent",children:[e.jsx(ft,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),e.jsx(ft,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),e.jsx(ft,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),e.jsxs("div",{children:[e.jsxs(js,{title:"Chat Bubbles",children:[e.jsx(ft,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),e.jsx(ft,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),e.jsx(ft,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),e.jsx(ft,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),e.jsxs(js,{title:"Chat Layout",children:[e.jsx(ft,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),e.jsx(ft,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),e.jsx(ft,{label:"Input border",value:n.inputBorder,onChange:c=>i("inputBorder",c)}),e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[e.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[e.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)"}}),e.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),e.jsx("button",{onClick:()=>{const c=t?dn:un,p=Lt(t?"light":"dark");t?Ys(c,p):Ys(p,c),o(c),Xt(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 $d(){const[t,s]=a.useState(cr),[r,n]=a.useState(!0),[o,i]=a.useState(()=>Lt("dark"));a.useEffect(()=>{n(Jt());const p=new MutationObserver(()=>{const h=Jt();n(h);const w=cr();w==="custom"?Xt(Lt(h?"dark":"light")):_s(w,h?"dark":"light")});p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const f=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const h=Jt();n(h);const w=cr();w==="custom"?Xt(Lt(h?"dark":"light")):_s(w,h?"dark":"light")};return f.addEventListener("change",m),()=>{p.disconnect(),f.removeEventListener("change",m)}},[]),a.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?Xt(Lt(r?"dark":"light")):(Tn(),_s(t,r?"dark":"light"))},[t,r]),a.useEffect(()=>{i(Lt(r?"dark":"light"))},[r]);const c=p=>{s(p),Rd(p)},d=[...Pd,{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 e.jsxs("div",{children:[e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:d.map(p=>{const f=t===p.id,m=r?p.preview.dark:p.preview.light,h=p.id==="honey"||p.id==="ember"?"#1a1a1a":p.id==="custom"?o.userText:"#fff";return e.jsxs("button",{onClick:()=>c(p.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:[e.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[e.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:"Hello! How can I help?"}),e.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.userBubble,color:h},children:"Fix the bug please"}),e.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:"On it! ✨"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[f&&e.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-bold text-text-primary",children:p.id==="custom"?"🎨 Custom":p.name}),e.jsx("div",{className:"text-[10px] text-text-muted",children:p.description})]})]})]},p.id)})}),t==="custom"&&e.jsx(Ed,{dark:r,onColorsChange:p=>i(p)})]})}const Uo="adhdev_mobileDashboardMode_v1";function zo(){try{return localStorage.getItem(Uo)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Bd(t){try{localStorage.setItem(Uo,t)}catch{}}function Kd(){const[t,s]=a.useState(!0);return a.useEffect(()=>{s(zo()==="chat")},[]),e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Kt,{size:15})," Mobile Inbox (Chat Mode)"]}),description:t?"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:t,onChange:r=>{s(r),Bd(r?"chat":"workspace")},extra:e.jsx("span",{className:"text-[11px] text-text-muted",children:t?"Chat mode":"Workspace"})})}function Wd(t,s,r){return{...t||{},id:s,type:(t==null?void 0:t.type)||"adhdev-daemon",status:(t==null?void 0:t.status)||"online",timestamp:r.timestamp,platform:r.machine.platform,machine:{...(t==null?void 0:t.machine)||{},...r.machine}}}function Od(t,s){const{sendData:r}=St(),{injectEntries:n,getIdes:o}=pr(),i=Array.from(new Set(t.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(p=>Ot.subscribe({sendData:r},p,{type:"subscribe",topic:"machine.runtime",key:`machine:${p}`,params:{intervalMs:s==null?void 0:s.intervalMs}},f=>{const m=o().find(w=>w.id===p),h=Wd(m,p,f);n([h])}));return()=>{d.forEach(p=>p())}},[i,o,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}const Hd=4e3;function Fo(t,s){const{sendData:r}=St(),[n,o]=a.useState(null),[i,c]=a.useState(!1);return a.useEffect(()=>{if(!t){o(null),c(!1);return}if(!(s!=null&&s.enabled)||!r){c(!1);return}o(null),c(!0);let d=null;const p=Ot.subscribe({sendData:r},t,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${t}`,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 p.initialSendAccepted?d=setTimeout(()=>{c(!1)},Hd):c(!1),()=>{d&&clearTimeout(d),p()}},[t,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 Ud(t){return t.daemonId||(t.routeId.includes(":")?t.routeId.split(":")[0]||null:t.routeId||null)}function Vo(t){const{sendData:s}=St(),[r,n]=a.useState({});return a.useEffect(()=>{const o=Ud(t);if(!o||!t.sessionId||!s){n({});return}const i=Ot.subscribe({sendData:s},o,{type:"subscribe",topic:"session.modal",key:`daemon:${o}:session-modal:${t.sessionId}`,params:{targetSessionId:t.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),Qt.record({interactionId:c.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:t.sessionId,status:c.status,modalButtonCount:Array.isArray(c.modalButtons)?c.modalButtons.length:0}})});return()=>{i()}},[t.daemonId,t.routeId,t.sessionId,s]),r}const Go="adhdev_hiddenTabs";function zd(){try{const t=localStorage.getItem(Go);if(t)return new Set(JSON.parse(t))}catch{}return new Set}function cs(t){try{localStorage.setItem(Go,JSON.stringify([...t]))}catch{}}function Fd(){const[t,s]=a.useState(zd),r=a.useCallback(f=>{s(m=>{const h=new Set(m);return h.has(f)?h.delete(f):h.add(f),cs(h),h})},[]),n=a.useCallback(f=>{s(m=>{if(m.has(f))return m;const h=new Set(m);return h.add(f),cs(h),h})},[]),o=a.useCallback(f=>{s(m=>{if(!m.has(f))return m;const h=new Set(m);return h.delete(f),cs(h),h})},[]),i=a.useCallback(()=>{s(f=>{if(f.size===0)return f;const m=new Set;return cs(m),m})},[]),c=a.useCallback((f,m)=>{s(h=>{const w=new Set(h);for(const S of m)w.add(S);return cs(w),w})},[]),d=a.useCallback((f,m)=>{s(h=>{const w=new Set(h);for(const S of m)w.delete(S);return cs(w),w})},[]),p=a.useCallback(f=>t.has(f),[t]);return{hiddenTabs:t,toggleTab:r,hideTab:n,showTab:o,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:d,isHidden:p}}function Vd({visibleConversations:t,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){a.useEffect(()=>{Ql()},[]);const o=a.useMemo(()=>t.map(i=>({id:i.tabKey,name:So(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[t]);return td(o),a.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(d=>{const p=Date.now(),f={};for(const[m,h]of Object.entries(d))p-h<5e3&&(f[m]=h);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 p=d.filter(f=>f.timestamp>c).slice(-100);return p.length===d.length?d:p})},6e4);return()=>clearInterval(i)},[n]),null}function Gd(t){const s=t.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 Xs(t,s){if(t.length!==s.length)return!1;for(let r=0;r<t.length;r+=1)if(t[r]!==s[r])return!1;return!0}function qd(t,s){const r=Date.now();return t.map(n=>{const o=s[n.tabKey];return o&&r-o<5e3?{...n,messages:[],title:""}:n})}function Yd(t,s){const r=[],n=t.sessionId||t.instanceId;r.push({key:t.id,ref:s[t.id]}),n&&r.push({key:n,ref:s[n]});for(const o of t.childSessions||[]){const i=o.id||o.providerType,c=`${t.id}:${i}`;r.push({key:c,ref:s[c]}),r.push({key:o.id,ref:s[o.id]})}return r}function Xd(t,s){if(t.length!==s.length)return!1;for(let r=0;r<t.length;r+=1)if(t[r].key!==s[r].key||t[r].ref!==s[r].ref)return!1;return!0}function Jd(t){return[...t.messages].reverse().find(s=>!(s!=null&&s._localId))||t.messages[t.messages.length-1]}function Zd(t){const s=Jd(t);if(!s)return`empty:${t.messages.length}`;if(s.id)return`id:${String(s.id)}`;if(s._localId)return`local:${String(s._localId)}`;const r=String(s.role||""),n=ss(s.content).slice(0,240);return`${t.messages.length}:${r}:${n}`}function Qd({ides:t,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:o}){const i=a.useRef([]),c=a.useRef([]),d=a.useRef([]),p=a.useRef([]),f=a.useMemo(()=>{const x=Gd(t);return Xs(i.current,x)?i.current:(i.current=x,x)},[t]),m=a.useMemo(()=>Mo(t),[t]),h=a.useRef(new Map),w=a.useRef(new Map),S=a.useMemo(()=>{const x=new Map,g=[];for(const R of f){const{connectionState:K="new",machineName:D}=To(R,{machineNames:m,connectionStates:s,defaultConnectionState:"new"}),V=Yd(R,r),_=h.current.get(R.id);if(_&&_.ide===R&&_.connectionState===K&&_.machineName===D&&Xd(_.localRefs,V)){x.set(R.id,_),g.push(..._.conversations);continue}const C=In(R,r,{machineNames:m,connectionStates:s,defaultConnectionState:"new"}),T={ide:R,connectionState:K,machineName:D,localRefs:V,conversations:C};x.set(R.id,T),g.push(...C)}h.current=x;const y=new Map,j=R=>{const K=Zd(R),D=w.current.get(R.tabKey);if(D&&D.signature===K)return y.set(R.tabKey,D),D.timestamp;const V={signature:K,timestamp:Io(R)||(D==null?void 0:D.timestamp)||0};return y.set(R.tabKey,V),V.timestamp},E=[...g].sort((R,K)=>xr(R,K,j));return w.current=y,E},[f,r,s,m]),I=a.useMemo(()=>{const x=qd(S,n);return Xs(c.current,x)?c.current:(c.current=x,x)},[S,n]),u=a.useMemo(()=>{const x=new Map,g=Array.from(new Set(I.map(y=>y.routeId)));for(const y of g){const j=Dt(I,y);j&&x.set(y,j)}return x},[I]),b=a.useMemo(()=>{const x=new Map;for(const g of I)if(g.sessionId&&x.set(g.sessionId,g),g.streamSource==="native"&&g.sessionId){const y=u.get(g.routeId);y&&x.set(g.sessionId,y)}return x},[I,u]),v=a.useMemo(()=>{const x=new Map;for(const g of I)g.sessionId&&x.set(g.sessionId,g),x.set(g.routeId,u.get(g.routeId)||g),x.set(g.tabKey,g);return x},[I,u]),l=a.useCallback(x=>{if(x)return b.get(x)},[b]),N=a.useCallback(x=>{if(x)return v.get(x)},[v]),A=a.useMemo(()=>{const x=I.filter(g=>!o.has(g.tabKey));return Xs(d.current,x)?d.current:(d.current=x,x)},[I,o]),k=a.useMemo(()=>{const x=A.map(g=>g.tabKey);return Xs(p.current,x)?p.current:(p.current=x,x)},[A]);return{chatIdes:f,conversations:I,visibleConversations:A,visibleTabKeys:k,resolveConversationBySessionId:l,resolveConversationByTarget:N}}function eu({isMobile:t,urlActiveTab:s,resolveConversationBySessionId:r,setSearchParams:n}){const o=a.useMemo(()=>{var d;return t||!s?null:((d=r(s))==null?void 0:d.tabKey)??null},[t,r,s]),i=a.useMemo(()=>{var d;return!t||!s?null:((d=r(s))==null?void 0:d.tabKey)??null},[t,r,s]),c=a.useCallback(()=>{s&&n(d=>{const p=new URLSearchParams(d);return p.delete("activeTab"),p},{replace:!0})},[n,s]);return{requestedDesktopTabKey:o,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function tu({ides:t,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:o}){a.useEffect(()=>{ht.setIdes(t)},[t]),a.useEffect(()=>{ht.setResolveAction((i,c,d)=>{s(i,c,d).catch(()=>{})})},[s]),a.useEffect(()=>{const i=ht.onToast(p=>{r(m=>m.some(w=>w.message===p.message&&p.timestamp-w.timestamp<3e3)?m:[...m.slice(-4),{id:p.id,message:p.message,type:p.type,timestamp:p.timestamp,targetKey:p.targetKey,actions:p.actions}]);const f=p.duration||5e3;setTimeout(()=>r(m=>m.filter(h=>h.id!==p.id)),f)}),c=ht.onSystemMessage((p,f)=>{var S,I;const m=o(p),h=(S=f._localId)==null?void 0:S.startsWith("sys_approval_"),w=!!(m&&(m.status==="waiting_approval"||(I=m.modalButtons)!=null&&I.length||m.modalMessage));h&&w||n(u=>({...u,[p]:[...u[p]||[],f]}))}),d=ht.onClearSystemMessage((p,f)=>{n(m=>{var h;return(h=m[p])!=null&&h.length?{...m,[p]:m[p].filter(w=>{var S;return!(w.role==="system"&&((S=w._localId)!=null&&S.startsWith(f)))})}:m})});return()=>{i(),c(),d()}},[r,n]),a.useEffect(()=>{const i=jo.on("status_event",c=>{ht.handleRawEvent(c,"ws")});return()=>{i()}},[]),a.useEffect(()=>{var c;const i=d=>{var b;const p=d.data;if((p==null?void 0:p.type)!=="notification_action"||typeof p.action!="string"||!p.action.startsWith("approval_")||!(p.daemonId||p.targetSessionId||p.targetKey))return;const f=p.targetSessionId||p.targetKey||p.daemonId,m=o(f),h=(m==null?void 0:m.routeId)||p.daemonId;if(!h)return;const w=Number(p.buttonIndex),S=p.button||((b=m==null?void 0:m.modalButtons)==null?void 0:b[w])||"Approve",I=String(S).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),u=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(I);s(h,"resolve_action",{action:u?"approve":"reject",button:S,...Number.isFinite(w)&&{buttonIndex:w},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...p.targetSessionId&&{targetSessionId:p.targetSessionId}}).catch(v=>console.error("[SW Action] approval failed:",v))};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 su="adhdev_dashboardLayout_v1",ru="adhdev_dashboardDockview_v1",nu="adhdev_dashboardDockviewHiddenRestore_v1",ks={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function _n(t,s){try{const r=localStorage.getItem(t);return r?JSON.parse(r):s}catch{return s}}function qo(t){return t<768?"mobile":t<1280?"desktop-narrow":"desktop-wide"}function Yo(t){return`${su}:${t}`}function au(t){const s=Yo(t);return _n(s,null)}function ou(t,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=Yo(t);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function Xo(t){return`${ru}:${t}`}function iu(t){const s=Xo(t);return _n(s,null)}function cu(t,s){try{const r=Xo(t);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Jo(t){return`${nu}:${t}`}function lu(t){const s=Jo(t);return _n(s,{})}function du(t,s){try{const r=Jo(t);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function uu(){return{groupAssignments:[...ks.groupAssignments],focusedGroup:ks.focusedGroup,groupActiveTabIds:{...ks.groupActiveTabIds},groupTabOrders:{...ks.groupTabOrders},groupSizes:[...ks.groupSizes]}}function pu(){const[t]=a.useState(()=>qo(typeof window<"u"?window.innerWidth:1280)),[s,r]=a.useState(()=>new Map),[n,o]=a.useState(0),[i,c]=a.useState({}),[d,p]=a.useState({}),[f,m]=a.useState([]),[h,w]=a.useState(()=>typeof window<"u"&&window.innerWidth<768),[S,I]=a.useState(!1),u=a.useCallback(()=>{if(S)return;const b=au(t)??uu();r(new Map(b.groupAssignments)),o(b.focusedGroup),c(b.groupActiveTabIds),p(b.groupTabOrders),m(b.groupSizes),I(!0)},[S,t]);return a.useEffect(()=>{S&&ou(t,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:d,groupSizes:f})},[S,t,s,n,i,d,f]),a.useEffect(()=>{const b=window.matchMedia("(max-width: 767px)"),v=l=>w(l.matches);return b.addEventListener("change",v),()=>b.removeEventListener("change",v)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:o,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:d,setGroupTabOrders:p,groupSizes:f,setGroupSizes:m,isMobile:h,hasHydratedStoredLayout:S,hydrateStoredLayout:u}}function mu(t,s){if(!Array.isArray(t)||t.length!==1||!s)return!1;const r=t[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 fu({urlActiveTab:t,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:o,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:d,setSearchParams:p,historyModalOpen:f,activeConv:m,isRefreshingHistory:h,ides:w,handleRefreshHistory:S}){const I=a.useRef(!1),u=a.useRef(!1),b=a.useRef(null),v=a.useRef(!1);a.useEffect(()=>{if(!t||I.current||s.length===0)return;if(!o){i();return}const l=r(t);if(!l)return;const N=n.get(l.tabKey)??0;c(A=>({...A,[N]:l.tabKey})),d(N),I.current=!0,u.current=!0,b.current!=null&&(window.clearTimeout(b.current),b.current=null),p(A=>{const k=new URLSearchParams(A);return k.delete("activeTab"),k},{replace:!0})},[t,s,r,n,o,i,c,d,p]),a.useEffect(()=>{if(!(u.current||o)&&s.length!==0){if(!t){i(),u.current=!0;return}if(I.current){u.current=!0;return}if(b.current==null)return b.current=window.setTimeout(()=>{b.current=null,!(u.current||o)&&(i(),u.current=!0)},1500),()=>{b.current!=null&&(window.clearTimeout(b.current),b.current=null)}}},[t,s.length,o,i]),a.useEffect(()=>{if(!f){v.current=!1;return}if(!m||v.current||h)return;const l=w.find(N=>N.id===m.routeId);l&&(!l.chats||l.chats.length===0||mu(l.chats,m))&&(v.current=!0,S())},[f,m,h,w,S]),a.useEffect(()=>{if(!m)return;let l=null,N=0,A=-1,k=0;const x=()=>{l=null;const g=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(j=>j.offsetParent!==null);if(g.length===0){N<18&&(N+=1,l=requestAnimationFrame(x));return}let y=0;for(const j of g)j.scrollTop=j.scrollHeight,y+=j.scrollHeight;y===A?k+=1:(k=0,A=y),N+=1,!(k>=2||N>=18)&&(l=requestAnimationFrame(x))};return l=requestAnimationFrame(x),()=>{l!=null&&cancelAnimationFrame(l)}},[m==null?void 0:m.tabKey])}function xu({isMobile:t,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:o,conversations:i,ides:c,resolveConversationByTarget:d}){const[p,f]=a.useState(null),[m,h]=a.useState(null),w=a.useMemo(()=>{if(t||!n)return null;const v=d(n);return v&&!Xe(v)&&!Ve(v)?v:null},[t,n,d]),S=a.useMemo(()=>{const v=p==null?void 0:p.routeId;if(!v)return null;const l=p!=null&&p.tabKey?i.find(N=>N.tabKey===p.tabKey):o?i.find(N=>N.tabKey===o):null;return(l==null?void 0:l.routeId)===v?l:Dt(i,v)},[i,p,o]),I=a.useMemo(()=>{if(S)return c.find(v=>v.id===S.routeId)},[c,S]);a.useEffect(()=>{w&&(f({routeId:w.routeId,tabKey:aa(w)}),h(w),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,w]);const u=a.useCallback(v=>{v&&(f({routeId:v.routeId,tabKey:aa(v)}),h(v))},[]),b=a.useCallback(()=>{f(null),h(null)},[]);return{remoteDialogConv:S,remoteDialogIdeEntry:I,remoteDialogActiveConv:m,setRemoteDialogActiveConv:h,openRemoteDialog:u,closeRemoteDialog:b}}function fs(t){if(!t)return{};const s=t.sessionId?{targetSessionId:t.sessionId}:{};return t.sessionId?s:Xe(t)||Ve(t)?{agentType:jt(t)}:t.streamSource==="agent-stream"?{agentType:jt(t)}:s}function Bs(t){return t?mr(t):""}function Ns(t,s){t(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function Or(t,s){if(!Array.isArray(t)||t.length!==1||!s)return!1;const r=t[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 ka({sendDaemonCommand:t,activeConv:s,chats:r,updateRouteChats:n,setToasts:o,setLocalUserMessages:i,setClearedTabs:c}){const[d,p]=a.useState(!1),[f,m]=a.useState(!1),h=a.useCallback(async u=>{try{await t("standalone","launch_ide",{ideType:u,enableCdp:!0})}catch(b){console.error("Launch failed",b)}},[t]),w=a.useCallback(async(u,b)=>{try{const v=u||(s==null?void 0:s.daemonId)||"",l=await t(v,"switch_chat",{id:b,sessionId:b,...fs(s)}),N=l==null?void 0:l.result;if((l==null?void 0:l.success)===!0||N==="switched"||N==="switched-by-title")return;N===!1||N==="not_found"?Ns(o,"⚠️ Session tab not found — try refreshing history"):typeof N=="string"&&N.startsWith("error:")?Ns(o,`⚠️ Switch error: ${N}`):Ns(o,"⚠️ Session switch failed")}catch(v){console.error("Switch failed",v),Ns(o,`❌ Switch failed: ${v.message||"connection error"}`)}},[s,t,o]),S=a.useCallback(async()=>{if(!(!s||d)){p(!0);try{const u=Bs(s);await t(u,"new_chat",{...fs(s)}),c(b=>({...b,[s.tabKey]:Date.now()})),i(b=>({...b,[s.tabKey]:[]}))}catch(u){console.error("New chat failed",u)}finally{p(!1)}}},[s,d,t,c,i]),I=a.useCallback(async()=>{var u,b;if(!(!s||f)){m(!0);try{const v=Bs(s),l=async()=>t(v,"list_chats",{forceExpand:!0,...fs(s)});let N=await l(),A=(N==null?void 0:N.chats)||((u=N==null?void 0:N.result)==null?void 0:u.chats);Or(A,s)&&(await new Promise(k=>setTimeout(k,450)),N=await l(),A=(N==null?void 0:N.chats)||((b=N==null?void 0:N.result)==null?void 0:b.chats)),N!=null&&N.success&&Array.isArray(A)&&(n(s.routeId,A),Or(A,s)&&!Or(r,s)&&Ns(o,"⚠️ History dialog did not fully open — try once more"))}catch(v){console.error("Refresh history failed",v)}finally{m(!1)}}},[s,r,f,t,n,o]);return{isCreatingChat:d,isRefreshingHistory:f,handleLaunchIde:h,handleSwitchSession:w,handleNewChat:S,handleRefreshHistory:I}}function hu(t,s){if(t.size!==s.size)return!1;for(const[r,n]of t)if(s.get(r)!==n)return!1;return!0}function bu(t,s){return t.length!==s.length?!1:t.every((r,n)=>r===s[n])}function Na(t,s){const r=Object.keys(t),n=Object.keys(s);return r.length!==n.length?!1:r.every(o=>s[Number(o)]===t[Number(o)])}function Js(t,s){const r=new Set(s),n=s.length>0?[0]:[];for(const[c,d]of t)!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 t){if(!r.has(c)||d<=0)continue;const p=o[d];typeof p=="number"&&p>0&&i.set(c,p)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:o,usedGroups:n}}function Sa(t,s){const r={};for(const[n,o]of Object.entries(t)){const i=s[Number(n)];typeof i=="number"&&(r[i]=o)}return r}function gu(t,s,r){if(s.length===0)return 0;if(typeof r[t]=="number")return r[t];const n=[...s].reverse().find(o=>o<t)??s[0];return r[n]??0}function yu(t,s,r){if(s.length<=1)return[];const n=s.map(c=>t[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 Ca(t,s){const r={};for(const[n,o]of Object.entries(t)){const i=Number(n);r[i>=s?i+1:i]=o}return r}function Ia(t){return Array(t).fill(100/t)}function vu({groupAssignments:t,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:o,groupSizes:i,setGroupSizes:c,isMobile:d,visibleConversations:p,visibleTabKeys:f}){const m=a.useRef(null),h=a.useMemo(()=>Js(t,f),[t,f]),w=h.assignments,S=a.useMemo(()=>d?1:h.groupCount,[h.groupCount,d]),I=S>1,u=a.useCallback((k,x)=>{s(g=>{const y=new Map(Js(g,f).assignments);return x===0?y.delete(k):y.set(k,x),y}),n(g=>({...g,[x]:k})),r(x)},[s,f,n,r]),b=a.useCallback(k=>{s(x=>{const g=Js(x,f).assignments,y=new Map;for(const[j,E]of g)E!==k&&(E>k?y.set(j,E-1):y.set(j,E));return y}),c(x=>{if(x.length<=1)return[];const g=[...x];g.splice(k,1);const y=g.reduce((j,E)=>j+E,0);return y>0?g.map(j=>j/y*100):[]}),r(0)},[s,f,c,r]),v=a.useCallback((k,x)=>{x.preventDefault();const g=m.current;if(!g)return;const y=x.clientX,j=g.offsetWidth,E=i.length===S?[...i]:Ia(S),R=D=>{const _=(D.clientX-y)/j*100,C=[...E];C[k]=Math.max(15,E[k]+_),C[k+1]=Math.max(15,E[k+1]-_),c(C)},K=()=>{document.removeEventListener("mousemove",R),document.removeEventListener("mouseup",K),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",R),document.addEventListener("mouseup",K)},[i,S,c]),l=a.useCallback((k,x,g)=>{if(S>=4)return;const y=g==="left"?x:x+1;s(j=>{const E=Js(j,f).assignments,R=new Map;for(const K of p){const D=E.get(K.tabKey)??0,V=D>=y?D+1:D;V>0&&R.set(K.tabKey,V)}return y>0&&R.set(k,y),R}),c(j=>{const E=j.length===S?[...j]:Ia(S),R=E[x]??100/S,K=Math.max(15,R/2),D=Math.max(15,R/2),V=[...E];V[x]=K,V.splice(y,0,D);const _=V.reduce((C,T)=>C+T,0);return V.map(C=>C/_*100)}),n(j=>{const E=Ca(j,y);return E[y]=k,E}),o(j=>{const E=Ca(j,y);return E[y]=[k],E}),r(y)},[S,s,f,p,c,n,o,r]);a.useEffect(()=>{hu(t,w)||s(w)},[t,w,s]),a.useEffect(()=>{const{mapping:k,usedGroups:x}=h;n(g=>{const y=Sa(g,k);return Na(g,y)?g:y}),o(g=>{const y=Sa(g,k);return Na(g,y)?g:y}),r(g=>{const y=d?0:gu(g,x,k);return g===y?g:y}),c(g=>{const y=d?[]:yu(g,x,h.groupCount);return bu(g,y)?g:y})},[h,d,n,o,r,c]);const N=a.useMemo(()=>{const k=Array.from({length:S},()=>[]);for(const x of p){const g=w.get(x.tabKey)??0,y=Math.min(g,S-1);k[y].push(x)}return k},[p,w,S]),A=a.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:m,normalizedGroupAssignments:w,numGroups:S,isSplitMode:I,groupedConvs:N,moveTabToGroup:u,closeGroup:b,handleResizeStart:v,splitTabRelative:l,clearAllSplits:A}}function wu({ides:t,sendDaemonCommand:s}){const r="0.8.51",n=a.useMemo(()=>t.filter(m=>m.type!=="adhdev-daemon"?!1:Ko(m,r)).sort((m,h)=>Number(Ts(h,r))-Number(Ts(m,r))),[r,t]),o=a.useMemo(()=>n.some(m=>Ts(m,r)),[r,n]),[i,c]=a.useState(!1),[d,p]=a.useState({}),f=a.useCallback(async m=>{var h,w;p(S=>({...S,[m]:"upgrading"}));try{const S=await s(m,"daemon_upgrade",{});(h=S==null?void 0:S.result)!=null&&h.upgraded||(w=S==null?void 0:S.result)!=null&&w.success?p(I=>({...I,[m]:"done"})):p(I=>({...I,[m]:"error"}))}catch{p(S=>({...S,[m]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:o,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:f}}function Aa(t){return!t||typeof t!="object"?t:t.result&&typeof t.result=="object"?t.result:t}function Pn(t){return t instanceof Error?t.message:String(t||"")}function Ma(t){const s=Pn(t).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Ta(t,s){const r=Pn(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${t}** failed — button not found`:`⚠️ **${t}** failed — ${r}`:`⚠️ **${t}** unavailable`}function Sr({sendDaemonCommand:t,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:o}){const[i,c]=a.useState(!1),[d,p]=a.useState(!1),f=a.useRef(!1),m=a.useRef(null),h=a.useCallback(async u=>{if(!s)return;const b=u.trim();if(!b||f.current)return;const v=s.tabKey,l=Date.now(),N=m.current;if(N&&N.tabKey===v&&N.message===b&&l-N.timestamp<2e3)return;f.current=!0,p(!0),m.current={tabKey:v,message:b,timestamp:l};const A=`${l}-${Math.random().toString(36).slice(2,8)}`,k={role:"user",content:b,timestamp:l,_localId:A},x=!(Xe(s)||Ve(s));x&&r(g=>({...g,[v]:[...g[v]||[],k]}));try{const g=Bs(s);if(!g)return;const y=await t(g,"send_chat",{message:b,...fs(s)}),j=Aa(y);if(x&&(j!=null&&j.deduplicated||(j==null?void 0:j.sent)===!1)){r(E=>({...E,[v]:(E[v]||[]).filter(R=>R._localId!==A)}));return}if((j==null?void 0:j.success)===!1)throw new Error((j==null?void 0:j.error)||"Send failed");setTimeout(()=>{const E=Date.now()-6e4;r(R=>{const K=R[v];if(!K)return R;const D=K.filter(V=>V.timestamp>E);return D.length===K.length?R:{...R,[v]:D}})},6e4)}catch(g){const y=Pn(g);y.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",y):console.error("Send failed",g),x&&r(j=>({...j,[v]:(j[v]||[]).filter(E=>E._localId!==A)}))}finally{f.current=!1,p(!1)}},[s,t,r]),w=a.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await t(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(u){console.error("Relaunch failed",u)}},[s,t]),S=a.useCallback(async u=>{if(s)try{const v=(s.modalButtons||[]).indexOf(u),l=u.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),N=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(l),A=Bs(s);if(!A)return;const k=await t(A,"resolve_action",{button:u,action:N?"approve":"reject",...v>=0&&{buttonIndex:v},...fs(s)}),x=Aa(k);x.success||n(g=>[...g,{routeId:s.tabKey,text:Ta(u,x==null?void 0:x.error),timestamp:Date.now()}])}catch(b){Ma(b)||console.error("[ModalButton] Error:",b),n(v=>[...v,{routeId:s.tabKey,text:Ma(b)?Ta(u,b):`❌ **${u}** error`,timestamp:Date.now()}])}},[s,t,n]),I=a.useCallback(async()=>{if(!(!s||i)){c(!0);try{await t(s.routeId,"focus_session",{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(u){console.error("Focus agent failed",u)}finally{c(!1)}}},[s,i,t]);return{isSendingChat:d,isFocusingAgent:i,handleSendChat:h,handleRelaunch:w,handleModalButton:S,handleFocusAgent:I}}const Ln=a.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:o,terminalRef:i,handleModalButton:c,handleRelaunch:d,handleSendChat:p,isSendingChat:f,handleFocusAgent:m,isFocusingAgent:h,actionLogs:w,userName:S,scrollToBottomRequestNonce:I,isInputActive:u=!0}){const b=Vo(s),v=b.status||b.modalMessage||b.modalButtons?{...s,...b.status?{status:b.status}:{},...b.modalMessage!==void 0?{modalMessage:b.modalMessage}:{},...b.modalButtons!==void 0?{modalButtons:b.modalButtons}:{}}:s;return e.jsxs(e.Fragment,{children:[e.jsx(po,{activeConv:v,onModalButton:c}),v.transport!=="pty"&&v.transport!=="acp"&&v.cdpConnected===!1?e.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:e.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:[e.jsx("span",{className:"text-sm",children:e.jsx(ts,{size:14})}),e.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),e.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,v.transport==="pty"?e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{display:n?"flex":"none",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:e.jsx(Tl,{activeConv:v,clearToken:r,terminalRef:i,handleSendChat:p,isSendingChat:f,isVisible:n})}),!n&&e.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:e.jsx(nn,{activeConv:v,ideEntry:o,handleSendChat:p,isSendingChat:f,handleFocusAgent:m,isFocusingAgent:h,actionLogs:w,userName:S,scrollToBottomRequestNonce:I,isInputActive:u})})]}):e.jsx(nn,{activeConv:v,ideEntry:o,handleSendChat:p,isSendingChat:f,handleFocusAgent:m,isFocusingAgent:h,actionLogs:w,userName:S,scrollToBottomRequestNonce:I,isInputActive:u})]})},(t,s)=>t.activeConv===s.activeConv&&t.isCliTerminal===s.isCliTerminal&&t.ideEntry===s.ideEntry&&t.terminalRef===s.terminalRef&&t.handleModalButton===s.handleModalButton&&t.handleRelaunch===s.handleRelaunch&&t.handleSendChat===s.handleSendChat&&t.isSendingChat===s.isSendingChat&&t.handleFocusAgent===s.handleFocusAgent&&t.isFocusingAgent===s.isFocusingAgent&&t.actionLogs===s.actionLogs&&t.userName===s.userName&&t.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&t.isInputActive===s.isInputActive);function ju({selectedConversation:t,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:o,userName:i,isSendingChat:c,isFocusingAgent:d,onBack:p,onOpenNativeConversation:f,onOpenMachine:m,onOpenHistory:h,onOpenRemote:w,onHideConversation:S,onStopCli:I,cliViewMode:u,onSetCliViewMode:b,handleSendChat:v,handleFocusAgent:l,handleModalButton:N,handleRelaunch:A}){const k=a.useRef(null),x=Xe(t)&&!s,g=x&&u==="terminal",y=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`flex items-center justify-between gap-3 ${y} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[e.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[e.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:e.jsx(xn,{size:18})}),e.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[e.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:Qe(t)}),e.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:e.jsx(bo,{conversation:t,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>f(t),onOpenMachine:()=>m(t)})})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[x&&u&&e.jsx(Sn,{mode:u,onChange:b,compact:!0}),x&&I&&e.jsx("button",{onClick:()=>{I(t)},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:e.jsx(vt,{size:14})}),e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>h(t),type:"button",children:e.jsx(bn,{size:14})}),!s&&!x&&e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>w(t),type:"button",children:e.jsx(Nt,{size:14})}),S&&e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(t),type:"button",title:"Close chat",children:e.jsx(vt,{size:14})})]})]}),e.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:e.jsx(Ln,{activeConv:t,clearToken:0,isCliTerminal:g,ideEntry:n,terminalRef:k,handleModalButton:N,handleRelaunch:A,handleSendChat:v,isSendingChat:c,handleFocusAgent:l,isFocusingAgent:d,actionLogs:o,userName:i})})]})}const Hr={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 ku(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Zo(){const[t,s]=a.useState("unix"),[r,n]=a.useState("powershell"),[o,i]=a.useState(!1),c=t==="unix"?"unix":r;a.useEffect(()=>{s(ku())},[]);const d=a.useCallback(()=>{navigator.clipboard.writeText(Hr[c].cmd).catch(()=>{}),i(!0),setTimeout(()=>i(!1),2e3)},[c]);return e.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:[e.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[e.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${t==="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"}),e.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${t==="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"})]}),t==="windows"&&e.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[e.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"}),e.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"})]}),e.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:d,title:"Click to copy",children:[e.jsx("span",{className:"text-text-muted select-none",children:Hr[c].prompt}),e.jsx("span",{className:"flex-1 break-all",children:Hr[c].cmd}),e.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:o?"✓":"📋"})]}),e.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",e.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function Qo({section:t,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:Nt},{key:"chats",label:"Chats",icon:Kt}];return e.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:e.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=t===n;return e.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:[e.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:e.jsx(i,{size:15})}),e.jsx("span",{children:o})]},n)})})})}function Zs({title:t,className:s=""}){return e.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${s}`,children:e.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:t})})}function ls({children:t,className:s=""}){return e.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:t})}function Ss({icon:t,title:s,subtitle:r,children:n}){return e.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:[e.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:t}),e.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:s}),e.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function Qs({item:t,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:p,isConnecting:f}=ys(t.conversation),m=Qe(t.conversation),h=ns(t.conversation),w=No(t.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",I=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",b=c?"text-text-muted":"text-text-secondary",v=c?"text-text-secondary opacity-80":"text-text-muted",l=c?"text-text-muted opacity-80":"text-text-muted",N="text-[color:var(--status-warning)]";return e.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(t.conversation),type:"button",children:[o||i?e.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,e.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${I}`,style:o?{color:"var(--accent-on-primary)"}:void 0,children:r(m)}),e.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${u}`,children:m}),!i&&e.jsx("span",{className:`text-[11px] font-medium shrink-0 ${l}`,children:uo(t.timestamp)})]}),e.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${b}`,children:[h,p?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1 opacity-50",children:"·"}),e.jsx("span",{className:`${N} animate-pulse`,children:"Reconnecting…"})]}):f?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1 opacity-50",children:"·"}),e.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):w==="Action needed"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1 opacity-50",children:"·"}),e.jsx("span",{className:N,children:"Action needed"})]})]}),e.jsx("div",{className:`mt-0.5 truncate text-[13px] ${v}`,children:t.preview})]}),o&&!d&&e.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),d&&e.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&&e.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"})]},t.conversation.tabKey)}function _a({size:t=32,label:s}){return e.jsxs("div",{className:"flex flex-col items-center gap-2.5",children:[e.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:t,height:t}}),s&&e.jsx("div",{className:"text-xs font-semibold text-accent-primary-light tracking-tight",children:s})]})}function Nu({section:t,attentionItems:s,unreadItems:r,workingItems:n,completedItems:o,hiddenConversations:i,machineCards:c,getAvatarText:d,onOpenConversation:p,onShowConversation:f,onShowAllHidden:m,onOpenNewSession:h,onOpenMachine:w,onOpenSettings:S,onSectionChange:I,wsStatus:u="connected",isStandalone:b=!1}){const v=u==="disconnected"||u==="reconnecting"||u==="offline"||u==="auth_failed",l=c.length>0,N=s.length>0||r.length>0||n.length>0||o.length>0,A=t==="machines"?"Machines":"Chats",k=b?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",x=b?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]";return e.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[e.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${k}`,children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:A}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[t==="chats"&&(s.length>0||r.length>0)&&e.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:[e.jsx(jr,{size:13}),e.jsx("span",{children:s.length+r.length})]}),e.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:e.jsx(vr,{size:18})})]})]})}),e.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] ${x}`,children:[t==="machines"&&e.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:v?e.jsx(Ss,{icon:e.jsx(_a,{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?e.jsx(Ss,{icon:e.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:b?"Waiting for your daemon":"Connect your first machine",subtitle:b?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install the ADHDev daemon on your machine, then it will show up here.",children:!b&&e.jsx("div",{className:"w-full max-w-[360px] mt-4",children:e.jsx(Zo,{})})}):e.jsx(ls,{children:c.map((g,y)=>e.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${y>0?"border-t border-border-subtle/70":""}`,onClick:()=>w(g.id),type:"button",children:[e.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(g.label)}),e.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:g.label}),e.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:g.unread>0?e.jsxs("span",{className:"text-accent-primary",children:[g.unread," new"]}):g.total>0?`${g.total} chats`:"Idle"})]}),e.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:g.subtitle}),g.total>0?e.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[g.total," chat",g.total!==1?"s":"",g.unread>0?` · ${g.unread} unread`:""]}):e.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},g.id))})}),t==="chats"&&s.length>0&&e.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[e.jsx(Zs,{title:"Needs attention",className:"mb-0"}),e.jsx(ls,{children:s.map((g,y)=>e.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:e.jsx(Qs,{item:g,type:"needs_attention",getAvatarText:d,onOpenConversation:p})},g.conversation.tabKey))})]}),t==="chats"&&r.length>0&&e.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[e.jsx(Zs,{title:"Task complete",className:"mb-0 mt-2"}),e.jsx(ls,{children:r.map((g,y)=>e.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:e.jsx(Qs,{item:g,type:"task_complete",getAvatarText:d,onOpenConversation:p})},g.conversation.tabKey))})]}),t==="chats"&&n.length>0&&e.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[e.jsx(Zs,{title:"Working now",className:"mb-0 mt-2"}),e.jsx(ls,{children:n.map((g,y)=>e.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:e.jsx(Qs,{item:g,type:"working",getAvatarText:d,onOpenConversation:p})},g.conversation.tabKey))})]}),t==="chats"&&e.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[o.length>0&&e.jsx(Zs,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),o.length>0?e.jsx(ls,{children:o.map((g,y)=>e.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:e.jsx(Qs,{item:g,type:"earlier",getAvatarText:d,onOpenConversation:p})},g.conversation.tabKey))}):N?e.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):v?e.jsx(Ss,{icon:e.jsx(_a,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):l?e.jsx(Ss,{icon:e.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:e.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."}):e.jsx(Ss,{icon:e.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."})]}),t==="chats"&&i.length>0&&e.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[e.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:[e.jsx("span",{children:"Hidden"}),e.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:m,children:"Restore all"})]}),e.jsx(ls,{className:"bg-bg-secondary/25",children:i.map((g,y)=>e.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 ${y>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(g),type:"button",children:[e.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(Qe(g))}),e.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:Qe(g)}),e.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),e.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:ns(g)}),e.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},g.tabKey))})]})]}),t==="chats"&&h&&e.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:h,"aria-label":"Start new session",children:e.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),e.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),e.jsx(Qo,{section:t,onSectionChange:I})]})}function Su(t){const s=t.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 Cr(t,s=[]){if(t==="win32"){for(const r of s){if(typeof r!="string")continue;const n=Su(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 Cu(t){const s=t.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 Ir(t,s,r){const n=await t(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=(p,f)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${f}`:p==="/"||p==="\\"?`${i}${f}`:`${p.replace(/[\\/]+$/,"")}${i}${f}`,d=Array.isArray(n==null?void 0:n.files)?n.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:c(o,p.name)})).sort((p,f)=>p.name.localeCompare(f.name)):[];return{path:o,directories:d}}function Ar({title:t,description:s,currentPath:r,directories:n,busy:o=!1,error:i="",confirmLabel:c="Use this folder",onClose:d,onNavigate:p,onConfirm:f}){const[m,h]=a.useState(r);a.useEffect(()=>{h(r)},[r]);const w=Cu(r),S=m.trim();return e.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:e.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:[e.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:t}),e.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),e.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:e.jsx(vt,{size:16})})]}),e.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[e.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:()=>{!w||o||p(w)},disabled:!w||o,children:[e.jsx(xn,{size:15}),"Parent"]}),e.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"text",value:m,onChange:I=>h(I.target.value),onKeyDown:I=>{I.key!=="Enter"||!S||o||(I.preventDefault(),p(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"}),e.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||p(S)},disabled:!S||o,children:"Go"})]})]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:o?e.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):i?e.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):n.length===0?e.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):e.jsx("div",{className:"p-3",children:n.map(I=>e.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:()=>p(I.path),children:[e.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:e.jsx(xs,{size:17})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:I.name}),e.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:I.path})]})]},I.path))})}),e.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-4 border-t border-border-subtle bg-bg-secondary",children:[e.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:d,children:"Cancel"}),e.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 Rn({title:t,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:o,onWorkspaceChange:i,confirmLabel:c="Launch",busy:d=!1,showArgsInput:p,argsValue:f,onArgsChange:m,showModelInput:h,modelValue:w,onModelChange:S,historyProviderNode:I,onConfirm:u,onCancel:b}){const v=n==null?void 0:n.find(l=>l.key===o);return e.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:e.jsxs("div",{className:"w-full max-w-lg rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:t}),e.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),e.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:b,"aria-label":"Close launch confirmation",children:e.jsx(vt,{size:16})})]}),e.jsxs("div",{className:"px-5 py-4 flex flex-col gap-3",children:[n&&n.length>0&&i&&e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),e.jsx("select",{value:o||"",onChange:l=>i(l.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:n.map(l=>e.jsx("option",{value:l.key,children:l.label},l.key))}),(v==null?void 0:v.description)&&e.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:v.description})]}),I,r.map(l=>e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:l.label}),e.jsx("div",{className:"text-sm text-text-primary break-all",children:l.value})]},`${l.label}:${l.value}`)),h&&S&&e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),e.jsx("input",{type:"text",value:w||"",onChange:l=>S(l.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),p&&m&&e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),e.jsx("input",{type:"text",value:f||"",onChange:l=>m(l.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-4 border-t border-border-subtle bg-bg-secondary",children:[e.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:b,disabled:d,children:"Cancel"}),e.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:u,disabled:d,children:[e.jsx(gn,{size:14}),d?"Launching…":c]})]})]})})}function Pa(t,s){return s||t.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||t}function Zt(t){const{machine:s,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:o=!0}=t,i=[];o&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const p of s.workspaces||[])i.push({key:`saved:${p.id}`,label:`${p.id===s.defaultWorkspaceId?"⭐ ":""}${Pa(p.path,p.label)}`,description:p.path,workspaceId:p.id,workspacePath:p.path});const c=(r==null?void 0:r.trim())||"",d=c?(s.workspaces||[]).find(p=>p.path===c):null;if(c&&!d&&i.push({key:`custom:${c}`,label:Pa(c),description:c,workspaceId:null,workspacePath:c}),n){const p=`saved:${n}`;if(i.some(f=>f.key===p))return{options:i,selectedKey:p}}return d?{options:i,selectedKey:`saved:${d.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function Ur(t,s,r){return t?"ide":s>0?"cli":r>0?"acp":null}function Iu({selectedMachineEntry:t,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:o,onListSavedSessions:i}){var ye,F,me,Ce;const c=Hs(),[d,p]=a.useState(!1),f=(((ye=t.detectedIdes)==null?void 0:ye.length)||0)>0,m=a.useMemo(()=>(t.workspaces||[]).map(xe=>({id:xe.id,path:xe.path,label:xe.label})),[t]),h=t.defaultWorkspaceId||null,[w,S]=a.useState(h||((F=m[0])==null?void 0:F.id)||""),[I,u]=a.useState(""),[b,v]=a.useState(""),[l,N]=a.useState([]),[A,k]=a.useState(!1),[x,g]=a.useState(""),[y,j]=a.useState(!1),[E,R]=a.useState(Ur(f,s.length,r.length)),K=a.useRef(null),[D,V]=a.useState(null),_=a.useRef("__home__"),[C,T]=a.useState("__home__"),[z,L]=a.useState(""),[$,H]=a.useState(""),[se,Y]=a.useState(""),[ie,je]=a.useState([]),[G,oe]=a.useState(!1),[W,be]=a.useState(!1),X=a.useRef(null);a.useEffect(()=>{(!t.workspaces||!t.availableProviders||!t.detectedIdes||!t.recentLaunches)&&c(t.id,{minFreshMs:3e4}).catch(()=>{})},[c,t]);const ue=w==="__custom__"?I.trim():((me=m.find(xe=>xe.id===w))==null?void 0:me.path)||"",te=w==="__custom__"&&!!ue&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),ae=w!=="__custom__"&&((Ce=m.find(xe=>xe.id===w))==null?void 0:Ce.path)||"",fe=a.useCallback(async xe=>{k(!0),g("");try{const Le=await o(xe);v(Le.path),u(Le.path),N(Le.directories)}catch(Le){g(Le instanceof Error?Le.message:"Could not load folder")}finally{k(!1)}},[o]),le=a.useCallback(()=>{var Le,Be;S("__custom__"),j(!0);const xe=Cr(t.platform,[I.trim(),ae,(Le=m.find(Fe=>Fe.id===h))==null?void 0:Le.path,(Be=m[0])==null?void 0:Be.path]);fe(xe)},[I,h,fe,ae,t.platform,m]),he=a.useCallback(xe=>{if(xe!=null&&xe.workspaceId){S(xe.workspaceId),u("");return}if(xe!=null&&xe.workspacePath){S("__custom__"),u(xe.workspacePath);return}S(""),u("")},[]),J=a.useCallback(xe=>{if(S(xe),xe==="__custom__"){le();return}u("")},[le]),pe=a.useCallback(xe=>{S("__custom__"),u(xe)},[]),ne=a.useCallback((xe,Le)=>{K.current=Le,_.current=xe.selectedWorkspaceKey||"__home__",T(xe.selectedWorkspaceKey||"__home__"),L(xe.initialArgs||""),H(xe.initialModel||""),Y(""),je([]),V(xe),xe.providerType&&i&&(oe(!0),i(xe.providerType).then(Be=>je(Be||[])).catch(Be=>console.warn("Failed to load saved sessions",Be)).finally(()=>oe(!1)))},[i]),we=a.useCallback(()=>{K.current&&(be(!0),K.current().finally(()=>{K.current=null,be(!1),V(null)}))},[]),ge=a.useCallback(()=>{K.current=null,V(null)},[]),P=a.useCallback(xe=>{_.current=xe,T(xe)},[]);return a.useEffect(()=>{var xe;X.current!==t.id&&(X.current=t.id,S(h||((xe=m[0])==null?void 0:xe.id)||"__custom__"),u(""),v(""),N([]),g(""),j(!1),R(Ur(f,s.length,r.length)))},[r.length,s.length,h,f,t.id,m]),a.useEffect(()=>{var xe;w!=="__custom__"&&(w&&m.some(Le=>Le.id===w)||S(h||((xe=m[0])==null?void 0:xe.id)||"__custom__"))},[h,w,m]),a.useEffect(()=>{E==="ide"&&f||E==="cli"&&s.length>0||E==="acp"&&r.length>0||R(Ur(f,s.length,r.length))},[E,r.length,s.length,f]),{showAllRecent:d,setShowAllRecent:p,hasIdeOptions:f,workspaceRows:m,defaultWorkspaceId:h,workspaceChoice:w,customWorkspacePath:I,browseCurrentPath:b,browseDirectories:l,browseBusy:A,browseError:x,browseDialogOpen:y,activeLauncherKind:E,launchConfirm:D,launchConfirmWorkspaceKeyRef:_,launchConfirmWorkspaceKey:C,launchConfirmArgs:z,launchConfirmModel:$,launchConfirmResumeId:se,launchConfirmSavedSessions:ie,launchConfirmSessionsLoading:G,launchConfirmBusy:W,resolvedWorkspacePath:ue,canCreateMissingWorkspace:te,openBrowseDialog:le,loadBrowsePath:fe,handleWorkspaceChoiceChange:J,chooseCustomWorkspacePath:pe,setCustomWorkspacePath:u,setBrowseDialogOpen:j,setActiveLauncherKind:R,openLaunchConfirm:ne,handleConfirmLaunch:we,closeLaunchConfirm:ge,setWorkspaceSelectionFromOption:he,setLaunchConfirmWorkspaceKeyAndSync:P,setLaunchConfirmArgs:L,setLaunchConfirmModel:H,setLaunchConfirmResumeId:Y}}function Au({selectedMachineEntry:t,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:o,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:d,isStandalone:p,section:f,showBottomNav:m,onBack:h,onSectionChange:w,onOpenConversation:S,onOpenRecent:I,onOpenMachineDetails:u,onMachineUpgrade:b,onLaunchDetectedIde:v,onAddWorkspace:l,onBrowseDirectory:N,onLaunchWorkspaceProvider:A,onListSavedSessions:k}){const x=C=>C==="ide"?"IDE":C==="cli"?"CLI":"ACP",g=r.slice(0,4),y=s.slice(0,3),j=Iu({selectedMachineEntry:t,cliProviders:n,acpProviders:o,machineAction:d,onBrowseDirectory:N,onListSavedSessions:k}),E=a.useMemo(()=>g.map(C=>({key:`recent-launch:${C.id}`,primary:C.label,secondary:`${x(C.kind)}${C.subtitle?` · ${C.subtitle}`:""}`,onClick:()=>{const{options:T,selectedKey:z}=Zt({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspacePath:C.workspace});j.openLaunchConfirm({title:`Launch ${C.label}?`,description:"Recent launches require one more confirmation before they run.",confirmLabel:"Launch",workspaceOptions:T,selectedWorkspaceKey:z,details:[{label:"Mode",value:x(C.kind)},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]},async()=>{const L=T.find($=>$.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption(L),await I({...C,workspace:(L==null?void 0:L.workspacePath)??null})})}})),[j,I,g]),R=a.useMemo(()=>y.map(C=>({key:`recent-chat:${C.conversation.tabKey}`,primary:Qe(C.conversation),secondary:Cl(C.conversation,{timestampLabel:C.timestamp?uo(C.timestamp):null}),unread:C.unread,onClick:()=>S(C.conversation)})),[S,y]),K=j.showAllRecent?E:E.slice(0,4),D=E.length>0,V=R.length>0,_=p?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:`flex items-center justify-between gap-3 ${_} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:e.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[e.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:h,type:"button","aria-label":"Back",children:e.jsx(xn,{size:18})}),e.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[e.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:kt(t,{fallbackId:t.id})}),e.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[t.platform||"machine",t.version?` · v${t.version}`:""]})]})]})}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[V&&e.jsxs("section",{className:"flex flex-col gap-0",children:[e.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),e.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:R.map(C=>e.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:[e.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))})]}),D&&e.jsxs("section",{className:"flex flex-col gap-0",children:[e.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),e.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:K.map(C=>e.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:[e.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))}),E.length>4&&e.jsx("div",{className:"flex justify-center px-4 pt-2",children:e.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>j.setShowAllRecent(C=>!C),children:j.showAllRecent?"Show fewer":`Show ${E.length-4} more`})})]}),(j.hasIdeOptions||n.length>0||o.length>0)&&e.jsxs("section",{className:"flex flex-col gap-0",children:[e.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),e.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:e.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:[e.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),e.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),e.jsx("select",{value:j.workspaceChoice,onChange:C=>j.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:j.workspaceRows.length>0?e.jsxs(e.Fragment,{children:[j.workspaceRows.map(C=>e.jsxs("option",{value:C.id,children:[C.id===j.defaultWorkspaceId?"⭐ ":"",kr(C.path,C.label)||C.path]},C.id)),e.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):e.jsx("option",{value:"__custom__",children:"Select workspace…"})}),j.workspaceChoice==="__custom__"&&e.jsxs("div",{className:"flex flex-col gap-2.5",children:[e.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.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:e.jsx(xs,{size:17})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),e.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:j.resolvedWorkspacePath||j.browseCurrentPath||"No folder selected yet."})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-secondary text-[12px] font-bold",onClick:j.openBrowseDialog,children:"Select workspace…"}),e.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-accent-primary/30 bg-accent-primary/10 text-text-primary text-[12px] font-bold disabled:opacity-40",onClick:()=>{j.resolvedWorkspacePath&&l(j.resolvedWorkspacePath)},disabled:!j.resolvedWorkspacePath||j.browseBusy,children:"Save as workspace"})]})]}),j.resolvedWorkspacePath&&e.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[j.hasIdeOptions&&e.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${j.activeLauncherKind==="ide"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>j.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&e.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${j.activeLauncherKind==="cli"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>j.setActiveLauncherKind("cli"),children:"CLI"}),o.length>0&&e.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${j.activeLauncherKind==="acp"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>j.setActiveLauncherKind("acp"),children:"ACP"})]}),j.activeLauncherKind&&e.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[e.jsx("div",{className:"text-xs font-bold text-text-secondary",children:j.activeLauncherKind==="ide"?"Choose an IDE":j.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),e.jsx("div",{className:"grid grid-cols-1 gap-2",children:j.activeLauncherKind==="ide"?(t.detectedIdes||[]).slice(0,6).map(C=>e.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:T,selectedKey:z}=Zt({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspaceId:j.workspaceChoice!=="__custom__"?j.workspaceChoice:null,currentWorkspacePath:j.resolvedWorkspacePath});j.openLaunchConfirm({title:`Launch ${C.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:T,selectedWorkspaceKey:z,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:C.name}]},async()=>{const L=T.find($=>$.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption(L),v(C.type,{workspacePath:(L==null?void 0:L.workspacePath)??null})})},children:[e.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:C.name}),e.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath||"Use selected workspace"})]},C.type)):(j.activeLauncherKind==="cli"?n:o).map(C=>e.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 T=j.activeLauncherKind==="cli"?"cli":"acp",{options:z,selectedKey:L}=Zt({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspaceId:j.workspaceChoice!=="__custom__"?j.workspaceChoice:null,currentWorkspacePath:j.resolvedWorkspacePath});j.openLaunchConfirm({title:`Launch ${C.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${T.toUpperCase()}`,workspaceOptions:z,selectedWorkspaceKey:L,details:[{label:"Mode",value:T.toUpperCase()},{label:"Provider",value:C.displayName}],showArgsInput:!0,showModelInput:T==="acp",initialArgs:"",initialModel:"",providerType:C.type},async()=>{const $=z.find(H=>H.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption($),A(T,C.type,{workspaceId:($==null?void 0:$.workspaceId)??null,workspacePath:($==null?void 0:$.workspacePath)??null,args:j.launchConfirmArgs,model:j.launchConfirmModel,resumeSessionId:j.launchConfirmResumeId||null})})},children:[e.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[C.icon?`${C.icon} `:"",C.displayName]}),e.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath||"Use selected workspace"})]},C.type))})]}),d.message&&e.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,j.canCreateMissingWorkspace&&e.jsx("div",{className:"mt-2",children:e.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(j.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),e.jsxs("section",{className:"flex flex-col gap-0",children:[e.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),e.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[i&&e.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:b,children:[e.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),e.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:[e.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),j.browseDialogOpen&&e.jsx(Ar,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:j.browseCurrentPath,directories:j.browseDirectories,busy:j.browseBusy,error:j.browseError,confirmLabel:"Use this folder",onClose:()=>j.setBrowseDialogOpen(!1),onNavigate:C=>{j.loadBrowsePath(C)},onConfirm:C=>{j.chooseCustomWorkspacePath(C),j.setBrowseDialogOpen(!1)}}),j.launchConfirm&&e.jsx(Rn,{title:j.launchConfirm.title,description:j.launchConfirm.description,details:j.launchConfirm.details,workspaceOptions:j.launchConfirm.workspaceOptions,selectedWorkspaceKey:j.launchConfirmWorkspaceKey,onWorkspaceChange:j.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:j.launchConfirm.confirmLabel,busy:j.launchConfirmBusy,showArgsInput:j.launchConfirm.showArgsInput,argsValue:j.launchConfirmArgs,onArgsChange:j.setLaunchConfirmArgs,showModelInput:j.launchConfirm.showModelInput,modelValue:j.launchConfirmModel,onModelChange:j.setLaunchConfirmModel,historyProviderNode:j.launchConfirm.providerType&&(j.launchConfirmSessionsLoading||j.launchConfirmSavedSessions.length>0)&&e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume from history"}),j.launchConfirmSessionsLoading&&e.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),e.jsxs("select",{value:j.launchConfirmResumeId,onChange:C=>j.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:j.launchConfirmBusy||j.launchConfirmSessionsLoading,children:[e.jsx("option",{value:"",children:"Start a new session"}),j.launchConfirmSavedSessions.map(C=>e.jsxs("option",{value:C.providerSessionId,disabled:!C.canResume,children:[C.title||C.providerSessionId," ",C.canResume?"":"(workspace missing)"]},C.providerSessionId))]})]}),onConfirm:j.handleConfirmLaunch,onCancel:j.closeLaunchConfirm}),m&&e.jsx(Qo,{section:f,onSectionChange:w})]})}function ei(t){var r;const s=((r=t.p2p)==null?void 0:r.state)||"";return s==="connected"?"Connected":s==="connecting"||s==="new"||s==="checking"?"Connecting":"Offline"}function Mu(t,s){if(!t)return[];const r=t.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===t.id).map(n=>{var i,c,d,p,f;const o=$s(n)?"cli":ms(n)?"acp":"ide";return{id:`${o}:${n.type}:${n.workspace||""}`,label:((i=n.activeChat)==null?void 0:i.title)||($s(n)?n.cliName||n.type:ms(n)&&n.cliName||n.type),kind:o,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:ms(n)?n.currentModel||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,currentModel:n.currentModel,timestamp:((f=(p=(d=(c=n.activeChat)==null?void 0:c.messages)==null?void 0:d.at)==null?void 0:p.call(d,-1))==null?void 0:f.timestamp)||0}}).sort((n,o)=>o.timestamp-n.timestamp).map(({timestamp:n,...o})=>o)}function Tu(t,s){const r=new Map;for(const n of s){const o=zt(n.conversation),i=r.get(o);i?i.push(n):r.set(o,[n])}return t.map(n=>{const o=r.get(n.id)||[],i=[...o].sort((h,w)=>w.timestamp-h.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,d=rn(n),p=o.filter(h=>h.unread||h.requiresAction).length,f=ei(n),m=[n.platform||"machine",f].filter(Boolean);return{id:n.id,label:kt(n,{fallbackId:n.id}),subtitle:m.join(" · "),unread:p,total:o.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:d,preview:c?Il(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 er(t,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] ${t}`,s)}catch{}}function _u({conversations:t,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:o,screen:i,liveSessionInboxState:c,sendDaemonCommand:d,requestedActiveTabKey:p,onRequestedActiveTabConsumed:f,requestedMachineId:m,onRequestedMachineConsumed:h,requestedMobileSection:w,onRequestedMobileSectionConsumed:S,setSelectedTabKey:I,setScreen:u,setSelectedMachineId:b,setSection:v,setMachineBackTarget:l,resetMachineAction:N}){const A=a.useRef(null),k=a.useCallback(x=>{if(!(x!=null&&x.sessionId))return;const g=Ds(x,c),y=Math.max(Date.now(),Ht(x),g.lastUpdated||0);er("mark_read:start",{tabKey:x.tabKey,sessionId:x.sessionId,displayPrimary:Qe(x),inboxBucket:g.inboxBucket,unread:g.unread,lastSeenAt:g.lastSeenAt,lastUpdated:g.lastUpdated,activityAt:Ht(x),readAt:y}),d(zt(x)||x.routeId,"mark_session_seen",{sessionId:x.sessionId,seenAt:y}).then(j=>{er("mark_read:result",{tabKey:x.tabKey,sessionId:x.sessionId,result:j})}).catch(j=>{er("mark_read:error",{tabKey:x.tabKey,sessionId:x.sessionId,error:j instanceof Error?j.message:String(j)})})},[c,d]);return a.useEffect(()=>{var g;if(!n){u("inbox"),I(((g=t[0])==null?void 0:g.tabKey)||null),A.current=null;return}if(i!=="chat"){A.current=null;return}const x=`${n.tabKey}:${n.sessionId||""}`;A.current!==x&&(A.current=x,k(n))},[t,k,i,n,u,I]),a.useEffect(()=>{if(!p)return;const x=t.find(g=>g.tabKey===p);x&&(I(x.tabKey),u("chat"),f==null||f())},[t,f,p,u,I]),a.useEffect(()=>{if(!m)return;const x=s.find(g=>g.id===m);x&&(b(x.id),N(),v("machines"),l("inbox"),u("machine"),h==null||h())},[s,h,m,N,l,u,v,b]),a.useEffect(()=>{w&&(v(w),u("inbox"),S==null||S())},[S,w,u,v]),a.useEffect(()=>{const x=r.filter(g=>g.inboxBucket==="task_complete"||g.unread);x.length!==0&&er("inbox_state",{screen:i,selectedTabKey:o,items:x.map(g=>{const y=Ds(g.conversation,c);return{liveState:y,tabKey:g.conversation.tabKey,sessionId:g.conversation.sessionId,displayPrimary:Qe(g.conversation),serverBucket:y.inboxBucket,computedBucket:g.inboxBucket,serverUnread:y.unread,computedUnread:g.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,activityAt:Ht(g.conversation)}})})},[r,c,i,o]),{markConversationRead:k}}function Pu(t){if(!t)return"";const s=String(t);return s.includes(":")&&s.split(":")[0]||s}function La(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Lu(t){return(t instanceof Error?t.message:String(t||"")).includes("P2P command timeout")}function Ru({sendDaemonCommand:t,navigate:s,ides:r,conversations:n}){const[o,i]=a.useState("idle"),[c,d]=a.useState(""),[p,f]=a.useState(null),m=a.useCallback(()=>{i("idle"),d(""),f(null)},[]),h=a.useCallback(async(l,N,A)=>{var k;try{i("loading"),d(`Launching ${N}…`);const x={ideType:N,enableCdp:!0};(k=A==null?void 0:A.workspacePath)!=null&&k.trim()&&(x.workspace=A.workspacePath.trim()),await t(l,"launch_ide",x),i("done"),d(`${N} launch requested`)}catch(x){i("error"),d(x instanceof Error?x.message:"Launch IDE failed"),console.error("Launch IDE failed",x)}},[t]),w=a.useCallback(async(l,N,A)=>{if(N.trim())try{i("loading"),d(A!=null&&A.createIfMissing?"Creating folder…":"Saving workspace…");const k=await t(l,"workspace_add",{path:N.trim(),createIfMissing:(A==null?void 0:A.createIfMissing)===!0});if(k!=null&&k.success){i("done"),d(A!=null&&A.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")}},[t]),S=a.useCallback(async l=>{var N,A,k,x,g,y;try{i("loading"),d("Starting daemon upgrade…");const j=await t(l,"daemon_upgrade",{});if((N=j==null?void 0:j.result)!=null&&N.alreadyLatest){i("done"),d(`Already on v${((A=j==null?void 0:j.result)==null?void 0:A.version)||"latest"}.`);return}if((k=j==null?void 0:j.result)!=null&&k.upgraded||(x=j==null?void 0:j.result)!=null&&x.success){i("done"),d(`Upgrade to v${((g=j==null?void 0:j.result)==null?void 0:g.version)||"latest"} started. Daemon is restarting…`);return}i("error"),d(((y=j==null?void 0:j.result)==null?void 0:y.error)||"Upgrade failed")}catch(j){i("error"),d(j instanceof Error?j.message:"Upgrade failed")}},[t]),I=a.useCallback(async(l,N,A,k)=>{var y,j,E;const x=Date.now(),g={machineId:l,kind:N,providerType:A,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:x};try{i("loading"),d(`Launching ${A}…`),f(g);const R={cliType:A};(y=k==null?void 0:k.workspacePath)!=null&&y.trim()?R.dir=k.workspacePath.trim():k!=null&&k.workspaceId&&(R.workspaceId=k.workspaceId),k!=null&&k.resumeSessionId&&(R.resumeSessionId=k.resumeSessionId),(j=k==null?void 0:k.args)!=null&&j.trim()&&(R.cliArgs=k.args.trim().split(/\s+/).filter(Boolean)),(E=k==null?void 0:k.model)!=null&&E.trim()&&(R.initialModel=k.model.trim());const K=await t(l,"launch_cli",R),D=(K==null?void 0:K.result)||K,V=(D==null?void 0:D.sessionId)||(D==null?void 0:D.id);if(K!=null&&K.success&&V){f(null),i("done"),d(`${A} launched`),s(`/dashboard?activeTab=${encodeURIComponent(V)}`);return}if(K!=null&&K.success){i("loading"),d(`${A} launch requested — waiting for session…`);return}f(null),i("error"),d((K==null?void 0:K.error)||(D==null?void 0:D.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(R){if(Lu(R)){i("loading"),d(`${A} launch requested — waiting for session…`);return}f(null),i("error"),d(R instanceof Error?R.message:`Could not launch ${N.toUpperCase()} workspace`)}},[s,t]),u=a.useCallback(async(l,N)=>{try{const A=await t(l,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),k=(A==null?void 0:A.result)??A;return Array.isArray(k==null?void 0:k.sessions)?k.sessions:[]}catch(A){return console.error("Failed to list saved sessions on mobile:",A),[]}},[t]),b=a.useCallback(async(l,N)=>Ir(t,l,N),[t]);a.useEffect(()=>{var k;if(!p)return;const l=La(p.workspacePath),N=r.find(x=>{var K,D,V,_;if(!x||x.type==="adhdev-daemon"||Pu(x.daemonId||x.id)!==p.machineId||(x.transport==="acp"?"acp":x.transport==="pty"?"cli":null)!==p.kind||String(x.agentType||x.type||"")!==p.providerType)return!1;const E=String(x.providerSessionId||"");if(p.resumeSessionId&&E)return E===p.resumeSessionId;if(l){const C=La(x.workspace||x.runtimeWorkspaceLabel);return C?C===l:!1}return Number(x.lastUpdated||x._lastUpdate||x.timestamp||((_=(V=(D=(K=x.activeChat)==null?void 0:K.messages)==null?void 0:D.at)==null?void 0:V.call(D,-1))==null?void 0:_.timestamp)||0)>=p.startedAt-5e3});if(!N)return;const A=typeof N.sessionId=="string"&&N.sessionId?N.sessionId:typeof N.instanceId=="string"&&N.instanceId?N.instanceId:(k=n.find(x=>x.routeId===N.id))==null?void 0:k.sessionId;A&&(f(null),i("done"),d(`${p.providerType} launched`),s(`/dashboard?activeTab=${encodeURIComponent(A)}`))},[n,r,s,p]),a.useEffect(()=>{if(!p)return;const l=window.setTimeout(()=>{f(N=>!N||N.startedAt!==p.startedAt?N:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(l)},[p]);const v=a.useCallback(async(l,N)=>{if(N.kind==="ide"&&N.providerType){await h(l,N.providerType,{workspacePath:N.workspace||null});return}(N.kind==="cli"||N.kind==="acp")&&N.providerType&&await I(l,N.kind,N.providerType,{workspacePath:N.workspace||null,resumeSessionId:N.providerSessionId||null})},[h,I]);return{machineAction:{state:o,message:c},resetMachineAction:m,handleLaunchDetectedIde:h,handleAddWorkspace:w,handleMachineUpgrade:S,handleLaunchWorkspaceProvider:I,handleListSavedSessions:u,handleBrowseDirectory:b,handleOpenRecent:v}}function Du({conversations:t,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:o,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:d,setSection:p,setMachineBackTarget:f}){const m=a.useCallback(v=>{i(v.tabKey),c("chat"),n(v)},[n,c,i]),h=a.useCallback(v=>{const l=t.find(N=>N.routeId===v.routeId&&N.streamSource==="native");l&&(i(l.tabKey),c("chat"),n(l))},[t,n,c,i]),w=a.useCallback(()=>{n(s),c("inbox")},[n,s,c]),S=a.useCallback((v,l="inbox")=>{d(v),o(),p("machines"),f(l),c("machine")},[o,f,c,p,d]),I=a.useCallback(v=>{const l=zt(v);l&&S(l,"chat")},[S]),u=a.useCallback(()=>{o(),c(r)},[r,o,c]),b=a.useCallback(v=>{p(v),c("inbox")},[c,p]);return{openConversation:m,openNativeConversation:h,backFromConversation:w,openMachine:S,openConversationMachine:I,backFromMachine:u,changeMachineSection:b}}function Eu(t){const s=t.trim();return s?s[0].toUpperCase():"?"}function $u(t){const s=t instanceof Error?t.message:String(t||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function tr(t){return[...t].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Bu({conversations:t,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:d,userName:p,requestedActiveTabKey:f,onRequestedActiveTabConsumed:m,requestedMachineId:h,onRequestedMachineConsumed:w,requestedMobileSection:S,onRequestedMobileSectionConsumed:I,onOpenHistory:u,onOpenRemote:b,onStopCli:v,wsStatus:l,isConnected:N,onShowHiddenConversation:A,onShowAllHiddenConversations:k,onHideConversation:x,onOpenNewSession:g}){const[y,j]=a.useState(()=>{var F;return((F=t[0])==null?void 0:F.tabKey)||null}),[E,R]=a.useState(()=>t[0]?"chat":"inbox"),[K,D]=a.useState("chats"),[V,_]=a.useState(null),[C,T]=a.useState("inbox"),z=bs(),L="0.8.51",$=a.useMemo(()=>t.find(F=>F.tabKey===y)||t[0]||null,[t,y]),H=a.useMemo(()=>$?r.find(F=>F.id===$.routeId):void 0,[r,$]),se=a.useMemo(()=>!$||Ve($)||!Xe($)?null:hs($),[$]),Y=a.useMemo(()=>r.filter(F=>F.type==="adhdev-daemon").sort(wn),[r]),ie=a.useMemo(()=>Y.find(F=>F.id===V)||null,[Y,V]),je=a.useMemo(()=>Ws(r),[r]),G=Sr({sendDaemonCommand:o,activeConv:$||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:d}),oe=Ru({sendDaemonCommand:o,navigate:z,ides:r,conversations:t}),W=a.useMemo(()=>t.map(F=>{const me=E==="chat"&&($==null?void 0:$.tabKey)===F.tabKey,Ce=Es(F,je,{hideOpenTaskCompleteUnread:!0,isOpenConversation:me}),xe=Ht(F),Le=ko(F);return{conversation:F,timestamp:xe,preview:Le,unread:Ce.unread,requiresAction:Ce.requiresAction,isWorking:Ce.isWorking,inboxBucket:Ce.inboxBucket}}),[t,je,E,$]),{markConversationRead:be}=_u({conversations:t,machineEntries:Y,items:W,selectedConversation:$,selectedTabKey:y,screen:E,liveSessionInboxState:je,sendDaemonCommand:o,requestedActiveTabKey:f,onRequestedActiveTabConsumed:m,requestedMachineId:h,onRequestedMachineConsumed:w,requestedMobileSection:S,onRequestedMobileSectionConsumed:I,setSelectedTabKey:j,setScreen:R,setSelectedMachineId:_,setSection:D,setMachineBackTarget:T,resetMachineAction:oe.resetMachineAction}),X=Du({conversations:t,selectedConversation:$,machineBackTarget:C,markConversationRead:be,resetMachineAction:oe.resetMachineAction,setSelectedTabKey:j,setScreen:R,setSelectedMachineId:_,setSection:D,setMachineBackTarget:T}),ue=a.useMemo(()=>tr(W.filter(F=>F.requiresAction)),[W]),te=a.useMemo(()=>tr(W.filter(F=>F.unread&&!F.requiresAction)),[W]),ae=a.useMemo(()=>tr(W.filter(F=>!F.unread&&!F.requiresAction&&F.isWorking)),[W]),fe=a.useMemo(()=>tr(W.filter(F=>!F.unread&&!F.requiresAction&&!F.isWorking)),[W]),le=a.useMemo(()=>ie?W.filter(F=>zt(F.conversation)===ie.id):[],[W,ie]),he=a.useMemo(()=>Mu(ie,r),[r,ie]),J=(ie==null?void 0:ie.version)||null,pe=!!ie&&!!J&&!0&&J!==L,ne=a.useMemo(()=>(ie==null?void 0:ie.availableProviders)||[],[ie]),we=a.useMemo(()=>ne.filter(F=>F.category==="cli"&&F.installed!==!1).map(F=>({type:F.type,displayName:F.displayName||F.type,icon:F.icon})),[ne]),ge=a.useMemo(()=>ne.filter(F=>F.category==="acp"&&F.installed!==!1).map(F=>({type:F.type,displayName:F.displayName||F.type,icon:F.icon})),[ne]),P=a.useMemo(()=>Tu(Y,W),[W,Y]),ye=a.useCallback(async F=>{ie&&await oe.handleOpenRecent(ie.id,F)},[oe,ie]);return e.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:E==="chat"&&$?e.jsx(ju,{selectedConversation:$,isAcp:Ve($),isStandalone:d,selectedIdeEntry:H,actionLogs:n,userName:p,isSendingChat:G.isSendingChat,isFocusingAgent:G.isFocusingAgent,handleModalButton:G.handleModalButton,handleRelaunch:G.handleRelaunch,onBack:X.backFromConversation,onOpenNativeConversation:X.openNativeConversation,onOpenMachine:X.openConversationMachine,onHideConversation:x,onOpenHistory:u,onOpenRemote:b,onStopCli:v,cliViewMode:se,onSetCliViewMode:async F=>{if($&&se!==F)try{await o(zt($)||$.routeId,"set_cli_view_mode",{targetSessionId:$.sessionId,cliType:jt($),mode:F})}catch(me){$u(me)?console.warn("Skipped CLI view mode switch:",me instanceof Error?me.message:String(me)):console.error("Failed to switch CLI view mode:",me)}},handleSendChat:G.handleSendChat,handleFocusAgent:G.handleFocusAgent}):E==="machine"&&ie?e.jsx(Au,{selectedMachineEntry:ie,selectedMachineConversations:le,selectedMachineRecentLaunches:he,cliProviders:we,acpProviders:ge,selectedMachineNeedsUpgrade:pe,appVersion:L,machineAction:oe.machineAction,isStandalone:d,section:K,showBottomNav:C==="inbox",onBack:X.backFromMachine,onSectionChange:X.changeMachineSection,onOpenConversation:X.openConversation,onOpenRecent:ye,onOpenMachineDetails:()=>z(`/machines/${ie.id}`),onMachineUpgrade:()=>oe.handleMachineUpgrade(ie.id),onLaunchDetectedIde:(F,me)=>oe.handleLaunchDetectedIde(ie.id,F,me),onAddWorkspace:(F,me)=>oe.handleAddWorkspace(ie.id,F,me),onBrowseDirectory:F=>oe.handleBrowseDirectory(ie.id,F),onLaunchWorkspaceProvider:(F,me,Ce)=>oe.handleLaunchWorkspaceProvider(ie.id,F,me,Ce),onListSavedSessions:F=>oe.handleListSavedSessions(ie.id,F)}):e.jsx(Nu,{section:K,attentionItems:ue,unreadItems:te,workingItems:ae,completedItems:fe,hiddenConversations:s,machineCards:P,getAvatarText:Eu,onOpenConversation:X.openConversation,onShowConversation:A,onShowAllHidden:k,onOpenNewSession:g,onOpenMachine:X.openMachine,onOpenSettings:()=>z("/settings"),onSectionChange:D,wsStatus:l,isConnected:N,isStandalone:d})})}function zr(t,s){return!!(t<4&&s&&window.innerWidth>=768)}function Ku({conversations:t,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:o,onClearPreviewOrder:i}){const c=a.useRef(0),[d,p]=a.useState(!1),[f,m]=a.useState(null),h=a.useCallback(()=>{c.current=0,p(!1),m(null)},[]);a.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const w=a.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,p(!0))},[]),S=a.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!zr(s,r)){m("merge");return}const v=b.currentTarget.getBoundingClientRect(),l=b.clientX-v.left,N=v.width/3;l<N?m("split-left"):l>N*2?m("split-right"):m("merge")},[s,r]),I=a.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,p(!1),m(null))},[]),u=a.useCallback(b=>{c.current=0,p(!1);const v=b.dataTransfer.getData("text/tab-key"),l=v?t.some(A=>A.tabKey===v):!1,N=f;if(m(null),i(),!!v){if(b.preventDefault(),N==="split-left"&&zr(s,r)){r==null||r(v,"split-left");return}if(N==="split-right"&&zr(s,r)){r==null||r(v,"split-right");return}if(l){o(v);return}n==null||n(v)}},[t,f,s,r,n,o,i]);return{dragOver:d,dropAction:f,resetDragState:h,handleDragEnter:w,handleDragOver:S,handleDragLeave:I,handleDrop:u}}function Wu(t,s){const r=new Set(s.map(i=>i.tabKey)),n=t.filter(i=>r.has(i)),o=s.filter(i=>!t.includes(i.tabKey)).map(i=>i.tabKey);return[...n,...o]}function Ou({conversations:t,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:o}){const[i,c]=a.useState(s??null),[d,p]=a.useState(r??[]),[f,m]=a.useState(null),h=a.useRef(null),w=a.useRef(null),S=a.useRef(n),I=a.useRef(o);a.useEffect(()=>{S.current=n},[n]),a.useEffect(()=>{I.current=o},[o]),a.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),a.useEffect(()=>{p(g=>{const y=Wu(g,t);return y.length===g.length&&y.every((j,E)=>j===g[E])?g:y})},[t]);const u=a.useMemo(()=>{const g=f??d;if(g.length===0)return t;const y=new Map(g.map((j,E)=>[j,E]));return[...t].sort((j,E)=>{const R=y.get(j.tabKey)??999,K=y.get(E.tabKey)??999;return R-K})},[t,f,d]);a.useEffect(()=>{var y,j;if(u.length===0){i!==null&&(c(null),(y=S.current)==null||y.call(S,null));return}if(i&&u.some(E=>E.tabKey===i))return;const g=u[0].tabKey;g!==i&&(c(g),(j=S.current)==null||j.call(S,g))},[u,i]);const b=a.useMemo(()=>u.find(g=>g.tabKey===i),[u,i]),v=a.useCallback(g=>{var y;c(g),(y=S.current)==null||y.call(S,g)},[]),l=a.useCallback((g,y,j)=>{p(E=>{var V;const R=E.filter(_=>_!==g),K=R.indexOf(y);if(K<0)return E;const D=j==="left"?K:K+1;return R.splice(D,0,g),(V=I.current)==null||V.call(I,R),R}),m(null)},[]),N=a.useCallback((g,y,j)=>{const R=(d.length>0?d:t.map(V=>V.tabKey)).filter(V=>V!==g),K=R.indexOf(y);if(K<0)return;const D=j==="left"?K:K+1;R.splice(D,0,g),h.current=R,m(R)},[d,t]),A=a.useCallback(()=>{var y;const g=h.current;g&&(p(g),(y=I.current)==null||y.call(I,g))},[]),k=a.useCallback(()=>{h.current=null,m(null)},[]),x=a.useCallback(g=>{p(y=>{var E;const j=y.filter(R=>R!==g);return j.push(g),(E=I.current)==null||E.call(I,j),j})},[]);return{activeTabId:i,activeConv:b,sortedConversations:u,previewOrderRef:h,draggingTabRef:w,selectTab:v,handleTabReorder:l,updatePreviewOrder:N,commitPreviewOrder:A,clearPreviewOrder:k,moveTabToEnd:x,setDraggingTabKey:g=>{w.current=g}}}function Hu({dropAction:t,canSplit:s}){return e.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[e.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:t==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:t==="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:e.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"})}),e.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:t==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:t==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:e.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"})}),e.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:t==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:t==="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:e.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 Dn({conversationsCount:t,isSplitMode:s,isStandalone:r,hasRegisteredMachines:n=!1,detectedIdes:o,handleLaunchIde:i}){const c=!r&&!n,d=r?"Waiting for your daemon":n?"No conversations yet":"Connect your first machine",p=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 the ADHDev daemon and link your dashboard to start.";return t===0&&!s&&o&&i?e.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[e.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:e.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),e.jsxs("div",{className:"text-center max-w-lg",children:[e.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:d}),e.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:p}),c&&e.jsx(Zo,{}),r&&o.length>0&&e.jsxs("div",{className:"flex flex-col gap-3 items-center",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wider text-text-muted",children:"Detected IDEs"}),e.jsx("div",{className:"flex flex-wrap gap-2.5 justify-center mt-1",children:o.map(f=>e.jsxs("button",{className:"btn btn-sm bg-accent/10 border border-accent/25 text-accent text-xs font-medium px-4 py-2.5 rounded-lg cursor-pointer flex items-center gap-2 transition-all hover:bg-accent/20 hover:scale-105 active:scale-95",onClick:()=>i(f.type),children:[e.jsx(oo,{size:14,className:"opacity-70"})," Open ",f.name]},f.type))})]}),c&&e.jsx("div",{className:"mt-8",children:e.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 →"})})]})]}):e.jsx("div",{className:"text-sm text-text-muted opacity-50",children:s?"Move a tab here to view":"No active agent"})}const ti="adhdev-tab-shortcuts";function si(){try{return JSON.parse(localStorage.getItem(ti)||"{}")}catch{return{}}}function ri({enabled:t=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const o=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=a.useState(()=>si()),[d,p]=a.useState(null),f=a.useCallback(h=>{const w=[];return h.metaKey&&w.push(o?"⌘":"Meta"),h.ctrlKey&&w.push("Ctrl"),h.altKey&&w.push(o?"⌥":"Alt"),h.shiftKey&&w.push(o?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(w.push(h.key.length===1?h.key.toUpperCase():h.key),w.join("+"))},[o]),m=a.useCallback(h=>{c(h);try{localStorage.setItem(ti,JSON.stringify(h))}catch{}},[]);return a.useEffect(()=>{if(!t||!d)return;const h=w=>{if(w.preventDefault(),w.stopPropagation(),w.key==="Escape"){p(null);return}const S=f(w);if(!S)return;const I={...i};for(const[u,b]of Object.entries(I))b===S&&delete I[u];I[d]=S,m(I),p(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[t,d,i,m,f]),a.useEffect(()=>{if(!t)return;const h=w=>{if(!(!w.ctrlKey&&!w.metaKey&&!w.altKey)){for(const[S,I]of Object.entries(i))if(s.includes(S)&&f(w)===I){w.preventDefault(),r(),n(S);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[t,i,s,r,n,f]),{isMac:o,tabShortcuts:i,shortcutListening:d,setShortcutListening:p,saveShortcuts:m}}const Uu=a.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:o,shortcut:i,conversationKeys:c,draggingTabRef:d,onFocus:p,onSelectTab:f,onConversationActivated:m,onPreviewReorder:h,onReorderTab:w,onCommitPreviewOrder:S,onClearPreviewOrder:I,onDragStateReset:u,onDragTabKeyChange:b,onReceiveTab:v,onOpenContextMenu:l,longPressTimer:N,isGroupActive:A}){const k=ys(s),x=k.isGenerating?"agent-tab-generating":k.isWaiting?"agent-tab-waiting":"",g=k.isReconnecting,y=a.useCallback(T=>{d.current=s.tabKey,b(s.tabKey),T.dataTransfer.setData("text/tab-key",s.tabKey),T.dataTransfer.effectAllowed="move"},[s.tabKey,d,b]),j=a.useCallback(()=>{d.current=null,b(null),S(),I(),u()},[d,b,S,I,u]),E=a.useCallback(T=>{const z=d.current;if(!(!z||z===s.tabKey)&&T.dataTransfer.types.includes("text/tab-key")){T.preventDefault(),T.stopPropagation();const L=T.currentTarget.getBoundingClientRect(),$=T.clientX<L.left+L.width/2?"left":"right";h(z,s.tabKey,$)}},[s.tabKey,d,h]),R=a.useCallback(T=>{T.preventDefault(),T.stopPropagation();const z=T.dataTransfer.getData("text/tab-key");if(z&&z!==s.tabKey){const L=T.currentTarget.getBoundingClientRect(),$=T.clientX<L.left+L.width/2?"left":"right";c.includes(z)?w(z,s.tabKey,$):v&&v(z)}I()},[s.tabKey,c,w,v,I]),K=a.useCallback(T=>{T.stopPropagation(),p(),f(s.tabKey),m(s)},[s,m,p,f]),D=a.useCallback(T=>{T.preventDefault(),l(T.clientX,T.clientY,s.tabKey)},[s.tabKey,l]),V=a.useCallback(T=>{const z=T.touches[0];N.current=setTimeout(()=>{l(z.clientX,z.clientY,s.tabKey)},600)},[s.tabKey,N,l]),_=a.useCallback(()=>{N.current&&clearTimeout(N.current)},[N]),C=["adhdev-dockview-tab",x,r&&"is-active",A&&"is-group-active",g&&"is-reconnecting"].filter(Boolean).join(" ");return e.jsxs("div",{"data-tabkey":s.tabKey,className:C,draggable:!0,onDragStart:y,onDragEnd:j,onDragOver:E,onDrop:R,onClick:K,onContextMenu:D,onTouchStart:V,onTouchEnd:_,onTouchMove:_,style:{cursor:"pointer",opacity:n?.4:void 0},children:[o&&e.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),e.jsx("div",{className:"adhdev-dockview-tab-status",children:k.isGenerating?e.jsx("div",{className:"tab-spinner"}):k.isWaiting?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):g?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):k.isConnecting?e.jsx("div",{className:"tab-connecting-spinner"}):s.connectionState==="connected"?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):e.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),e.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[e.jsx("span",{className:"adhdev-dockview-tab-primary",title:Qe(s),children:Qe(s)}),e.jsx("span",{className:"adhdev-dockview-tab-meta",children:g?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Yt(s)}):k.isConnecting?e.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[Yt(s),e.jsx("span",{className:"connecting-dots"})]}):Yt(s)})]}),i&&e.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})]})},(t,s)=>t.conv===s.conv&&t.isActive===s.isActive&&t.isDraggedTab===s.isDraggedTab&&t.isTaskCompleteUnread===s.isTaskCompleteUnread&&t.shortcut===s.shortcut&&t.conversationKeys===s.conversationKeys&&t.isGroupActive===s.isGroupActive);function zu({conversations:t,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:o,onFocus:i,onSelectTab:c,onConversationActivated:d,onPreviewReorder:p,onReorderTab:f,onCommitPreviewOrder:m,onClearPreviewOrder:h,onDragStateReset:w,onDragTabKeyChange:S,onReceiveTab:I,onHideTab:u,isGroupActive:b,allowTabShortcuts:v=!0}){const[l,N]=a.useState(null),A=a.useRef(null),k=a.useRef(null),x=a.useMemo(()=>t.map(D=>D.tabKey),[t]);Ks("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:t.length,ctxMenuTab:(l==null?void 0:l.tabKey)||null});const{isMac:g,tabShortcuts:y,shortcutListening:j,setShortcutListening:E,saveShortcuts:R}=ri({enabled:v,sortedTabKeys:t.map(D=>D.tabKey),onFocus:i,onSelectTab:c});a.useEffect(()=>{if(!l)return;const D=V=>{const _=document.querySelector("[data-pane-context-menu]");_&&_.contains(V.target)||N(null)};return window.addEventListener("mousedown",D,!0),()=>window.removeEventListener("mousedown",D,!0)},[l]),a.useEffect(()=>{const D=k.current;if(!D)return;const V=_=>{Math.abs(_.deltaY)>Math.abs(_.deltaX)&&(_.preventDefault(),D.scrollLeft+=_.deltaY)};return D.addEventListener("wheel",V,{passive:!1}),()=>D.removeEventListener("wheel",V)},[]);const K=a.useCallback((D,V,_)=>{N({x:D,y:V,tabKey:_})},[]);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:e.jsxs("div",{ref:k,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none"},children:[t.map(D=>e.jsx(Uu,{conv:D,isActive:s===D.tabKey,isDraggedTab:o.current===D.tabKey,isTaskCompleteUnread:n.has(D.tabKey),shortcut:v?y[D.tabKey]:void 0,conversationKeys:x,draggingTabRef:o,onFocus:i,onSelectTab:c,onConversationActivated:d,onPreviewReorder:p,onReorderTab:f,onCommitPreviewOrder:m,onClearPreviewOrder:h,onDragStateReset:w,onDragTabKeyChange:S,onReceiveTab:I,onOpenContextMenu:K,longPressTimer:A,isGroupActive:b},D.tabKey)),t.length===0&&e.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),l&&e.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:[v&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:D=>{D.stopPropagation(),E(l.tabKey),N(null)},children:["⌨ ",y[l.tabKey]?`Change shortcut (${y[l.tabKey]})`:"Set shortcut"]}),y[l.tabKey]&&e.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 D={...y};delete D[l.tabKey],R(D),N(null)},children:"✕ Remove shortcut"})]}),u&&e.jsxs(e.Fragment,{children:[v&&e.jsx("div",{className:"border-t border-border-subtle my-1"}),e.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),N(null)},children:"🚫 Hide from Dashboard"})]})]}),v&&j&&e.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:()=>E(null),children:e.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:D=>D.stopPropagation(),children:[e.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),e.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",g?"⌘+1":"Ctrl+1",", ",g?"⌥+A":"Alt+A",")"]}),e.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),e.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function Fu({conversations:t,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:d,hasRegisteredMachines:p,userName:f,groupIndex:m,onFocus:h,isSplitMode:w,numGroups:S,onMoveTab:I,onReceiveTab:u,style:b,detectedIdes:v,handleLaunchIde:l,onActiveTabChange:N,initialActiveTabId:A,initialTabOrder:k,onTabOrderChange:x,onHideTab:g,isFocused:y,allowTabShortcuts:j=!0}){const{sendCommand:E}=St(),R=a.useRef(null),{activeTabId:K,activeConv:D,sortedConversations:V,draggingTabRef:_,selectTab:C,handleTabReorder:T,updatePreviewOrder:z,commitPreviewOrder:L,clearPreviewOrder:$,moveTabToEnd:H,setDraggingTabKey:se}=Ou({conversations:t,initialActiveTabId:A,initialTabOrder:k,onActiveTabChange:N,onTabOrderChange:x}),Y=Sr({sendDaemonCommand:o,activeConv:D,setLocalUserMessages:i,setActionLogs:c,isStandalone:d}),{dragOver:ie,dropAction:je,resetDragState:G,handleDragEnter:oe,handleDragOver:W,handleDragLeave:be,handleDrop:X}=Ku({conversations:t,numGroups:S,onMoveTab:I,onReceiveTab:u,onOwnTabDrop:H,onClearPreviewOrder:$}),ue=D&&!Ve(D)&&hs(D)==="terminal",te=a.useMemo(()=>D?s.find(J=>J.id===D.routeId):void 0,[s,D]),ae=a.useMemo(()=>D?n.filter(J=>J.routeId===D.tabKey):[],[n,D]),fe=a.useMemo(()=>Ws(s),[s]),le=a.useMemo(()=>new Set(V.filter(J=>Kc(J,fe,{isOpenConversation:J.tabKey===K})).map(J=>J.tabKey)),[K,fe,V]);Ks("PaneGroup",{groupIndex:m,conversationCount:t.length,activeTabId:K,dragOver:ie});const he=a.useCallback(J=>{J.streamSource==="agent-stream"&&J.agentType&&E(J.routeId,"focus_session",{agentType:J.agentType,...J.sessionId&&{targetSessionId:J.sessionId}}).catch(()=>{})},[E]);return e.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:h,style:{...b,outline:ie?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[e.jsx(zu,{conversations:V,activeTabId:K,groupIndex:m,numGroups:S,unreadTabKeys:le,draggingTabRef:_,onFocus:h,onSelectTab:C,onConversationActivated:he,onPreviewReorder:z,onReorderTab:T,onCommitPreviewOrder:L,onClearPreviewOrder:$,onDragStateReset:G,onDragTabKeyChange:se,onMoveTab:I,onReceiveTab:u,onHideTab:g,isGroupActive:y??!1,allowTabShortcuts:j}),e.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:oe,onDragOver:W,onDragLeave:be,onDrop:X,children:[ie&&e.jsx(Hu,{dropAction:je,canSplit:!!(S<4&&I)}),D?e.jsx(Ln,{activeConv:D,clearToken:r[D.tabKey]||0,isCliTerminal:!!ue,ideEntry:te,terminalRef:R,handleModalButton:Y.handleModalButton,handleRelaunch:Y.handleRelaunch,handleSendChat:Y.handleSendChat,isSendingChat:Y.isSendingChat,handleFocusAgent:Y.handleFocusAgent,isFocusingAgent:Y.isFocusingAgent,actionLogs:ae,userName:f,isInputActive:!w||!!y}):e.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:e.jsx(Dn,{conversationsCount:t.length,isSplitMode:w,isStandalone:d,hasRegisteredMachines:p,detectedIdes:v,handleLaunchIde:l})})]})]})}function Vu({containerRef:t,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:o,clearedTabs:i,ides:c,actionLogs:d,sendDaemonCommand:p,setLocalUserMessages:f,setActionLogs:m,isStandalone:h,hasRegisteredMachines:w,userName:S,focusedGroup:I,setFocusedGroup:u,moveTabToGroup:b,splitTabRelative:v,closeGroup:l,handleResizeStart:N,detectedIdes:A,handleLaunchIde:k,groupActiveTabIds:x,setGroupActiveTabIds:g,groupTabOrders:y,setGroupTabOrders:j,toggleHiddenTab:E,allowTabShortcuts:R=!0}){return e.jsx("div",{ref:t,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:o.map((K,D)=>{const V=s&&n.length===r?`${n[D]}%`:void 0;return e.jsxs(et.Fragment,{children:[s&&D>0&&e.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:_=>N(D-1,_),onDoubleClick:()=>l(D),title:"Drag to resize · Double-click to merge",children:e.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),e.jsx(Fu,{style:s?{flexBasis:V??`${100/r}%`,flexGrow:V?0:1,flexShrink:V?0:1}:void 0,conversations:K,clearedTabs:i,ides:c,actionLogs:d,sendDaemonCommand:p,setLocalUserMessages:f,setActionLogs:m,isStandalone:h,hasRegisteredMachines:w,userName:S,groupIndex:D,isFocused:s&&I===D,onFocus:()=>u(D),isSplitMode:s,numGroups:r,onMoveTab:(_,C)=>{C==="left"&&D>0?b(_,D-1):C==="right"&&D<r-1?b(_,D+1):C==="split-left"&&r<4?v(_,D,"left"):C==="split-right"&&r<4&&v(_,D,"right")},onReceiveTab:_=>b(_,D),detectedIdes:D===0?A:void 0,handleLaunchIde:D===0?k:void 0,onActiveTabChange:_=>g(C=>(C[D]??null)===(_??null)?C:{...C,[D]:_}),initialActiveTabId:x[D],initialTabOrder:y[D],onTabOrderChange:_=>j(C=>{const T=C[D]||[];return T.length===_.length&&T.every((z,L)=>z===_[L])?C:{...C,[D]:_}}),onHideTab:E,allowTabShortcuts:R})]},D)})})}function ni({doId:t,targetSessionId:s,connState:r,viewMode:n}){const[o,i]=a.useState(null),[c,d]=a.useState(null);a.useEffect(()=>t?tt.onScreenshot("ide-page",(m,h)=>{if(m!==t)return;const w=new FileReader;w.onload=()=>i(w.result),w.readAsDataURL(h)}):void 0,[t]),a.useEffect(()=>{r!=="connected"&&i(null)},[r]),a.useEffect(()=>{var m;return t?((m=tt.onStatus)==null?void 0:m.call(tt,(h,w)=>{h===t&&w!=null&&w.screenshotUsage&&d(w.screenshotUsage)}))||(()=>{}):void 0},[t]),a.useEffect(()=>{i(null)},[t,s]),a.useEffect(()=>{const f=t?tt.get(t):null;if(!(!f||r!=="connected"))return n!=="chat"&&s?f.startScreenshots(s):f.stopScreenshots(s),()=>{f.stopScreenshots(s)}},[n,r,s,t]);const p=a.useCallback(async(f,m)=>{const h=t?tt.get(t):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(f,m,s)},[t,r,s]);return{connScreenshot:o,screenshotUsage:c,handleRemoteAction:p}}const ai="adhdev-dashboard-action-shortcuts",Gu=1200,qu={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Yu(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function Je(t,s){switch(t){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 oi(t){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:Je("openShortcutHelp",t)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:Je("hideCurrentTab",t)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:Je("toggleHiddenTabs",t)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:Je("openHistoryForActiveTab",t)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:Je("openRemoteForActiveTab",t)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:Je("floatActiveTab",t)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:Je("popoutActiveTab",t)},{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",t)},{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",t)},{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",t)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:Je("focusLeftPane",t)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:Je("focusRightPane",t)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:Je("focusUpPane",t)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:Je("focusDownPane",t)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:Je("moveActiveTabToLeftPane",t)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:Je("moveActiveTabToRightPane",t)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:Je("moveActiveTabToUpPane",t)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:Je("moveActiveTabToDownPane",t)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:Je("triggerPrimaryApprovalAction",t)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:Je("triggerSecondaryApprovalAction",t)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:Je("triggerTertiaryApprovalAction",t)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:Je("setActiveTabShortcut",t)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:Je("selectPreviousGroupTab",t)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:Je("selectNextGroupTab",t)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:Je("toggleCliView",t)}]}function pn(t){if(!(t instanceof HTMLElement))return!1;if(t.isContentEditable)return!0;const s=t.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function gr(t){const s=Object.fromEntries(oi(t).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(ai)||"{}"),n={...s,...r};for(const[o,i]of Object.entries(qu))n[o]===i&&(n[o]=s[o]);return n}catch{return s}}function ii(t){return t===" "?"Space":t==="Escape"?"Esc":t==="ArrowLeft"?"←":t==="ArrowRight"?"→":t==="ArrowUp"?"↑":t==="ArrowDown"?"↓":t.length===1?t.toUpperCase():t}function Xu({enabled:t=!0,onTrigger:s}){const r=Yu(),[n,o]=a.useState(()=>gr(r)),[i,c]=a.useState(null),[d,p]=a.useState([]),f=a.useRef({parts:[],timer:null}),m=a.useCallback(u=>{const b=[];return u.metaKey&&b.push(r?"⌘":"Meta"),u.ctrlKey&&b.push("Ctrl"),u.altKey&&b.push(r?"⌥":"Alt"),u.shiftKey&&u.key.length!==1&&b.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(u.key)?null:(b.push(ii(u.key)),b.join("+"))},[r]),h=a.useCallback(u=>{o(u);try{localStorage.setItem(ai,JSON.stringify(u))}catch{}},[]);a.useEffect(()=>{const u=gr(r),b=Object.entries(n),v=Object.entries(u);b.length===v.length&&b.every(([l,N])=>u[l]===N)||h(u)},[n,r,h]);const w=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}},Gu))},[]);a.useEffect(()=>{if(!i)return;const u=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){c(null),p([]);return}const v=m(b);if(!v)return;const N=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(v);if(d.length===0&&N){p([v]);return}const k=[...d,v].slice(0,2).join(" "),x={...n};for(const[g,y]of Object.entries(x))y===k&&delete x[g];x[i]=k,h(x),c(null),p([])};return window.addEventListener("keydown",u,!0),()=>window.removeEventListener("keydown",u,!0)},[n,m,h,i,d]),a.useEffect(()=>{if(!t||i)return;const u=b=>{if(b.defaultPrevented)return;const v=m(b);if(!v)return;const l=b.metaKey||b.ctrlKey||b.altKey;if(pn(b.target)&&!l)return;const N=f.current.parts,A=l?[v]:[...N.slice(-1),v].slice(-2),k=A.join(" "),x=A[A.length-1],g=Object.entries(n).filter(([,K])=>!!K),y=g.find(([,K])=>K===k);if(y){b.preventDefault(),w(),s(y[0]);return}if(g.some(([,K])=>K.startsWith(`${k} `))){b.preventDefault(),f.current.parts=A,S();return}const E=g.find(([,K])=>K===x);if(E){b.preventDefault(),w(),s(E[0]);return}if(g.some(([,K])=>K.startsWith(`${x} `))){b.preventDefault(),f.current.parts=[x],S();return}w()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[n,S,t,m,s,w,i]),a.useEffect(()=>()=>w(),[w]);const I=a.useMemo(()=>oi(r),[r]);return{isMac:r,actionDefinitions:I,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:d,setShortcutListening:c,setShortcutListeningDraft:p,saveShortcuts:h}}const ci=a.createContext(null);function Mr(){const t=a.useContext(ci);if(!t)throw new Error("DashboardDockviewContext missing");return t}function lr(t){return Qe(t)||t.tabKey}function Ju(t){return`remote:${t}`}function Wt(t){return t.startsWith("remote:")}function Ra(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Fr(t){var r,n,o,i,c;const s=t==null?void 0:t.defaultView;if(s)try{s.focus(),(n=(r=t==null?void 0:t.body)==null?void 0:r.focus)==null||n.call(r),(i=(o=t==null?void 0:t.documentElement)==null?void 0:o.focus)==null||i.call(o),(c=s.requestAnimationFrame)==null||c.call(s,()=>{var d,p;try{s.focus(),(p=(d=t==null?void 0:t.body)==null?void 0:d.focus)==null||p.call(d)}catch{}})}catch{}}function sr(t,s){t.classList.remove(en.className,tn.className),t.classList.add(s==="light"?en.className:tn.className)}function Da(t){return t?Array.from(new Set(t.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 Zu(t){const[,s]=a.useState(0);a.useEffect(()=>{const r=()=>s(o=>o+1),n=[t.api.onDidActiveGroupChange(r),t.api.onDidTitleChange(r),t.api.onDidGroupChange(r),t.containerApi.onDidActivePanelChange(r)];return()=>{for(const o of n)o.dispose()}},[t.api,t.containerApi])}function Qu(t,s,r){var d;const n=[s];let o;for(const p of n){let f;for(const m of p){const h=t.addPanel({id:m.tabKey,component:"conversation",title:lr(m),params:{kind:"conversation",tabKey:m.tabKey},...f?{position:{referencePanel:f,direction:"within"},inactive:!0}:o?{position:{referencePanel:o,direction:"right"},inactive:!0}:{}});f||(f=h.id)}o=f??o}const i=r??((d=s[0])==null?void 0:d.tabKey)??null;if(!i)return;const c=t.getPanel(i);c&&c.group.model.openPanel(c)}function Ea(t,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...t.panels])Wt(n.id)||r.has(n.id)||t.removePanel(n);for(const n of s){const o=t.getPanel(n.tabKey);if(o){o.update({params:{tabKey:n.tabKey}}),o.title!==lr(n)&&o.api.setTitle(lr(n));continue}t.addPanel({id:n.tabKey,component:"conversation",title:lr(n),params:{kind:"conversation",tabKey:n.tabKey},...t.activePanel?{position:{referencePanel:t.activePanel.id,direction:"within"},inactive:!0}:t.panels[0]?{position:{referencePanel:t.panels[0].id,direction:"within"},inactive:!0}:{}})}}function $a(t,s,r){var p,f;const n=r?Ju(r):null;for(const m of[...t.panels])Wt(m.id)&&(!n||m.id!==n)&&t.removePanel(m);if(!r||!n)return;const o=Dt(s,r);if(!o&&t.totalPanels===0)return;const i=t.getPanel(n),c=Co(o);if(i){i.title!==c&&i.api.setTitle(c);return}const d=(o==null?void 0:o.tabKey)??((p=t.activePanel)==null?void 0:p.id)??((f=t.panels.find(m=>!Wt(m.id)))==null?void 0:f.id);t.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...d?{position:{referencePanel:d,direction:"right"},inactive:!0}:{}})}function ep({params:t,api:s}){var h;const r=Mr(),n=a.useRef(null),[o,i]=a.useState(s.isActive),c=r.conversationsByTabKey.get(t.tabKey),d=Sr({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});a.useEffect(()=>{i(s.isActive);const w=[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 w)S.dispose()}},[s]);const p=a.useMemo(()=>c?r.ides.find(w=>w.id===c.routeId):void 0,[r.ides,c]),f=a.useMemo(()=>c?r.actionLogs.filter(w=>w.routeId===c.tabKey):[],[r.actionLogs,c]);if(!c)return e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:e.jsx(Dn,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,detectedIdes:r.detectedIdes,handleLaunchIde:r.handleLaunchIde})});const m=!Ve(c)&&hs(c)==="terminal";return e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:e.jsx(Ln,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:m,ideEntry:p,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:((h=r.scrollToBottomRequest)==null?void 0:h.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:o})})}function tp({params:t}){var p;const s=Mr(),r=a.useMemo(()=>Dt([...s.conversationsByTabKey.values()],t.routeId),[s.conversationsByTabKey,t.routeId]),n=a.useMemo(()=>s.ides.find(f=>f.id===t.routeId),[s.ides,t.routeId]),o=(r==null?void 0:r.daemonId)||((p=r==null?void 0:r.routeId)==null?void 0:p.split(":")[0])||t.routeId.split(":")[0]||t.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:d}=ni({doId:o,targetSessionId:r?Nn(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?e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:e.jsx(lo,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:c,transportType:r.transport,onAction:d})}):e.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 sp(){const t=Mr();return e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:e.jsx(Dn,{conversationsCount:0,isSplitMode:!1,isStandalone:t.isStandalone,hasRegisteredMachines:t.hasRegisteredMachines,detectedIdes:t.detectedIdes,handleLaunchIde:t.handleLaunchIde})})}function rp(t){var S,I;Zu(t);const s=Mr(),r=a.useCallback(u=>{"button"in u&&u.button!==0||t.api.setActive()},[t.api]);if(t.params.kind==="remote"){const u=Dt([...s.conversationsByTabKey.values()],t.params.routeId),b=((S=t.api.group.activePanel)==null?void 0:S.id)===t.api.id,v=t.api.isGroupActive;return e.jsxs("div",{className:`adhdev-dockview-tab${b?" is-active":""}${v?" is-group-active":""}`,title:t.api.title||"Remote","data-tab-key":(u==null?void 0:u.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[e.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:e.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),e.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[e.jsx("div",{className:"adhdev-dockview-tab-primary",children:t.api.title||"Remote"}),e.jsx("div",{className:"adhdev-dockview-tab-meta",children:u!=null&&u.machineName?e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"Live remote view"}),e.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),e.jsx("span",{className:"adhdev-dockview-tab-machine",children:u.machineName})]}):e.jsx("span",{children:"Live remote view"})})]})]})}const n=s.conversationsByTabKey.get(t.params.tabKey);if(!n)return e.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":t.params.tabKey||"",children:e.jsx("div",{className:"adhdev-dockview-tab-copy",children:e.jsx("div",{className:"adhdev-dockview-tab-primary",children:t.api.title||t.params.tabKey})})});const o=((I=t.api.group.activePanel)==null?void 0:I.id)===t.api.id,i=t.api.isGroupActive,c=Es(n,s.liveSessionInboxState,{isOpenConversation:o}),d=c.isReconnecting,p=c.isConnecting,f=c.isGenerating,m=c.isWaiting,h=c.unread,w=s.tabShortcuts[n.tabKey];return e.jsxs("div",{className:`adhdev-dockview-tab${o?" is-active":""}${i?" is-group-active":""}${d?" is-reconnecting":""}`,title:Qe(n),"data-tab-key":t.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:u=>{var b;u.preventDefault(),r(u),s.openTabContextMenu({x:u.clientX,y:u.clientY,tabKey:n.tabKey,sourceDocument:((b=u.target)==null?void 0:b.ownerDocument)??document})},children:[h&&e.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),e.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:f?e.jsx("div",{className:"tab-spinner"}):m?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):d?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):p?e.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):e.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),e.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[e.jsx("div",{className:"adhdev-dockview-tab-primary",children:Qe(n)}),e.jsx("div",{className:"adhdev-dockview-tab-meta",children:d?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Yt(n)}):p?e.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Yt(n)}):e.jsx("span",{children:Yt(n)})})]}),w&&e.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:w,children:w})]})}function np({visibleConversations:t,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:d,hasRegisteredMachines:p,initialDataLoaded:f,userName:m,detectedIdes:h,handleLaunchIde:w,toggleHiddenTab:S,actionShortcuts:I,registerActionHandlers:u,onActiveTabChange:b,requestedActiveTabKey:v,requestedRemoteIdeId:l,onRequestedActiveTabConsumed:N,scrollToBottomRequest:A}){var wt,bt,Tt;const{theme:k}=Mn(),{sendCommand:x}=St(),g=a.useRef(null),y=a.useRef(null),j=a.useRef(!1),E=a.useRef(!1),R=a.useRef(!1),K=a.useRef(null),D=a.useRef([]),[V,_]=a.useState(null),[C,T]=a.useState(!1),[z,L]=a.useState(!1),[$,H]=a.useState(0),se=a.useRef(null),Y=a.useMemo(()=>qo(typeof window<"u"?window.innerWidth:1280),[]),ie=a.useRef(typeof window>"u"?{}:lu(Y)),je=a.useMemo(()=>new Map(t.map(B=>[B.tabKey,B])),[t]),G=a.useMemo(()=>Ws(r),[r]),oe=a.useCallback(()=>{var B;(B=g.current)==null||B.focus()},[]),W=a.useCallback(B=>{const U=document,q=B.document;for(const Z of U.querySelectorAll('link[rel="stylesheet"]')){const Ie=q.createElement("link");Ie.rel="stylesheet",Ie.href=Z.href,Z.crossOrigin&&(Ie.crossOrigin=Z.crossOrigin),q.head.appendChild(Ie)}for(const Z of U.querySelectorAll("style")){const Ie=q.createElement("style");Ie.textContent=Z.textContent,q.head.appendChild(Ie)}const O=[];for(const Z of U.styleSheets)try{for(const Ie of Z.cssRules)Ie instanceof CSSStyleRule&&(Ie.selectorText===":root"||Ie.selectorText==="html")&&O.push(Ie.cssText)}catch{}if(O.length>0){const Z=q.createElement("style");Z.textContent=O.join(`
43
43
  `),q.head.appendChild(Z)}const de=U.documentElement.getAttribute("data-theme");de&&q.documentElement.setAttribute("data-theme",de),q.documentElement.style.colorScheme=de==="light"?"light":"dark",q.body.className=U.body.className;const Se=U.documentElement.getAttribute("style");Se&&q.documentElement.setAttribute("style",Se);const Ae=q.getElementById("dv-popout-window");Ae instanceof HTMLElement&&(Ae.classList.add("adhdev-dockview"),sr(Ae,k))},[k]),be=a.useCallback(()=>{var U;const B=g.current;if(B)for(const q of B.groups)try{const O=(U=q.element)==null?void 0:U.ownerDocument;if(!O||O===document)continue;const de=O.getElementById("dv-popout-window");de instanceof HTMLElement&&(de.classList.add("adhdev-dockview"),sr(de,k));const Se=document.documentElement.getAttribute("data-theme");Se&&O.documentElement.setAttribute("data-theme",Se),O.documentElement.style.colorScheme=Se==="light"?"light":"dark",O.body.className=document.body.className;const Ae=document.documentElement.getAttribute("style");Ae?O.documentElement.setAttribute("style",Ae):O.documentElement.removeAttribute("style")}catch{}},[k]),X=a.useCallback(()=>{var U;const B=g.current;if(B)for(const q of B.groups)try{const O=(U=q.element)==null?void 0:U.ownerDocument;if(!O||O===document)continue;const de=O.getElementById("dv-popout-window");if(!(de instanceof HTMLElement))continue;de.classList.add("adhdev-dockview"),sr(de,k),de.classList.toggle("is-showing-dockview-overlay",z),de.classList.toggle("is-dragging-dockview",C)}catch{}},[C,z,k]),ue=a.useCallback(B=>{const U=g.current;if(!U)return;const q=U.getPanel(B);q&&U.addPopoutGroup(q,{popoutUrl:"/popout.html",onDidOpen:({window:O})=>{W(O),we();const de=je.get(B);O.document.title=de?`${Qe(de)} — ADHDev`:"ADHDev — Popout"}})},[je,W]),te=a.useCallback(B=>{const U=g.current,q=U==null?void 0:U.getPanel(B);if(!U||!q)return;const O=U.groups.filter(de=>{var Se;try{return((Se=de.element)==null?void 0:Se.ownerDocument)===document}catch{return!0}});O.length>0?q.api.moveTo({group:O[0],position:"center"}):q.api.moveTo({position:"center"}),q.api.setActive()},[]),ae=a.useCallback(B=>{var O;const U=g.current;if(!U)return!1;const q=U.getPanel(B);if(!q)return!1;try{return((O=q.group.element)==null?void 0:O.ownerDocument)!==document}catch{return!1}},[]),fe=a.useCallback(B=>{ae(B)&&te(B),S(B)},[ae,te,S]),le=a.useCallback(B=>{const U=g.current,q=U==null?void 0:U.getPanel(B);!U||!q||U.addFloatingGroup(q,{width:600,height:500})},[]),he=a.useCallback(B=>{var q;const U=(q=g.current)==null?void 0:q.getPanel(B);if(!U)return!1;try{return U.group.model.location.type==="floating"}catch{return!1}},[]),J=a.useCallback(()=>{var U,q;const B=(q=(U=g.current)==null?void 0:U.activePanel)==null?void 0:q.id;return!B||Wt(B)?null:je.has(B)?B:null},[je]),pe=a.useCallback(B=>{const U=g.current,q=U==null?void 0:U.getPanel(B);if(!U||!q)return;const O=U.groups.filter(de=>{try{return de.model.location.type==="grid"}catch{return!0}});O.length>0?q.api.moveTo({group:O[0],position:"center"}):q.api.moveTo({position:"center"}),q.api.setActive()},[]),ne=a.useCallback(()=>{var Se;const B=g.current;if(!B)return;const q=B.groups.filter(Ae=>{var Z;try{return((Z=Ae.element)==null?void 0:Z.ownerDocument)===document&&Ae.model.location.type==="grid"}catch{return!1}})[0]||null,O=[...B.panels];for(const Ae of O){const Z=(Se=Ae.group.element)==null?void 0:Se.ownerDocument,Ie=Ae.group.model.location.type;Z===document&&Ie==="grid"||(q&&q.id!==Ae.group.id?Ae.api.moveTo({group:q,position:"center"}):Ae.api.moveTo({position:"center"}))}const de=B.activePanel;de&&(de.group.model.openPanel(de),de.api.setActive()),Fr(document)},[]),we=a.useCallback(()=>{var U,q;const B=g.current;if(B)for(const O of B.groups){const de=(U=O.element)==null?void 0:U.ownerDocument;if(!de||de===document)continue;const Se=de.getElementById("dv-popout-window");if(!(Se instanceof HTMLElement))continue;let Ae=null,Z=de.title||"ADHDev",Ie="Popout workspace";const De=O.activePanel;if(De)if(Ae=De.id,Wt(De.id)){const re=((q=De.params)==null?void 0:q.routeId)||De.id.slice(7),ce=Dt([...je.values()],re);Z=Co(ce),Ie=ce!=null&&ce.machineName?`Remote view · ${ce.machineName}`:"Remote view"}else{const re=je.get(De.id);Z=re?Qe(re):De.title||De.id,Ie=re?Yt(re):"Dockview panel"}de.title=`${Z} — ADHDev`;let Ue=de.getElementById("adhdev-popout-header");Ue instanceof HTMLElement||(Ue=de.createElement("div"),Ue.id="adhdev-popout-header",de.body.appendChild(Ue)),Ue.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(";")),Ue.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 $=await r(
63
63
  ✅ Auto-fix completed!`]),v.current&&clearInterval(v.current))}catch{}},3e3)},[t,s.type,r,o]),x=async()=>{if(p.length!==0){i("running"),S(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${p.join(", ")}`,m?`💬 Comment: ${m}`:"",""]),u("");try{const y=await r(t,"provider_auto_fix",{providerType:s.type,functions:p,agent:c,...m?{comment:m}:{}});y!=null&&y.success&&(y!=null&&y.started||y!=null&&y.running)?(S(j=>[...j,"✅ Agent started. Monitoring progress..."]),k()):(i("error"),u((y==null?void 0:y.error)||"Failed to start auto-fix"))}catch(y){i("error"),u((y==null?void 0:y.message)||"Connection failed")}}},g=async()=>{try{await r(t,"provider_auto_fix_cancel",{providerType:s.type}),S(y=>[...y,`
64
64
  ⚠️ Auto-fix cancelled.`]),i("done"),v.current&&clearInterval(v.current)}catch{}};return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",onClick:n,children:e.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:y=>y.stopPropagation(),children:[e.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"text-lg",children:s.icon||"🔧"}),e.jsxs("div",{children:[e.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",s.displayName]}),e.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),e.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[o==="config"&&e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),e.jsx("div",{className:"flex gap-2",children:Rp.map(y=>e.jsxs("button",{onClick:()=>d(y.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===y.value?y.color+"66":"var(--border-subtle)",background:c===y.value?y.color+"0d":"transparent"},children:[e.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===y.value?y.color:"var(--text-primary)"},children:y.label}),e.jsx("div",{className:"text-[10px] text-text-muted",children:y.desc})]},y.value))})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("button",{onClick:N,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),e.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),e.jsx("button",{onClick:A,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Oa.map(y=>e.jsxs("button",{onClick:()=>l(y),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:p.includes(y)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:p.includes(y)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:p.includes(y)?"#a78bfa":"var(--text-secondary)"},children:[p.includes(y)?"☑ ":"☐ ",y]},y))})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",e.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),e.jsx("textarea",{value:m,onChange:y=>h(y.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")&&e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),e.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:[w.map((y,j)=>e.jsx("div",{className:y.startsWith("✅")?"text-green-400":"",style:y.startsWith("❌")||y.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:y},j)),o==="running"&&e.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),e.jsx("div",{ref:b})]}),I&&e.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:I})]})]}),e.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[e.jsxs("div",{className:"text-[10px] text-text-muted",children:[o==="config"&&p.length>0&&`${p.length} script(s) selected`,o==="running"&&"Agent is generating...",o==="done"&&"Run `adhdev provider verify` to validate"]}),e.jsxs("div",{className:"flex gap-2",children:[o==="config"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),e.jsx("button",{onClick:x,disabled:p.length===0,className:"machine-btn",style:{background:p.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:p.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:p.length>0?"#a78bfa":void 0,opacity:p.length===0?.4:1},children:"🚀 Start Fix"})]}),o==="running"&&e.jsx("button",{onClick:g,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(o==="done"||o==="error")&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>{i("config"),S([]),u("")},className:"machine-btn",children:"← Back"}),e.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Ep({machineId:t,providers:s,sendDaemonCommand:r,onClose:n,onCreated:o}){var k;const i=s.filter(x=>x.category==="ide"),[c,d]=a.useState(((k=i[0])==null?void 0:k.type)||""),[p,f]=a.useState(""),[m,h]=a.useState(""),[w,S]=a.useState(!1),[I,u]=a.useState(""),[b,v]=a.useState(!1),l=x=>{const g=x.toLowerCase().replace(/[^a-z0-9-]/g,"");f(g),(!m||m===N(p))&&h(N(g))},N=x=>x.split("-").map(g=>g.charAt(0).toUpperCase()+g.slice(1)).join(" "),A=async()=>{if(!(!p||!m||!c)){S(!0),u("");try{const x=await r(t,"provider_clone",{type:p,name:m,category:"ide",location:"user",cloneFrom:c});x!=null&&x.success||x!=null&&x.created?(v(!0),o==null||o(p)):u((x==null?void 0:x.error)||"Failed to create provider")}catch(x){u((x==null?void 0:x.message)||"Connection failed")}S(!1)}};return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",onClick:n,children:e.jsxs("div",{className:"w-full max-w-[480px] rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:x=>x.stopPropagation(),children:[e.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[e.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),e.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),e.jsx("div",{className:"px-5 py-4 flex flex-col gap-4",children:b?e.jsxs("div",{className:"text-center py-6",children:[e.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),e.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),e.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[e.jsx("code",{className:"text-violet-400",children:p})," has been created at ",e.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",p,"/"]})]}),e.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",e.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",p]})," or use Auto-Fix to implement scripts."]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:i.map(x=>e.jsxs("button",{onClick:()=>d(x.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===x.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===x.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[e.jsx("div",{className:"text-lg",children:x.icon}),e.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===x.type?"#a78bfa":"var(--text-secondary)"},children:x.displayName})]},x.type))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),e.jsx("input",{value:p,onChange:x=>l(x.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"}),e.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",e.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",p||"...","/"]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),e.jsx("input",{value:m,onChange:x=>h(x.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"})]}),I&&e.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:I})]})}),e.jsx("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-end gap-2",children:b?e.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),e.jsx("button",{onClick:A,disabled:!p||!m||w,className:"machine-btn",style:{background:p&&m?"rgba(34,197,94,0.12)":void 0,borderColor:p&&m?"rgba(34,197,94,0.3)":void 0,color:p&&m?"#86efac":void 0,opacity:!p||!m||w?.4:1},children:w?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function $p({machineId:t,providers:s,sendDaemonCommand:r}){const[n,o]=a.useState([]),[i,c]=a.useState(!1),[d,p]=a.useState(null),[f,m]=a.useState("all"),[h,w]=a.useState(null),[S,I]=a.useState(!1),u=a.useCallback(async()=>{if(t){c(!0);try{const v=await r(t,"get_provider_settings",{}),l=Pp(v);if(l){const N=Lp(l,s);N.sort((A,k)=>A.category.localeCompare(k.category)||A.displayName.localeCompare(k.displayName)),o(N)}}catch{}c(!1)}},[t,s,r]);a.useEffect(()=>{n.length===0&&u()},[]);const b=async(v,l,N)=>{p(`${v}.${l}`),o(A=>A.map(k=>k.type===v?{...k,values:{...k.values,[l]:N}}:k));try{const A=await r(t,"set_provider_setting",{providerType:v,key:l,value:N});A!=null&&A.success||u()}catch{u()}p(null)};return e.jsxs("div",{children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsxs("div",{className:"flex gap-1 items-center",children:[e.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(v=>e.jsx("button",{onClick:()=>m(v),className:`machine-btn text-[10px] px-2 py-0.5 ${f===v?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:v.toUpperCase()},v))]}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("button",{onClick:()=>I(!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"}),e.jsx("button",{onClick:u,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),f!=="all"&&n.filter(v=>v.category===f).length>1&&(()=>{const v=n.filter(k=>k.category===f),l=new Map;for(const k of v)for(const x of k.schema){if(x.type!=="boolean")continue;const g=l.get(x.key),y=!!(k.values[x.key]??x.default);g?(g.onCount+=y?1:0,g.total+=1):l.set(x.key,{label:x.label||x.key,onCount:y?1:0,total:1})}const N=[...l.entries()].filter(([,k])=>k.total===v.length);if(N.length===0)return null;const A=async(k,x)=>{for(const g of v)await b(g.type,k,x)};return e.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[e.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",f.toUpperCase()," providers (",v.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:N.map(([k,x])=>{const g=x.onCount===x.total,y=x.onCount===0;return e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[e.jsx("span",{className:"text-text-secondary font-medium",children:x.label}),e.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",x.onCount,"/",x.total,")"]}),e.jsx("button",{onClick:()=>void A(k,!0),disabled:g,className:`machine-btn text-[9px] px-1.5 py-px ${g?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),e.jsx("button",{onClick:()=>void A(k,!1),disabled:y,className:`machine-btn text-[9px] px-1.5 py-px ${y?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},k)})})]})})(),i&&n.length===0?e.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):e.jsx("div",{className:"flex flex-col gap-2",children:n.filter(v=>f==="all"||v.category===f).map(v=>e.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[e.jsx("span",{className:"text-lg",children:v.icon}),e.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:v.displayName}),e.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:v.category==="acp"?"rgba(139,92,246,0.08)":v.category==="cli"?"rgba(59,130,246,0.08)":v.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:v.category==="acp"?"#a78bfa":v.category==="cli"?"#60a5fa":v.category==="ide"?"#86efac":"var(--status-warning)"},children:v.category}),v.category==="ide"&&e.jsx("button",{onClick:()=>w(s.find(l=>l.type===v.type)||{type:v.type,name:v.displayName,displayName:v.displayName,icon:v.icon,category:v.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"})]}),e.jsx("div",{className:"flex flex-col gap-2",children:v.schema.map(l=>e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"text-xs font-medium text-text-primary",children:[l.label||l.key,d===`${v.type}.${l.key}`&&e.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),l.description&&e.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:l.description})]}),e.jsx("div",{className:"shrink-0",children:l.type==="boolean"?e.jsx("button",{onClick:()=>b(v.type,l.key,!(v.values[l.key]??l.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:v.values[l.key]??l.default?"#8b5cf6":"var(--border-subtle)"},children:e.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:v.values[l.key]??l.default?21:3}})}):l.type==="number"?e.jsx("input",{type:"number",value:Number(v.values[l.key]??l.default??0)||0,min:l.min,max:l.max,onChange:N=>{const A=parseInt(N.target.value)||0;l.min!==void 0&&A<l.min||l.max!==void 0&&A>l.max||b(v.type,l.key,A)},className:"machine-input w-20 text-center text-[11px]"}):l.type==="select"&&l.options?e.jsx("select",{value:String(v.values[l.key]??l.default??""),onChange:N=>b(v.type,l.key,N.target.value),className:"machine-input text-[11px]",children:l.options.map(N=>e.jsx("option",{value:N,children:N},N))}):e.jsx("input",{type:"text",value:String(v.values[l.key]??l.default??""),onBlur:N=>b(v.type,l.key,N.target.value),className:"machine-input w-[120px] text-[11px]"})})]},l.key))})]},v.type))}),h&&e.jsx(Dp,{machineId:t,provider:h,sendDaemonCommand:r,onClose:()=>w(null)}),S&&e.jsx(Ep,{machineId:t,providers:s,sendDaemonCommand:r,onClose:()=>I(!1),onCreated:()=>{I(!1),u()}})]})}function Ha(t){if(!t||Object.keys(t).length===0)return"";try{const s=JSON.stringify(t);return s.length>220?`${s.slice(0,220)}…`:s}catch{return"[unserializable payload]"}}function Bp({machineId:t,sendDaemonCommand:s}){const[r,n]=a.useState([]),[o,i]=a.useState([]),[c,d]=a.useState([]),[p,f]=a.useState(0),[m,h]=a.useState(0),[w,S]=a.useState(!0),[I,u]=a.useState("debug"),b=a.useRef(null),v=a.useRef(!1);return a.useEffect(()=>{if(!t||!w)return;const l=async()=>{try{const[A,k]=await Promise.all([s(t,"get_logs",{count:200,minLevel:I,since:p}),s(t,"get_debug_trace",{count:120,since:m})]),x=(A==null?void 0:A.result)||A;if(A!=null&&A.success&&Array.isArray(x==null?void 0:x.logs)&&x.logs.length>0){n(j=>[...j,...x.logs.map(R=>({timestamp:R.ts,level:R.level,message:`[${R.category}] ${R.message}`}))].slice(-300));const y=Math.max(...x.logs.map(j=>j.ts));f(y)}const g=(k==null?void 0:k.result)||k;if(k!=null&&k.success&&Array.isArray(g==null?void 0:g.trace)){i(g.trace.slice(-120));const y=g.trace.reduce((j,E)=>Math.max(j,Number(E.ts||0)),m);y>m&&h(y)}}catch{}d(Qt.list({limit:120}))};l();const N=setInterval(l,3e3);return()=>clearInterval(N)},[t,w,p,m,I,s]),a.useEffect(()=>{if(w&&(r.length>0||o.length>0||c.length>0)){const l=v.current?"smooth":"instant";setTimeout(()=>{var N;(N=b.current)==null||N.scrollIntoView({behavior:l}),v.current=!0},50)}},[r.length,o.length,c.length,w]),e.jsxs("div",{children:[e.jsxs("div",{className:"flex justify-between items-center mb-3",children:[e.jsxs("div",{className:"flex gap-1 items-center",children:[e.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Level"}),["debug","info","warn","error"].map(l=>e.jsx("button",{onClick:()=>{u(l),n([]),f(0)},className:`machine-btn text-[10px] px-2 py-0.5 ${I===l?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:l.toUpperCase()},l))]}),e.jsxs("div",{className:"flex gap-1.5 items-center",children:[e.jsxs("span",{className:"text-[10px] text-text-muted",children:["logs=",r.length," trace=",o.length," web=",c.length]}),e.jsx("button",{onClick:()=>S(!w),className:`machine-btn ${w?"text-green-500 border-green-500/30":""}`,children:w?"⏸ Pause":"▶ Resume"}),e.jsx("button",{onClick:()=>{n([]),i([]),d([]),f(0),h(0),Qt.clear()},className:"machine-btn",children:"Clear"})]})]}),e.jsxs("div",{className:"grid gap-3",children:[e.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:[e.jsx("div",{className:"mb-2 text-[10px] uppercase tracking-wider text-text-muted",children:"Daemon logs"}),r.length===0&&e.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs..."}),r.map((l,N)=>e.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:[e.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(l.timestamp).toLocaleTimeString()}),e.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"}),e.jsx("span",{children:l.message})]},`log-${N}`))]}),e.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:[e.jsx("div",{className:"mb-2 text-[10px] uppercase tracking-wider text-text-muted",children:"Structured daemon trace"}),o.length===0&&e.jsx("div",{className:"p-6 text-center text-text-muted",children:"No trace entries yet. Run daemon with --dev or --trace."}),o.map(l=>e.jsxs("div",{className:"py-1 border-b border-white/5 last:border-b-0",children:[e.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted",children:[e.jsx("span",{children:new Date(l.ts).toLocaleTimeString()}),e.jsx("span",{children:l.level.toUpperCase()}),e.jsxs("span",{children:[l.category,".",l.stage]}),l.interactionId&&e.jsxs("span",{children:["ix=",l.interactionId]})]}),e.jsx("div",{children:Ha(l.payload)})]},l.id))]}),e.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:[e.jsx("div",{className:"mb-2 text-[10px] uppercase tracking-wider text-text-muted",children:"Browser debug events"}),c.length===0&&e.jsx("div",{className:"p-6 text-center text-text-muted",children:"No browser debug events captured yet."}),c.map(l=>e.jsxs("div",{className:"py-1 border-b border-white/5 last:border-b-0",children:[e.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted",children:[e.jsx("span",{children:new Date(l.ts).toLocaleTimeString()}),e.jsx("span",{children:l.kind}),l.topic&&e.jsxs("span",{children:["topic=",l.topic]}),l.interactionId&&e.jsxs("span",{children:["ix=",l.interactionId]})]}),e.jsx("div",{children:Ha(l.payload)})]},l.id))]})]}),e.jsx("div",{ref:b})]})}function Yr(t){return t!=null&&t.result&&typeof t.result=="object"&&"success"in t.result?t.result:t}function Xr(t){return t?new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Ua(t){if(!t)return"unknown";const s=Date.now()-t,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 Kp(t){return t?t.ownerType==="user"?`user control · ${t.clientId}`:`agent control · ${t.clientId}`:"view only"}function Wp(t){const s=typeof(t==null?void 0:t.runtimeRecoveryState)=="string"?String(t.runtimeRecoveryState):"";return s?s==="auto_resumed"?"restored after restart":s==="resume_failed"?"restore failed":s==="host_restart_interrupted"?"host restart interrupted":s==="orphan_snapshot"?"snapshot recovered":s.replace(/_/g," "):null}function Op(t){switch(t){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(t){var r;const s=new Map;for(const n of t){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 Up({machineId:t,cliSessions:s,sendDaemonCommand:r}){const[n,o]=a.useState(""),[i,c]=a.useState(null),[d,p]=a.useState(!1),f=Fo(t,{enabled:!!t,includeSessions:!0,limit:12,intervalMs:8e3}),m=f.diagnostics,h=f.loading,w=f.applyDiagnostics,S=a.useMemo(()=>new Map(s.map(x=>[x.sessionId||x.id,x])),[s]),I=a.useCallback(async()=>{if(t){p(!0);try{const x=await r(t,"session_host_get_diagnostics",{includeSessions:!0,limit:12}),g=Yr(x);if(!(g!=null&&g.success))throw new Error((g==null?void 0:g.error)||"Could not load session host diagnostics");w(g.diagnostics||g.result||null),o("")}catch(x){const g=x instanceof Error?x.message:"Could not load session host diagnostics";o(g)}finally{p(!1)}}},[w,t,r]);a.useEffect(()=>{!t||m||h||d||I()},[m,h,t,I,d]);const u=a.useCallback(async(x,g)=>{const y=`${x}:${g.sessionId}`;if(!(x==="session_host_stop_session"&&!window.confirm(`Stop ${g.displayName}?
65
65
  This will terminate the hosted runtime.`))){c(y);try{const j=await r(t,x,{sessionId:g.sessionId}),E=Yr(j);if(!(E!=null&&E.success))throw new Error((E==null?void 0:E.error)||"Session host action failed");const R=x==="session_host_resume_session"?"resumed":x==="session_host_restart_session"?"restarted":"stopped";ht.showToast(`Session host ${R}: ${g.displayName}`,"success"),await I()}catch(j){const E=j instanceof Error?j.message:"Session host action failed";ht.showToast(E,"warning"),o(E)}finally{c(j=>j===y?null:j)}}},[t,I,r]),b=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 g=await r(t,"session_host_prune_duplicate_sessions",{}),y=Yr(g);if(!(y!=null&&y.success))throw new Error((y==null?void 0:y.error)||"Duplicate prune failed");const j=y.result||{},E=Array.isArray(j.prunedSessionIds)?j.prunedSessionIds.length:0,R=typeof j.duplicateGroupCount=="number"?j.duplicateGroupCount:0;ht.showToast(`Pruned ${E} duplicate runtime(s) across ${R} group(s)`,"success"),await I()}catch(g){const y=g instanceof Error?g.message:"Duplicate prune failed";ht.showToast(y,"warning"),o(y)}finally{c(g=>g==="session_host_prune_duplicate_sessions"?null:g)}}},[t,I,r]),v=a.useMemo(()=>[...(m==null?void 0:m.sessions)||[]].sort((x,g)=>(g.lastActivityAt||0)-(x.lastActivityAt||0)),[m==null?void 0:m.sessions]),l=a.useMemo(()=>Hp(v),[v]),N=a.useMemo(()=>v.reduce((x,g)=>{var y;return x+(((y=g.attachedClients)==null?void 0:y.length)||0)},0),[v]),A=a.useMemo(()=>[...(m==null?void 0:m.recentTransitions)||[]].slice(-6).reverse(),[m==null?void 0:m.recentTransitions]),k=a.useMemo(()=>[...(m==null?void 0:m.recentLogs)||[]].reverse().find(x=>x.level==="warn"||x.level==="error")||null,[m==null?void 0:m.recentLogs]);return e.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[e.jsx(Ut,{size:14})," Session Host"]}),e.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:"Hosted CLI runtime diagnostics and recovery controls."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[l>0&&e.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{b()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${l})`}),e.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${m?"bg-green-500/[0.08] text-green-500":"bg-amber-500/[0.08] text-amber-400"}`,children:m?"Managed":"Unavailable"}),e.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{I()},disabled:h||d,children:[e.jsx(gs,{size:13}),h||d?"Refreshing…":"Refresh"]})]})]}),n&&!m&&e.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:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ts,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-amber-100",children:"Session host diagnostics unavailable"}),e.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),m&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Runtimes"}),e.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:m.runtimeCount})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Clients"}),e.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:N})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),e.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:m.recentRequests.length})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),e.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:Ua(m.hostStartedAt)}),e.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Xr(m.hostStartedAt)})]})]}),k&&e.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:[e.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[e.jsx(ts,{size:13})," Latest host warning"]}),e.jsx("div",{className:"text-text-primary leading-relaxed",children:k.message}),e.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Xr(k.timestamp),k.sessionId?` · ${k.sessionId}`:""]})]}),e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[e.jsx(wr,{size:14})," Hosted Runtimes"]}),v.length===0?e.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No hosted runtimes on this machine yet."}):e.jsx("div",{className:"space-y-2",children:v.map(x=>{var D;const g=i===`session_host_resume_session:${x.sessionId}`,y=i===`session_host_restart_session:${x.sessionId}`,j=i===`session_host_stop_session:${x.sessionId}`,E=Wp(x.meta),R=S.get(x.sessionId),K=x.attachedClients.length===1?"1 client":`${x.attachedClients.length} clients`;return e.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:x.displayName||(R==null?void 0:R.cliName)||x.providerType}),e.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Op(x.lifecycle)}`,children:x.lifecycle}),E&&e.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:E})]}),e.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[e.jsx("span",{className:"text-text-primary/90",children:x.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||x.workspace||"No workspace"}),e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsx("span",{className:"font-mono text-text-primary",children:x.runtimeKey}),x.osPid?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsxs("span",{className:"text-text-primary/90",children:["pid ",x.osPid]})]}):null]}),e.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[e.jsx("span",{className:((D=x.writeOwner)==null?void 0:D.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Kp(x.writeOwner)}),e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[e.jsx(hn,{size:11})," ",K]}),e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsxs("span",{className:"text-text-primary/85",children:["active ",Ua(x.lastActivityAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[(x.lifecycle==="interrupted"||x.lifecycle==="failed"||x.lifecycle==="stopped")&&e.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{u("session_host_resume_session",x)},children:g?"Resuming…":"Resume"}),e.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{u("session_host_restart_session",x)},children:y?"Restarting…":"Restart"}),(x.lifecycle==="running"||x.lifecycle==="starting"||x.lifecycle==="interrupted")&&e.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",x)},children:j?"Stopping…":"Stop"})]})]})},x.sessionId)})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),A.length===0?e.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."}):e.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:A.map(x=>{var y;const g=v.find(j=>j.sessionId===x.sessionId);return e.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-text-primary font-medium",children:(g==null?void 0:g.displayName)||((y=S.get(x.sessionId))==null?void 0:y.cliName)||x.sessionId}),e.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[x.action,x.lifecycle?` · ${x.lifecycle}`:"",x.detail?` · ${x.detail}`:"",x.error?` · ${x.error}`:""]})]}),e.jsx("div",{className:`shrink-0 text-[10px] ${x.success===!1?"text-red-300":"text-text-secondary"}`,children:Xr(x.timestamp)})]},`${x.sessionId}:${x.timestamp}:${x.action}`)})})]}),e.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",e.jsx("span",{className:"font-mono text-text-primary",children:m.endpoint||"unknown"}),n?e.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function zp({machine:t,launchPick:s,actions:r}){const{runLaunchCliCore:n,setLaunchPick:o}=r;return e.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:e.jsxs("div",{className:"w-full max-w-md rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-5",children:[e.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),e.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."}),e.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(t.workspaces||[]).length===0?e.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(t.workspaces||[]).map(i=>e.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:[e.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),e.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!t.defaultWorkspacePath,onClick:()=>{o(null),n({cliType:s.cliType,useDefaultWorkspace:!0,argsStr:s.argsStr,model:s.model})},children:"Default workspace"}),e.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"}),e.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>o(null),children:"Cancel"})]})]})})}function Jr({icon:t,children:s}){return e.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[t,e.jsx("span",{children:s})]})}function Zr({children:t,className:s=""}){return e.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${s}`,children:t})}function Fp({machineEntry:t,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:o,onOpenRecent:i,onOpenConversation:c}){const d=n.slice(0,6),p=r.slice(0,4),m=Ts(t,"0.8.50"),h=w=>w==="ide"?"IDE":w==="cli"?"CLI":"ACP";return e.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&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Jr,{icon:e.jsx(Kt,{size:13}),children:"Current Chats"}),e.jsx(Zr,{children:e.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(w=>{const S=an(w);return e.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(w),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[e.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:Qe(w)}),S>0&&e.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:vn(S)})]}),e.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ns(w)})]},w.tabKey)})})})]}),p.length>0&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Jr,{icon:e.jsx(ao,{size:13}),children:"Recent Launches"}),e.jsx(Zr,{children:e.jsx("div",{className:"flex flex-col gap-1.5",children:p.map(w=>e.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(w),children:[e.jsx("span",{className:"text-sm font-semibold text-text-primary truncate w-full group-hover:text-accent-primary transition-colors",children:w.label}),e.jsxs("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:[h(w.kind),w.subtitle?` · ${w.subtitle}`:""]})]},w.id))})})]}),t.versionMismatch&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Jr,{icon:e.jsx(ts,{size:13}),children:"Daemon Update"}),e.jsx(Zr,{className:"border-amber-500/20 bg-amber-500/5",children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:m?"Daemon update required":"Version mismatch detected"}),e.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:m?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),e.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:[e.jsx(gs,{size:13}),e.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Vp(t){return t?t.ownerType==="user"?"you control":"agent controls":"view only"}const Gp={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 nr(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function qp(t){const s=t instanceof Error?t.message:String(t||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function Qr({category:t,machine:s,machineId:r,providers:n,managedEntries:o,getIcon:i,actions:c,sendDaemonCommand:d,initialWorkspaceId:p,initialWorkspacePath:f}){const m=bs(),{handleLaunchIde:h,handleStopCli:w,handleRestartIde:S,handleStopIde:I,handleDetectIdes:u,launchingIde:b,launchingAgentType:v,addLog:l}=c,[N,A]=a.useState(null),k=a.useCallback(M=>{M&&m({pathname:"/",search:`?activeTab=${encodeURIComponent(M)}`})},[m]),x=Gp[t],g=t==="ide",y=t==="acp",j=a.useMemo(()=>n.filter(M=>M.category===t&&(t==="ide"||M.installed!==!1)),[t,n]),E=a.useMemo(()=>new Map(j.map(M=>[M.type,M.displayName||M.type])),[j]),[R,K]=a.useState(""),[D,V]=a.useState(""),[_,C]=a.useState([]),[T,z]=a.useState(""),[L,$]=a.useState(""),[H,se]=a.useState([]),[Y,ie]=a.useState(!1),[je,G]=a.useState(""),[oe,W]=a.useState(!1),[be,X]=a.useState(null),[ue,te]=a.useState(f?"__custom__":p||s.defaultWorkspaceId||""),[ae,fe]=a.useState(f||""),[le,he]=a.useState([]),[J,pe]=a.useState(!1),[ne,we]=a.useState(""),[ge,P]=a.useState([]),[ye,F]=a.useState(!1),[me,Ce]=a.useState(""),xe=a.useRef(null),[Le,Be]=a.useState(null),Fe=a.useRef("__home__"),[st,ze]=a.useState("__home__"),[dt,gt]=a.useState(!1),Ge=a.useRef(0),at=le.filter(M=>!o.some(ee=>ee.type===M&&xt(ee.status)!=="stopped")),ot=a.useRef({});a.useEffect(()=>{s.defaultWorkspaceId&&!ue&&te(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),a.useEffect(()=>{if(f){te("__custom__"),fe(f);return}p&&(te(p),fe(""))},[p,f]),a.useEffect(()=>{g||R&&(j.some(M=>M.type===R)||(K(""),$("")))},[j,g,R]);const Ke=(()=>{if(ue==="__custom__")return ae.trim();if(!ue)return"";const M=(s.workspaces||[]).find(ee=>ee.id===ue);return(M==null?void 0:M.path)||""})(),ct=a.useCallback(M=>{const ee=ot.current[M];ee&&(clearTimeout(ee),delete ot.current[M]),he(re=>re.includes(M)?re.filter(ce=>ce!==M):re)},[]),ut=a.useRef(new Set),it=a.useCallback(async M=>{if(d){F(!0),Ce("");try{const ee=await Ir(d,r,M);we(ee.path),fe(ee.path),P(ee.directories)}catch(ee){Ce(ee instanceof Error?ee.message:"Could not load folder")}finally{F(!1)}}},[r,d]),Q=a.useCallback(()=>{var ee;if(!d)return;te("__custom__"),pe(!0);const M=Cr(s.platform,[ae.trim(),Ke,s.defaultWorkspacePath,(ee=s.workspaces[0])==null?void 0:ee.path]);it(M)},[ae,it,s.defaultWorkspacePath,s.platform,s.workspaces,Ke,d]),_e=a.useCallback(M=>{const ee=String(M.workspace||"").trim();if(!ee)return;const re=(s.workspaces||[]).find(ce=>nr(ce.path)===nr(ee));if(re){te(re.id),fe("");return}te("__custom__"),fe(ee)},[s.workspaces]),Re=a.useCallback(M=>{const ee=String(M.workspace||"").trim();if(!ee)return{workspaceId:null,workspacePath:"",useHome:!0};const re=(s.workspaces||[]).find(ce=>nr(ce.path)===nr(ee));return re?{workspaceId:re.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:ee,useHome:!1}},[s.workspaces]),We=a.useCallback(async M=>{if(!d||!M||t!=="cli"){se([]),ie(!1),G("");return}const ee=Ge.current+1;Ge.current=ee,ie(!0),G("");try{const re=await d(r,"list_saved_sessions",{providerType:M,kind:"cli",limit:30});if(Ge.current!==ee)return;const ce=(re==null?void 0:re.result)??re;se(Array.isArray(ce==null?void 0:ce.sessions)?ce.sessions:[])}catch(re){if(Ge.current!==ee)return;se([]),G(re instanceof Error?re.message:"Could not load saved sessions")}finally{Ge.current===ee&&ie(!1)}},[t,r,d]),Ct=a.useMemo(()=>{if(t!=="cli"||!R)return null;const M=E.get(R)||R;return{routeId:r,daemonId:r,providerSessionId:L||void 0,transport:"pty",mode:"chat",agentName:M,agentType:R,status:"idle",title:M,messages:[],ideType:R,workspaceName:Ke,displayPrimary:M,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${R}`}},[t,r,E,Ke,L,R]),pt=a.useCallback(M=>{if(t==="ide"||!M){C([]);return}C(pi(r,M))},[t,r]);a.useEffect(()=>{if($(""),pt(R),t!=="cli"||!R){se([]),G(""),ie(!1);return}We(R)},[t,pt,We,R]),a.useEffect(()=>{if(!L)return;const M=H.find(ee=>ee.providerSessionId===L);M!=null&&M.canResume||$("")},[H,L]);const wt=a.useCallback((M,ee)=>{xe.current=ee,Fe.current=M.selectedWorkspaceKey||"__home__",ze(M.selectedWorkspaceKey||"__home__"),Be(M)},[]),bt=a.useCallback(()=>{xe.current&&(gt(!0),xe.current().finally(()=>{xe.current=null,gt(!1),Be(null)}))},[]),Tt=a.useCallback(M=>{if(!M)return;he(re=>re.includes(M)?re:[...re,M]);const ee=ot.current[M];ee&&clearTimeout(ee),ot.current[M]=setTimeout(()=>{he(re=>re.includes(M)?re.filter(ce=>ce!==M):re),delete ot.current[M]},2e4)},[]);a.useEffect(()=>{for(const ee of o)xt(ee.status)!=="stopped"&&(le.includes(ee.type)&&!ut.current.has(ee.type)&&(ut.current.add(ee.type),l("info",`${E.get(ee.type)||ee.type} launched`,!0)),ct(ee.type));const M=new Set(o.filter(ee=>xt(ee.status)!=="stopped").map(ee=>ee.type));ut.current.forEach(ee=>{!le.includes(ee)&&!M.has(ee)&&ut.current.delete(ee)})},[l,ct,o,le,E]),a.useEffect(()=>()=>{Object.values(ot.current).forEach(clearTimeout),ot.current={}},[]);const[B,U]=a.useState({}),[q,O]=a.useState(null);a.useEffect(()=>{if(!g||!r||!d)return;(async()=>{try{const ee=await d(r,"get_ide_extensions",{}),re=(ee==null?void 0:ee.result)||ee;re!=null&&re.success&&(re!=null&&re.ideExtensions)&&U(re.ideExtensions)}catch{}})()},[g,r,d]);const de=M=>g?Ze(M.type):t==="cli"?M.cliName:M.acpName,Se=g?s.detectedIdes||[]:[],Ae=a.useCallback(async M=>{const ee=(M==null?void 0:M.type)||R,re=(M==null?void 0:M.workspacePath)??Ke;if(g){await h(ee,re?{workspace:re}:void 0)&&Tt(ee);return}const ce=await c.runLaunchCliCore({cliType:ee,dir:M!=null&&M.workspaceId?void 0:re||void 0,workspaceId:(M==null?void 0:M.workspaceId)||void 0,useHome:(M==null?void 0:M.useHome)||!(M!=null&&M.workspaceId)&&!re,argsStr:(M==null?void 0:M.argsStr)??(D||void 0),model:(M==null?void 0:M.model)??(y&&T||void 0),resumeSessionId:(M==null?void 0:M.resumeSessionId)||!y&&t==="cli"&&ee===R&&L||void 0});if(ce.success||ce.pending){const Pe=(M==null?void 0:M.argsStr)??D;!g&&(Pe!=null&&Pe.trim())&&(mi(r,ee,Pe),pt(ee)),Tt(ee),ce.success&&ce.sessionId&&k(ce.sessionId)}},[c,h,y,g,D,T,pt,Tt,r,k,Ke,L,R]),Z=()=>{var ce;const M=g?Ze(R):E.get(R)||R,{options:ee,selectedKey:re}=Zt({machine:s,currentWorkspaceId:ue&&ue!=="__custom__"?ue:null,currentWorkspacePath:Ke});wt({title:`Launch ${M}?`,description:"Review the provider and target folder before starting this session.",confirmLabel:"Launch",workspaceOptions:ee,selectedWorkspaceKey:re,details:[{label:"Mode",value:x.label},{label:"Provider",value:M},...!g&&t==="cli"&&L?[{label:"Resume",value:((ce=H.find(Pe=>Pe.providerSessionId===L))==null?void 0:ce.title)||L}]:[],...!g&&D.trim()?[{label:"Arguments",value:D.trim()}]:[],...y&&T.trim()?[{label:"Model",value:T.trim()}]:[]]},async()=>{const Pe=ee.find(Me=>Me.key===Fe.current);Pe!=null&&Pe.workspaceId?(te(Pe.workspaceId),fe("")):Pe!=null&&Pe.workspacePath?(te("__custom__"),fe(Pe.workspacePath)):(te(""),fe("")),await Ae({workspaceId:(Pe==null?void 0:Pe.workspaceId)??null,workspacePath:(Pe==null?void 0:Pe.workspacePath)??"",useHome:!(Pe!=null&&Pe.workspaceId)&&!(Pe!=null&&Pe.workspacePath)})})},Ie=M=>{g?I(M):w(M.type,M.workspace,M.id)},De=a.useCallback(async(M,ee,re=!1)=>{if(M.mode===ee){re&&M.sessionId&&k(M.sessionId);return}if(!d||!M.sessionId){re&&M.sessionId&&k(M.sessionId);return}try{await d(r,"set_cli_view_mode",{targetSessionId:M.sessionId,cliType:M.type,mode:ee}),re&&k(M.sessionId)}catch(ce){qp(ce)?console.warn("Skipped CLI view mode switch:",ce instanceof Error?ce.message:String(ce)):console.error("Failed to switch CLI view mode:",ce)}},[r,k,d]),Ue=e.jsxs("div",{className:"mb-3",children:[e.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[e.jsx("select",{value:ue,onChange:M=>{const ee=M.target.value;if(te(ee),ee==="__custom__"&&d){Q();return}ee!=="__custom__"&&fe("")},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?e.jsxs(e.Fragment,{children:[e.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(s.workspaces||[]).map(M=>e.jsxs("option",{value:M.id,children:[M.id===s.defaultWorkspaceId?"⭐ ":"",kr(M.path,M.label)]},M.id)),e.jsx("option",{value:"__custom__",children:d?"📁 Select workspace…":"✏️ Custom path…"})]}):e.jsxs(e.Fragment,{children:[e.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),e.jsx("option",{value:"__custom__",children:d?"📁 Select workspace…":"✏️ Custom path…"})]})}),ue==="__custom__"&&(d?e.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:Q,children:"Select workspace…"}):e.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:ae,onChange:M=>fe(M.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}))]}),e.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:ue==="__custom__"?Ke?e.jsx("span",{className:"font-mono truncate block",title:Ke,children:Ke}):d?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":Ke?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-medium text-text-secondary",children:ue===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),e.jsx("span",{className:"font-mono truncate block",title:Ke,children:Ke})]}):"No workspace selected. This launches in the home directory."})]});return e.jsxs("div",{children:[e.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${x.accent} relative overflow-hidden`,children:[e.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),e.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",x.label," to Launch"]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:g?Se.length>0?Se.map(M=>{const ee=o.find(Oe=>(Oe.type||"").toLowerCase()===(M.type||"").toLowerCase()&&xt(Oe.status)!=="stopped"),re=M.running||!!ee,ce=!!ee&&ee.cdpConnected,Pe=le.includes(M.type||M.id||""),Me=R===(M.type||"");return e.jsxs("button",{onClick:()=>{if(ce&&ee){const Oe=ee.sessionId;Oe?m(`/dashboard?activeTab=${encodeURIComponent(Oe)}`,{state:{openRemoteForTabKey:Oe}}):m("/dashboard",{state:{openRemoteForTabKey:ee.id}});return}Pe||K(Oe=>Oe===(M.type||"")?"":M.type||"")},disabled:!!b||Pe,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${ce?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Me?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:b&&b!==M.type?.4:1},children:[e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i(M.type)}),re&&e.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${ce?"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"}`})]}),e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:M.name||Ze(M.type)}),e.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ce?"text-green-400":Pe?"text-orange-400":Me?"text-accent-primary":"text-text-muted"}`,children:ce?"Open Session":Pe?"Starting...":Me?"Configure":"Select"})]})]},M.type)}):e.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.",e.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:[e.jsx(oc,{size:14})," Scan System"]})]}):j.length>0?j.map(M=>{const ee=R===M.type,re=le.includes(M.type),Pe=!!o.find(Me=>Me.type===M.type&&xt(Me.status)!=="stopped");return e.jsxs("button",{onClick:()=>K(Me=>Me===M.type?"":M.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${ee?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:M.icon}),Pe&&e.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)]"})]}),e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:M.displayName}),e.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${re?"text-orange-400":ee?"text-accent-primary":"text-text-muted"}`,children:re?"Starting...":ee?"Configure":"Select"})]})]},M.type)}):e.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 ",t.toUpperCase()," providers available.",e.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."})]})}),R&&(g?Se.find(M=>M.type===R):j.find(M=>M.type===R))&&e.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:[e.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[e.jsx("span",{children:"Launch Settings"}),e.jsx("span",{className:"text-accent-primary font-bold",children:g?Ze(R):E.get(R)||R})]}),Ue,!g&&e.jsxs("div",{className:"flex flex-col gap-3",children:[!y&&t==="cli"&&e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Resume from History"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void We(R),disabled:!R||Y,children:Y?"Loading…":"Refresh"}),e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>{R&&(W(!0),We(R))},disabled:!R,children:"Open History"})]})]}),L?(()=>{const M=H.find(ee=>ee.providerSessionId===L);return M?e.jsx("div",{className:"rounded-md border border-[#ffffff1a] bg-bg-primary px-3 py-2 text-[10px] text-text-muted leading-relaxed",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-text-primary text-[11px] font-semibold truncate",children:M.title||M.providerSessionId}),e.jsx("div",{className:"font-mono break-all",children:M.providerSessionId}),e.jsx("div",{children:M.workspace||"Workspace unknown"})]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:()=>$(""),children:"Clear"})]})}):null})():e.jsx("div",{className:"text-[10px] text-text-muted",children:"Start a new CLI session, or choose one from history."}),je&&e.jsx("div",{className:"text-[10px] text-red-400",children:je})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[y&&e.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[e.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),e.jsx("input",{type:"text",placeholder:"Leave empty for default",value:T,onChange:M=>z(M.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"})]}),e.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[e.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),e.jsx("input",{type:"text",placeholder:"Optional flags...",value:D,onChange:M=>V(M.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"}),_.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:_.map(M=>e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>V(M),title:M,children:M},M))})]})]})]}),e.jsx("div",{className:"flex justify-end mt-2",children:e.jsx("button",{onClick:Z,disabled:!!v||!!b||le.includes(R),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:v===R||b===R?"⏳ Launching...":"▶ Launch"})})]})]}),e.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",o.length+le.filter(M=>!o.some(ee=>ee.type===M&&xt(ee.status)!=="stopped")).length,")"]}),o.length===0&&at.length===0?e.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 ",x.plural," running"]}):e.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[at.map(M=>e.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:e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"text-lg",children:i(M)}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:g?Ze(M):E.get(M)||M}),e.jsx("div",{className:"text-[11px] text-text-muted",children:v===M?"Launching process...":"Waiting for process and session to register..."})]})]}),e.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:${M}`)),o.map(M=>{const ee=g?M:null,re=y?M:null,ce=!g&&!y?M:null,Pe=xt(M.status);return e.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[e.jsxs("div",{className:"flex justify-between items-center mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"text-lg",children:i(M.type)}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[de(M),(ee==null?void 0:ee.version)&&e.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",ee.version]})]}),e.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[e.jsx("span",{children:M.workspace||"—"}),(re==null?void 0:re.currentModel)&&e.jsxs("span",{className:"text-cyan-500",children:["🤖 ",re.currentModel]}),(re==null?void 0:re.currentPlan)&&e.jsxs("span",{style:{color:"var(--status-warning)"},children:["📋 ",re.currentPlan]}),(ce==null?void 0:ce.mode)&&e.jsx("span",{className:ce.mode==="chat"?"text-violet-400":"text-text-secondary",children:ce.mode==="chat"?"Chat view":"Terminal view"})]}),ce&&(ce.runtimeKey||ce.runtimeWriteOwner)&&e.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ce.runtimeKey&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),e.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",ce.runtimeKey]}),e.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var Me;(Me=navigator.clipboard)==null||Me.writeText(`adhdev attach ${ce.runtimeKey}`),A(ce.runtimeKey||null),window.setTimeout(()=>{A(Oe=>Oe===ce.runtimeKey?null:Oe)},1200)},children:N===ce.runtimeKey?"Copied":"Copy"})]}),ce.runtimeWriteOwner&&e.jsx("span",{style:{color:ce.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ce.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Vp(ce.runtimeWriteOwner)})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Pe==="stopped"?"bg-red-500/[0.08] text-red-500":Pe==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Pe}),g&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>{const Me=M.sessionId;if(Me){m(`/dashboard?activeTab=${encodeURIComponent(Me)}`,{state:{openRemoteForTabKey:Me}});return}m("/dashboard",{state:{openRemoteForTabKey:M.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:e.jsx(Nt,{size:13})}),e.jsx("button",{onClick:()=>{const Me=M.workspace||"",{options:Oe,selectedKey:rt}=Zt({machine:s,currentWorkspacePath:Me});wt({title:`Restart ${Ze(M.type)}?`,description:"Review or change the target workspace before restarting this IDE.",confirmLabel:"Restart",workspaceOptions:Oe,selectedWorkspaceKey:rt,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:Ze(M.type)}]},async()=>{const Ye=Oe.find(He=>He.key===Fe.current),qe=(Ye==null?void 0:Ye.workspacePath)??"";if(qe&&qe!==Me){await Ae({type:M.type,workspacePath:qe});return}await S(M)})},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:e.jsx(gs,{size:14})})]}),y&&e.jsx("button",{onClick:()=>{const Me=M.sessionId;Me&&k(Me)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"View chat",disabled:!M.sessionId,children:e.jsx(Kt,{size:14})}),ce&&Pe!=="stopped"&&e.jsxs(e.Fragment,{children:[ce.mode&&e.jsx(Sn,{mode:ce.mode,onChange:Me=>void De(ce,Me,!1),compact:!0}),e.jsx("button",{onClick:()=>{const Me=M.sessionId;Me&&k(Me)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"Open current view in dashboard",disabled:!M.sessionId,children:ce.mode==="chat"?e.jsx(Kt,{size:14}):e.jsx(Nt,{size:13})})]}),Pe==="stopped"?e.jsx("button",{onClick:()=>{const Me=M.workspace||"",Oe=g?Ze(M.type):de(M),{options:rt,selectedKey:Ye}=Zt({machine:s,currentWorkspacePath:Me});wt({title:`Launch ${Oe}?`,description:"Review or change the target workspace before launching this stopped session again.",confirmLabel:"Launch",workspaceOptions:rt,selectedWorkspaceKey:Ye,details:[{label:"Mode",value:x.label},{label:"Provider",value:Oe}]},async()=>{const qe=rt.find(He=>He.key===Fe.current);await Ae({type:M.type,workspaceId:(qe==null?void 0:qe.workspaceId)??null,workspacePath:(qe==null?void 0:qe.workspacePath)??"",useHome:!(qe!=null&&qe.workspaceId)&&!(qe!=null&&qe.workspacePath),model:re==null?void 0:re.currentModel})})},disabled:le.includes(M.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:le.includes(M.type)?"⏳":e.jsx(gn,{size:14})}):e.jsx("button",{onClick:()=>Ie(M),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:e.jsx(vt,{size:14})})]})]}),ee&&ee.aiAgents.length>0&&e.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:ee.aiAgents.map(Me=>e.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${mo(Me.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Me.name," · ",xt(Me.status)]},Me.id))}),ee&&(B[ee.type]||[]).length>0&&d&&e.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[e.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:(B[ee.type]||[]).map(Me=>e.jsxs("button",{disabled:q===`${ee.type}.${Me.type}`,onClick:async()=>{const Oe=`${ee.type}.${Me.type}`;O(Oe);try{await d(r,"set_ide_extension",{ideType:ee.type,extensionType:Me.type,enabled:!Me.enabled}),U(rt=>({...rt,[ee.type]:(rt[ee.type]||[]).map(Ye=>Ye.type===Me.type?{...Ye,enabled:!Ye.enabled}:Ye)}))}catch(rt){console.error("Extension toggle failed:",rt)}finally{O(null)}},className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-medium border transition-colors duration-150 cursor-pointer ${Me.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Me.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Me.name,e.jsx("span",{className:"text-[9px] font-normal",children:Me.enabled?"ON":"OFF"})]},Me.type))})]})]},M.id)})]}),J&&d&&e.jsx(Ar,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:ne,directories:ge,busy:ye,error:me,confirmLabel:"Use this folder",onClose:()=>pe(!1),onNavigate:M=>{it(M)},onConfirm:M=>{fe(M),te("__custom__"),pe(!1)}}),Le&&e.jsx(Rn,{title:Le.title,description:Le.description,details:Le.details,workspaceOptions:Le.workspaceOptions,selectedWorkspaceKey:st,onWorkspaceChange:M=>{Fe.current=M,ze(M)},confirmLabel:Le.confirmLabel,busy:dt,onConfirm:bt,onCancel:()=>{xe.current=null,Be(null)}}),oe&&Ct&&e.jsx(Cn,{activeConv:Ct,ides:[],isCreatingChat:!1,isRefreshingHistory:Y,savedSessions:H,isSavedSessionsLoading:Y,isResumingSavedSessionId:be,onClose:()=>W(!1),onNewChat:()=>{$(""),W(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{We(R)},onResumeSavedSession:M=>{if(!M.canResume||be)return;const ee=Re(M);$(M.providerSessionId),_e(M),X(M.providerSessionId),W(!1),Ae({type:M.providerType,workspaceId:ee.workspaceId,workspacePath:ee.workspacePath,useHome:ee.useHome,resumeSessionId:M.providerSessionId}).finally(()=>{X(re=>re===M.providerSessionId?null:re)})}})]})}const za=[{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 Yp({machine:t,machineId:s,providers:r,ideSessions:n,cliSessions:o,acpSessions:i,actions:c,getIcon:d,initialCategory:p="ide",initialWorkspaceId:f,initialWorkspacePath:m,sendDaemonCommand:h}){var u;const[w,S]=a.useState(p);a.useEffect(()=>{S(p)},[p]);const I=a.useMemo(()=>({ide:n.length,cli:o.length,acp:i.length}),[n.length,o.length,i.length]);return e.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[e.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[e.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),e.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[e.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:za.map(b=>e.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${w===b.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>S(b.id),children:[e.jsx("span",{children:b.label}),e.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${w===b.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:I[b.id]})]},b.id))}),e.jsx("div",{className:"text-xs text-text-muted italic",children:(u=za.find(b=>b.id===w))==null?void 0:u.helper})]}),w==="ide"&&e.jsx(Qr,{category:"ide",machine:t,machineId:s,providers:r,managedEntries:n,getIcon:d,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:m}),w==="cli"&&e.jsx(Qr,{category:"cli",machine:t,machineId:s,providers:r,managedEntries:o,getIcon:d,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:m}),w==="acp"&&e.jsx(Qr,{category:"acp",machine:t,machineId:s,providers:r,managedEntries:i,getIcon:d,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:m})]})}function Xp({onNicknameSynced:t}={}){var ae,fe,le,he,J,pe,ne,we,ge;const{id:s}=Hi(),r=bs(),n=fn(),{sendCommand:o}=St(),i=Hs(),c=wo(),d=c.ides||[],p=c.initialLoaded??!0,f=d.find(P=>P.id===s&&P.type==="adhdev-daemon"),m=d.some(P=>P.type==="adhdev-daemon"),[h,w]=a.useState("workspace"),[S,I]=a.useState("ide"),u=a.useRef(null),[b,v]=a.useState(null),l=a.useRef("__home__"),[N,A]=a.useState("__home__"),[k,x]=a.useState(!1),g=a.useRef(null);a.useEffect(()=>{!s||!f||!(!f.workspaces||!f.availableProviders||!f.detectedIdes||!f.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,f,s]),Od(s&&h==="overview"?[s]:[],{enabled:h==="overview",intervalMs:15e3});const y=()=>{if(m){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},j=Tp({machineId:s,registeredMachineId:(f==null?void 0:f.machineId)||null,sendDaemonCommand:o,onNicknameSynced:t,logsEndRef:g});a.useEffect(()=>ht.onToast(ye=>{c.setToasts(me=>{if(me.some(Le=>Le.message===ye.message&&ye.timestamp-Le.timestamp<3e3))return me;const xe={id:ye.id,message:ye.message,type:ye.type,timestamp:ye.timestamp,targetKey:ye.targetKey,actions:ye.actions};return[...me.slice(-4),xe]});const F=ye.duration||5e3;setTimeout(()=>c.setToasts(me=>me.filter(Ce=>Ce.id!==ye.id)),F)}),[c]);const E=(f==null?void 0:f.availableProviders)||[],R={};for(const P of E)R[P.type]=P.icon;const K=P=>R[P]||"",D=f?{id:f.id,hostname:fo(f,{fallbackId:f.id}),platform:((ae=f.machine)==null?void 0:ae.platform)||"unknown",arch:((fe=f.machine)==null?void 0:fe.arch)||"",cpus:((le=f.machine)==null?void 0:le.cpus)||0,totalMem:((he=f.machine)==null?void 0:he.totalMem)||0,freeMem:(J=f.machine)==null?void 0:J.freeMem,availableMem:(pe=f.machine)==null?void 0:pe.availableMem,loadavg:(ne=f.machine)==null?void 0:ne.loadavg,uptime:(we=f.machine)==null?void 0:we.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,V=d.filter(P=>P.daemonId===s&&P.type!=="adhdev-daemon").filter(P=>!$s(P)&&!ms(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,version:P.version||"",instanceId:P.instanceId||"",status:P.status,workspace:P.workspace||null,terminals:P.terminals||0,aiAgents:Zc(P.aiAgents||(P.agents||[]).map(ye=>({id:ye.name,name:ye.name,status:ye.status,version:ye.version}))),activeChat:P.activeChat||null,chats:P.chats||[],childSessions:P.childSessions||[],cdpConnected:P.cdpConnected||!1,daemonId:s})),_=d.filter(P=>P.daemonId===s&&$s(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,cliName:P.cliName||P.type,status:P.status,workspace:P.workspace||"",activeChat:P.activeChat||null,providerSessionId:P.providerSessionId,mode:P.mode,runtimeKey:P.runtimeKey,runtimeDisplayName:P.runtimeDisplayName,runtimeWorkspaceLabel:P.runtimeWorkspaceLabel,runtimeWriteOwner:P.runtimeWriteOwner||null,runtimeAttachedClients:P.runtimeAttachedClients||[],daemonId:s})),C=d.filter(P=>P.daemonId===s&&ms(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,acpName:P.cliName||P.type,status:P.status,workspace:P.workspace||"",activeChat:P.activeChat||null,providerSessionId:P.providerSessionId,currentModel:P.currentModel,currentPlan:P.currentPlan,daemonId:s})),T=f?kt(f,{fallbackId:s}):"",z="workspace",L=n.state,$=L==null?void 0:L.initialMachineTab,H=L==null?void 0:L.initialWorkspaceCategory,se=L==null?void 0:L.initialWorkspaceId,Y=L==null?void 0:L.initialWorkspacePath,ie=$==="ides"||$==="clis"||$==="acps"?"workspace":$||z,je=$==="ides"?"ide":$==="clis"?"cli":$==="acps"?"acp":H,G=[...V.map(P=>{var ye,F,me,Ce,xe;return{id:`ide:${P.type}:${P.workspace||""}`,label:((ye=P.activeChat)==null?void 0:ye.title)||P.type,kind:"ide",providerType:P.type,subtitle:P.workspace||void 0,workspace:P.workspace||void 0,timestamp:((xe=(Ce=(me=(F=P.activeChat)==null?void 0:F.messages)==null?void 0:me.at)==null?void 0:Ce.call(me,-1))==null?void 0:xe.timestamp)||0}}),..._.map(P=>{var ye,F,me,Ce,xe;return{id:`cli:${P.type}:${P.workspace||""}`,label:((ye=P.activeChat)==null?void 0:ye.title)||P.cliName,kind:"cli",providerType:P.type,providerSessionId:P.providerSessionId,subtitle:P.workspace||void 0,workspace:P.workspace||void 0,timestamp:((xe=(Ce=(me=(F=P.activeChat)==null?void 0:F.messages)==null?void 0:me.at)==null?void 0:Ce.call(me,-1))==null?void 0:xe.timestamp)||0}}),...C.map(P=>{var ye,F,me,Ce,xe;return{id:`acp:${P.type}:${P.workspace||""}`,label:((ye=P.activeChat)==null?void 0:ye.title)||P.acpName,kind:"acp",providerType:P.type,providerSessionId:P.providerSessionId,subtitle:P.currentModel||P.workspace||void 0,workspace:P.workspace||void 0,currentModel:P.currentModel,timestamp:((xe=(Ce=(me=(F=P.activeChat)==null?void 0:F.messages)==null?void 0:me.at)==null?void 0:Ce.call(me,-1))==null?void 0:xe.timestamp)||0}})].sort((P,ye)=>ye.timestamp-P.timestamp).map(({timestamp:P,...ye})=>ye),oe=((f==null?void 0:f.recentLaunches)||[]).length>0?((f==null?void 0:f.recentLaunches)||[]).map(P=>({id:P.id,label:P.title||P.providerName||P.providerType,kind:P.kind,providerType:P.providerType,providerSessionId:P.providerSessionId,subtitle:P.currentModel||P.workspace||void 0,workspace:P.workspace,currentModel:P.currentModel})):G,W=a.useMemo(()=>{var ye;const P=((ye=c.connectionStates)==null?void 0:ye[s||""])||void 0;return d.filter(F=>F.daemonId===s&&F.type!=="adhdev-daemon").flatMap(F=>In(F,{},{connectionStates:s&&P?{[s]:P}:void 0,defaultConnectionState:P})).filter(F=>!(F.transport==="pty"&&F.mode==="terminal")).sort((F,me)=>an(me)-an(F))},[d,c.connectionStates,s]),be=a.useCallback(P=>{const ye=P.sessionId||P.tabKey;ye&&r(`/dashboard?activeTab=${encodeURIComponent(ye)}`)},[r]),X=a.useCallback(()=>{u.current&&(x(!0),u.current().finally(()=>{u.current=null,x(!1),v(null)}))},[]),ue=a.useCallback(P=>{if(!D)return;const{options:ye,selectedKey:F}=Zt({machine:D,currentWorkspacePath:P.workspace}),me=async()=>{I(P.kind),w("workspace")};u.current=async()=>{const Ce=ye.find(Be=>Be.key===l.current),xe=(Ce==null?void 0:Ce.workspacePath)??null,Le=(Ce==null?void 0:Ce.workspaceId)??null;if(P.kind==="ide"&&P.providerType){await j.handleLaunchIde(P.providerType,xe?{workspace:xe}:void 0);return}if((P.kind==="cli"||P.kind==="acp")&&P.providerType){await j.runLaunchCliCore({cliType:P.providerType,dir:Le?void 0:xe||"",workspaceId:Le||void 0,model:P.kind==="acp"?P.currentModel:void 0,resumeSessionId:P.providerSessionId});return}await me()},l.current=F,A(F),v({title:`Launch ${P.label}?`,description:"Recent launches now require one more confirmation before they start.",confirmLabel:"Launch",workspaceOptions:ye,details:[{label:"Mode",value:P.kind.toUpperCase()},...P.providerType?[{label:"Provider",value:P.providerType}]:[]]})},[j,D]);if(a.useEffect(()=>{w(ie)},[z,ie,s]),a.useEffect(()=>{je&&I(je)},[je,s]),!D)return p?e.jsxs("div",{className:"p-10 text-center text-text-muted",children:[e.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),e.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),e.jsx("button",{onClick:y,className:"machine-btn-back",children:"← Back"})]}):e.jsx("div",{className:"p-10 text-center text-text-muted",children:e.jsx("p",{children:"⏳ Loading machine..."})});const te=[{id:"workspace",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Nt,{size:14})," Workspace"]}),count:V.length+_.length+C.length},{id:"session-host",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ut,{size:14})," Session Host"]})},{id:"providers",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(vr,{size:14})," Providers"]})},{id:"overview",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ic,{size:14})," System"]})},{id:"logs",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(nc,{size:14})," Logs"]})}];return e.jsxs("div",{className:"flex flex-col h-full",children:[e.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:[e.jsx("div",{className:"flex items-center justify-between w-full",children:e.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[e.jsx("button",{onClick:y,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:"←"}),e.jsxs("div",{className:"flex flex-col min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[j.editingNickname?e.jsxs("div",{className:"flex gap-1.5 items-center",children:[e.jsx("input",{autoFocus:!0,value:j.nicknameInput,onChange:P=>j.setNicknameInput(P.target.value),onKeyDown:P=>{P.key==="Enter"&&j.handleSaveNickname(),P.key==="Escape"&&j.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]"}),e.jsx("button",{onClick:j.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"}),e.jsx("button",{onClick:()=>j.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"})]}):e.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{j.setEditingNickname(!0),j.setNicknameInput(D.machineNickname||"")},title:"Click to set nickname",children:T}),e.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"})]}),e.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:[e.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[D.platform," · ",D.arch]}),e.jsxs("span",{children:[D.cpus," cores"]}),(f==null?void 0:f.version)&&e.jsxs("span",{children:["v",f.version]}),D.p2p.available&&e.jsxs("span",{children:["P2P ",D.p2p.state==="connected"?"connected":D.p2p.state]}),D.machineNickname&&e.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:D.hostname})]})]})]})}),e.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:te.map(P=>e.jsxs("button",{onClick:()=>w(P.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${h===P.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[P.label,P.count!==void 0&&e.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${h===P.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:P.count})]},P.id))})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:e.jsx("div",{className:"max-w-7xl mx-auto h-full",children:e.jsxs("div",{className:"h-full",children:[h==="workspace"&&e.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[e.jsx(Fp,{machineEntry:f,providers:E,recentLaunches:oe,currentConversations:W,onUpgradeDaemon:async()=>{try{await o(s,"daemon_upgrade",{})}catch{}},onOpenRecent:ue,onOpenConversation:be}),e.jsx(Yp,{machine:D,machineId:s,providers:E,ideSessions:V,cliSessions:_,acpSessions:C,actions:j,getIcon:K,initialCategory:S,initialWorkspaceId:se,initialWorkspacePath:Y,sendDaemonCommand:o})]}),h==="providers"&&e.jsx($p,{machineId:s,providers:E,sendDaemonCommand:o}),h==="overview"&&e.jsx(_p,{machineId:s,machine:D,ideSessions:V,cliSessions:_,acpSessions:C,actions:j,sendDaemonCommand:o}),h==="session-host"&&e.jsx(Up,{machineId:s,cliSessions:_,sendDaemonCommand:o}),h==="logs"&&e.jsx(Bp,{machineId:s,sendDaemonCommand:o})]})})}),j.launchPick&&D&&e.jsx(zp,{machine:D,launchPick:j.launchPick,actions:j}),b&&e.jsx(Rn,{title:b.title,description:b.description,details:b.details,workspaceOptions:b.workspaceOptions,selectedWorkspaceKey:N,onWorkspaceChange:P=>{l.current=P,A(P)},confirmLabel:b.confirmLabel,busy:k,onConfirm:X,onCancel:()=>{u.current=null,v(null)}}),e.jsx(Ao,{toasts:c.toasts||[],onDismiss:P=>c.setToasts(ye=>ye.filter(F=>F.id!==P)),onClickToast:P=>{P.targetKey&&r(`/dashboard?activeTab=${encodeURIComponent(P.targetKey)}`)}}),e.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 g=await r(t,"session_host_prune_duplicate_sessions",{}),y=Yr(g);if(!(y!=null&&y.success))throw new Error((y==null?void 0:y.error)||"Duplicate prune failed");const j=y.result||{},E=Array.isArray(j.prunedSessionIds)?j.prunedSessionIds.length:0,R=typeof j.duplicateGroupCount=="number"?j.duplicateGroupCount:0;ht.showToast(`Pruned ${E} duplicate runtime(s) across ${R} group(s)`,"success"),await I()}catch(g){const y=g instanceof Error?g.message:"Duplicate prune failed";ht.showToast(y,"warning"),o(y)}finally{c(g=>g==="session_host_prune_duplicate_sessions"?null:g)}}},[t,I,r]),v=a.useMemo(()=>[...(m==null?void 0:m.sessions)||[]].sort((x,g)=>(g.lastActivityAt||0)-(x.lastActivityAt||0)),[m==null?void 0:m.sessions]),l=a.useMemo(()=>Hp(v),[v]),N=a.useMemo(()=>v.reduce((x,g)=>{var y;return x+(((y=g.attachedClients)==null?void 0:y.length)||0)},0),[v]),A=a.useMemo(()=>[...(m==null?void 0:m.recentTransitions)||[]].slice(-6).reverse(),[m==null?void 0:m.recentTransitions]),k=a.useMemo(()=>[...(m==null?void 0:m.recentLogs)||[]].reverse().find(x=>x.level==="warn"||x.level==="error")||null,[m==null?void 0:m.recentLogs]);return e.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[e.jsx(Ut,{size:14})," Session Host"]}),e.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:"Hosted CLI runtime diagnostics and recovery controls."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[l>0&&e.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{b()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${l})`}),e.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${m?"bg-green-500/[0.08] text-green-500":"bg-amber-500/[0.08] text-amber-400"}`,children:m?"Managed":"Unavailable"}),e.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{I()},disabled:h||d,children:[e.jsx(gs,{size:13}),h||d?"Refreshing…":"Refresh"]})]})]}),n&&!m&&e.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:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ts,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-amber-100",children:"Session host diagnostics unavailable"}),e.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),m&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Runtimes"}),e.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:m.runtimeCount})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Clients"}),e.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:N})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),e.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:m.recentRequests.length})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),e.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:Ua(m.hostStartedAt)}),e.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Xr(m.hostStartedAt)})]})]}),k&&e.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:[e.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[e.jsx(ts,{size:13})," Latest host warning"]}),e.jsx("div",{className:"text-text-primary leading-relaxed",children:k.message}),e.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Xr(k.timestamp),k.sessionId?` · ${k.sessionId}`:""]})]}),e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[e.jsx(wr,{size:14})," Hosted Runtimes"]}),v.length===0?e.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No hosted runtimes on this machine yet."}):e.jsx("div",{className:"space-y-2",children:v.map(x=>{var D;const g=i===`session_host_resume_session:${x.sessionId}`,y=i===`session_host_restart_session:${x.sessionId}`,j=i===`session_host_stop_session:${x.sessionId}`,E=Wp(x.meta),R=S.get(x.sessionId),K=x.attachedClients.length===1?"1 client":`${x.attachedClients.length} clients`;return e.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:x.displayName||(R==null?void 0:R.cliName)||x.providerType}),e.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Op(x.lifecycle)}`,children:x.lifecycle}),E&&e.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:E})]}),e.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[e.jsx("span",{className:"text-text-primary/90",children:x.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||x.workspace||"No workspace"}),e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsx("span",{className:"font-mono text-text-primary",children:x.runtimeKey}),x.osPid?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsxs("span",{className:"text-text-primary/90",children:["pid ",x.osPid]})]}):null]}),e.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[e.jsx("span",{className:((D=x.writeOwner)==null?void 0:D.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Kp(x.writeOwner)}),e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[e.jsx(hn,{size:11})," ",K]}),e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsxs("span",{className:"text-text-primary/85",children:["active ",Ua(x.lastActivityAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[(x.lifecycle==="interrupted"||x.lifecycle==="failed"||x.lifecycle==="stopped")&&e.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{u("session_host_resume_session",x)},children:g?"Resuming…":"Resume"}),e.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{u("session_host_restart_session",x)},children:y?"Restarting…":"Restart"}),(x.lifecycle==="running"||x.lifecycle==="starting"||x.lifecycle==="interrupted")&&e.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",x)},children:j?"Stopping…":"Stop"})]})]})},x.sessionId)})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),A.length===0?e.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."}):e.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:A.map(x=>{var y;const g=v.find(j=>j.sessionId===x.sessionId);return e.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-text-primary font-medium",children:(g==null?void 0:g.displayName)||((y=S.get(x.sessionId))==null?void 0:y.cliName)||x.sessionId}),e.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[x.action,x.lifecycle?` · ${x.lifecycle}`:"",x.detail?` · ${x.detail}`:"",x.error?` · ${x.error}`:""]})]}),e.jsx("div",{className:`shrink-0 text-[10px] ${x.success===!1?"text-red-300":"text-text-secondary"}`,children:Xr(x.timestamp)})]},`${x.sessionId}:${x.timestamp}:${x.action}`)})})]}),e.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",e.jsx("span",{className:"font-mono text-text-primary",children:m.endpoint||"unknown"}),n?e.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function zp({machine:t,launchPick:s,actions:r}){const{runLaunchCliCore:n,setLaunchPick:o}=r;return e.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:e.jsxs("div",{className:"w-full max-w-md rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-5",children:[e.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),e.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."}),e.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(t.workspaces||[]).length===0?e.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(t.workspaces||[]).map(i=>e.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:[e.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),e.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!t.defaultWorkspacePath,onClick:()=>{o(null),n({cliType:s.cliType,useDefaultWorkspace:!0,argsStr:s.argsStr,model:s.model})},children:"Default workspace"}),e.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"}),e.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>o(null),children:"Cancel"})]})]})})}function Jr({icon:t,children:s}){return e.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[t,e.jsx("span",{children:s})]})}function Zr({children:t,className:s=""}){return e.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${s}`,children:t})}function Fp({machineEntry:t,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:o,onOpenRecent:i,onOpenConversation:c}){const d=n.slice(0,6),p=r.slice(0,4),m=Ts(t,"0.8.51"),h=w=>w==="ide"?"IDE":w==="cli"?"CLI":"ACP";return e.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&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Jr,{icon:e.jsx(Kt,{size:13}),children:"Current Chats"}),e.jsx(Zr,{children:e.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(w=>{const S=an(w);return e.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(w),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[e.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:Qe(w)}),S>0&&e.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:vn(S)})]}),e.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ns(w)})]},w.tabKey)})})})]}),p.length>0&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Jr,{icon:e.jsx(ao,{size:13}),children:"Recent Launches"}),e.jsx(Zr,{children:e.jsx("div",{className:"flex flex-col gap-1.5",children:p.map(w=>e.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(w),children:[e.jsx("span",{className:"text-sm font-semibold text-text-primary truncate w-full group-hover:text-accent-primary transition-colors",children:w.label}),e.jsxs("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:[h(w.kind),w.subtitle?` · ${w.subtitle}`:""]})]},w.id))})})]}),t.versionMismatch&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Jr,{icon:e.jsx(ts,{size:13}),children:"Daemon Update"}),e.jsx(Zr,{className:"border-amber-500/20 bg-amber-500/5",children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:m?"Daemon update required":"Version mismatch detected"}),e.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:m?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),e.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:[e.jsx(gs,{size:13}),e.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Vp(t){return t?t.ownerType==="user"?"you control":"agent controls":"view only"}const Gp={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 nr(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function qp(t){const s=t instanceof Error?t.message:String(t||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function Qr({category:t,machine:s,machineId:r,providers:n,managedEntries:o,getIcon:i,actions:c,sendDaemonCommand:d,initialWorkspaceId:p,initialWorkspacePath:f}){const m=bs(),{handleLaunchIde:h,handleStopCli:w,handleRestartIde:S,handleStopIde:I,handleDetectIdes:u,launchingIde:b,launchingAgentType:v,addLog:l}=c,[N,A]=a.useState(null),k=a.useCallback(M=>{M&&m({pathname:"/",search:`?activeTab=${encodeURIComponent(M)}`})},[m]),x=Gp[t],g=t==="ide",y=t==="acp",j=a.useMemo(()=>n.filter(M=>M.category===t&&(t==="ide"||M.installed!==!1)),[t,n]),E=a.useMemo(()=>new Map(j.map(M=>[M.type,M.displayName||M.type])),[j]),[R,K]=a.useState(""),[D,V]=a.useState(""),[_,C]=a.useState([]),[T,z]=a.useState(""),[L,$]=a.useState(""),[H,se]=a.useState([]),[Y,ie]=a.useState(!1),[je,G]=a.useState(""),[oe,W]=a.useState(!1),[be,X]=a.useState(null),[ue,te]=a.useState(f?"__custom__":p||s.defaultWorkspaceId||""),[ae,fe]=a.useState(f||""),[le,he]=a.useState([]),[J,pe]=a.useState(!1),[ne,we]=a.useState(""),[ge,P]=a.useState([]),[ye,F]=a.useState(!1),[me,Ce]=a.useState(""),xe=a.useRef(null),[Le,Be]=a.useState(null),Fe=a.useRef("__home__"),[st,ze]=a.useState("__home__"),[dt,gt]=a.useState(!1),Ge=a.useRef(0),at=le.filter(M=>!o.some(ee=>ee.type===M&&xt(ee.status)!=="stopped")),ot=a.useRef({});a.useEffect(()=>{s.defaultWorkspaceId&&!ue&&te(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),a.useEffect(()=>{if(f){te("__custom__"),fe(f);return}p&&(te(p),fe(""))},[p,f]),a.useEffect(()=>{g||R&&(j.some(M=>M.type===R)||(K(""),$("")))},[j,g,R]);const Ke=(()=>{if(ue==="__custom__")return ae.trim();if(!ue)return"";const M=(s.workspaces||[]).find(ee=>ee.id===ue);return(M==null?void 0:M.path)||""})(),ct=a.useCallback(M=>{const ee=ot.current[M];ee&&(clearTimeout(ee),delete ot.current[M]),he(re=>re.includes(M)?re.filter(ce=>ce!==M):re)},[]),ut=a.useRef(new Set),it=a.useCallback(async M=>{if(d){F(!0),Ce("");try{const ee=await Ir(d,r,M);we(ee.path),fe(ee.path),P(ee.directories)}catch(ee){Ce(ee instanceof Error?ee.message:"Could not load folder")}finally{F(!1)}}},[r,d]),Q=a.useCallback(()=>{var ee;if(!d)return;te("__custom__"),pe(!0);const M=Cr(s.platform,[ae.trim(),Ke,s.defaultWorkspacePath,(ee=s.workspaces[0])==null?void 0:ee.path]);it(M)},[ae,it,s.defaultWorkspacePath,s.platform,s.workspaces,Ke,d]),_e=a.useCallback(M=>{const ee=String(M.workspace||"").trim();if(!ee)return;const re=(s.workspaces||[]).find(ce=>nr(ce.path)===nr(ee));if(re){te(re.id),fe("");return}te("__custom__"),fe(ee)},[s.workspaces]),Re=a.useCallback(M=>{const ee=String(M.workspace||"").trim();if(!ee)return{workspaceId:null,workspacePath:"",useHome:!0};const re=(s.workspaces||[]).find(ce=>nr(ce.path)===nr(ee));return re?{workspaceId:re.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:ee,useHome:!1}},[s.workspaces]),We=a.useCallback(async M=>{if(!d||!M||t!=="cli"){se([]),ie(!1),G("");return}const ee=Ge.current+1;Ge.current=ee,ie(!0),G("");try{const re=await d(r,"list_saved_sessions",{providerType:M,kind:"cli",limit:30});if(Ge.current!==ee)return;const ce=(re==null?void 0:re.result)??re;se(Array.isArray(ce==null?void 0:ce.sessions)?ce.sessions:[])}catch(re){if(Ge.current!==ee)return;se([]),G(re instanceof Error?re.message:"Could not load saved sessions")}finally{Ge.current===ee&&ie(!1)}},[t,r,d]),Ct=a.useMemo(()=>{if(t!=="cli"||!R)return null;const M=E.get(R)||R;return{routeId:r,daemonId:r,providerSessionId:L||void 0,transport:"pty",mode:"chat",agentName:M,agentType:R,status:"idle",title:M,messages:[],ideType:R,workspaceName:Ke,displayPrimary:M,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${R}`}},[t,r,E,Ke,L,R]),pt=a.useCallback(M=>{if(t==="ide"||!M){C([]);return}C(pi(r,M))},[t,r]);a.useEffect(()=>{if($(""),pt(R),t!=="cli"||!R){se([]),G(""),ie(!1);return}We(R)},[t,pt,We,R]),a.useEffect(()=>{if(!L)return;const M=H.find(ee=>ee.providerSessionId===L);M!=null&&M.canResume||$("")},[H,L]);const wt=a.useCallback((M,ee)=>{xe.current=ee,Fe.current=M.selectedWorkspaceKey||"__home__",ze(M.selectedWorkspaceKey||"__home__"),Be(M)},[]),bt=a.useCallback(()=>{xe.current&&(gt(!0),xe.current().finally(()=>{xe.current=null,gt(!1),Be(null)}))},[]),Tt=a.useCallback(M=>{if(!M)return;he(re=>re.includes(M)?re:[...re,M]);const ee=ot.current[M];ee&&clearTimeout(ee),ot.current[M]=setTimeout(()=>{he(re=>re.includes(M)?re.filter(ce=>ce!==M):re),delete ot.current[M]},2e4)},[]);a.useEffect(()=>{for(const ee of o)xt(ee.status)!=="stopped"&&(le.includes(ee.type)&&!ut.current.has(ee.type)&&(ut.current.add(ee.type),l("info",`${E.get(ee.type)||ee.type} launched`,!0)),ct(ee.type));const M=new Set(o.filter(ee=>xt(ee.status)!=="stopped").map(ee=>ee.type));ut.current.forEach(ee=>{!le.includes(ee)&&!M.has(ee)&&ut.current.delete(ee)})},[l,ct,o,le,E]),a.useEffect(()=>()=>{Object.values(ot.current).forEach(clearTimeout),ot.current={}},[]);const[B,U]=a.useState({}),[q,O]=a.useState(null);a.useEffect(()=>{if(!g||!r||!d)return;(async()=>{try{const ee=await d(r,"get_ide_extensions",{}),re=(ee==null?void 0:ee.result)||ee;re!=null&&re.success&&(re!=null&&re.ideExtensions)&&U(re.ideExtensions)}catch{}})()},[g,r,d]);const de=M=>g?Ze(M.type):t==="cli"?M.cliName:M.acpName,Se=g?s.detectedIdes||[]:[],Ae=a.useCallback(async M=>{const ee=(M==null?void 0:M.type)||R,re=(M==null?void 0:M.workspacePath)??Ke;if(g){await h(ee,re?{workspace:re}:void 0)&&Tt(ee);return}const ce=await c.runLaunchCliCore({cliType:ee,dir:M!=null&&M.workspaceId?void 0:re||void 0,workspaceId:(M==null?void 0:M.workspaceId)||void 0,useHome:(M==null?void 0:M.useHome)||!(M!=null&&M.workspaceId)&&!re,argsStr:(M==null?void 0:M.argsStr)??(D||void 0),model:(M==null?void 0:M.model)??(y&&T||void 0),resumeSessionId:(M==null?void 0:M.resumeSessionId)||!y&&t==="cli"&&ee===R&&L||void 0});if(ce.success||ce.pending){const Pe=(M==null?void 0:M.argsStr)??D;!g&&(Pe!=null&&Pe.trim())&&(mi(r,ee,Pe),pt(ee)),Tt(ee),ce.success&&ce.sessionId&&k(ce.sessionId)}},[c,h,y,g,D,T,pt,Tt,r,k,Ke,L,R]),Z=()=>{var ce;const M=g?Ze(R):E.get(R)||R,{options:ee,selectedKey:re}=Zt({machine:s,currentWorkspaceId:ue&&ue!=="__custom__"?ue:null,currentWorkspacePath:Ke});wt({title:`Launch ${M}?`,description:"Review the provider and target folder before starting this session.",confirmLabel:"Launch",workspaceOptions:ee,selectedWorkspaceKey:re,details:[{label:"Mode",value:x.label},{label:"Provider",value:M},...!g&&t==="cli"&&L?[{label:"Resume",value:((ce=H.find(Pe=>Pe.providerSessionId===L))==null?void 0:ce.title)||L}]:[],...!g&&D.trim()?[{label:"Arguments",value:D.trim()}]:[],...y&&T.trim()?[{label:"Model",value:T.trim()}]:[]]},async()=>{const Pe=ee.find(Me=>Me.key===Fe.current);Pe!=null&&Pe.workspaceId?(te(Pe.workspaceId),fe("")):Pe!=null&&Pe.workspacePath?(te("__custom__"),fe(Pe.workspacePath)):(te(""),fe("")),await Ae({workspaceId:(Pe==null?void 0:Pe.workspaceId)??null,workspacePath:(Pe==null?void 0:Pe.workspacePath)??"",useHome:!(Pe!=null&&Pe.workspaceId)&&!(Pe!=null&&Pe.workspacePath)})})},Ie=M=>{g?I(M):w(M.type,M.workspace,M.id)},De=a.useCallback(async(M,ee,re=!1)=>{if(M.mode===ee){re&&M.sessionId&&k(M.sessionId);return}if(!d||!M.sessionId){re&&M.sessionId&&k(M.sessionId);return}try{await d(r,"set_cli_view_mode",{targetSessionId:M.sessionId,cliType:M.type,mode:ee}),re&&k(M.sessionId)}catch(ce){qp(ce)?console.warn("Skipped CLI view mode switch:",ce instanceof Error?ce.message:String(ce)):console.error("Failed to switch CLI view mode:",ce)}},[r,k,d]),Ue=e.jsxs("div",{className:"mb-3",children:[e.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[e.jsx("select",{value:ue,onChange:M=>{const ee=M.target.value;if(te(ee),ee==="__custom__"&&d){Q();return}ee!=="__custom__"&&fe("")},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?e.jsxs(e.Fragment,{children:[e.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(s.workspaces||[]).map(M=>e.jsxs("option",{value:M.id,children:[M.id===s.defaultWorkspaceId?"⭐ ":"",kr(M.path,M.label)]},M.id)),e.jsx("option",{value:"__custom__",children:d?"📁 Select workspace…":"✏️ Custom path…"})]}):e.jsxs(e.Fragment,{children:[e.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),e.jsx("option",{value:"__custom__",children:d?"📁 Select workspace…":"✏️ Custom path…"})]})}),ue==="__custom__"&&(d?e.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:Q,children:"Select workspace…"}):e.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:ae,onChange:M=>fe(M.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}))]}),e.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:ue==="__custom__"?Ke?e.jsx("span",{className:"font-mono truncate block",title:Ke,children:Ke}):d?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":Ke?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-medium text-text-secondary",children:ue===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),e.jsx("span",{className:"font-mono truncate block",title:Ke,children:Ke})]}):"No workspace selected. This launches in the home directory."})]});return e.jsxs("div",{children:[e.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${x.accent} relative overflow-hidden`,children:[e.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),e.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",x.label," to Launch"]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:g?Se.length>0?Se.map(M=>{const ee=o.find(Oe=>(Oe.type||"").toLowerCase()===(M.type||"").toLowerCase()&&xt(Oe.status)!=="stopped"),re=M.running||!!ee,ce=!!ee&&ee.cdpConnected,Pe=le.includes(M.type||M.id||""),Me=R===(M.type||"");return e.jsxs("button",{onClick:()=>{if(ce&&ee){const Oe=ee.sessionId;Oe?m(`/dashboard?activeTab=${encodeURIComponent(Oe)}`,{state:{openRemoteForTabKey:Oe}}):m("/dashboard",{state:{openRemoteForTabKey:ee.id}});return}Pe||K(Oe=>Oe===(M.type||"")?"":M.type||"")},disabled:!!b||Pe,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${ce?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Me?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:b&&b!==M.type?.4:1},children:[e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i(M.type)}),re&&e.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${ce?"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"}`})]}),e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:M.name||Ze(M.type)}),e.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ce?"text-green-400":Pe?"text-orange-400":Me?"text-accent-primary":"text-text-muted"}`,children:ce?"Open Session":Pe?"Starting...":Me?"Configure":"Select"})]})]},M.type)}):e.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.",e.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:[e.jsx(oc,{size:14})," Scan System"]})]}):j.length>0?j.map(M=>{const ee=R===M.type,re=le.includes(M.type),Pe=!!o.find(Me=>Me.type===M.type&&xt(Me.status)!=="stopped");return e.jsxs("button",{onClick:()=>K(Me=>Me===M.type?"":M.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${ee?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:M.icon}),Pe&&e.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)]"})]}),e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:M.displayName}),e.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${re?"text-orange-400":ee?"text-accent-primary":"text-text-muted"}`,children:re?"Starting...":ee?"Configure":"Select"})]})]},M.type)}):e.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 ",t.toUpperCase()," providers available.",e.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."})]})}),R&&(g?Se.find(M=>M.type===R):j.find(M=>M.type===R))&&e.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:[e.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[e.jsx("span",{children:"Launch Settings"}),e.jsx("span",{className:"text-accent-primary font-bold",children:g?Ze(R):E.get(R)||R})]}),Ue,!g&&e.jsxs("div",{className:"flex flex-col gap-3",children:[!y&&t==="cli"&&e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Resume from History"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void We(R),disabled:!R||Y,children:Y?"Loading…":"Refresh"}),e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>{R&&(W(!0),We(R))},disabled:!R,children:"Open History"})]})]}),L?(()=>{const M=H.find(ee=>ee.providerSessionId===L);return M?e.jsx("div",{className:"rounded-md border border-[#ffffff1a] bg-bg-primary px-3 py-2 text-[10px] text-text-muted leading-relaxed",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-text-primary text-[11px] font-semibold truncate",children:M.title||M.providerSessionId}),e.jsx("div",{className:"font-mono break-all",children:M.providerSessionId}),e.jsx("div",{children:M.workspace||"Workspace unknown"})]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:()=>$(""),children:"Clear"})]})}):null})():e.jsx("div",{className:"text-[10px] text-text-muted",children:"Start a new CLI session, or choose one from history."}),je&&e.jsx("div",{className:"text-[10px] text-red-400",children:je})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[y&&e.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[e.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),e.jsx("input",{type:"text",placeholder:"Leave empty for default",value:T,onChange:M=>z(M.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"})]}),e.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[e.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),e.jsx("input",{type:"text",placeholder:"Optional flags...",value:D,onChange:M=>V(M.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"}),_.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:_.map(M=>e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>V(M),title:M,children:M},M))})]})]})]}),e.jsx("div",{className:"flex justify-end mt-2",children:e.jsx("button",{onClick:Z,disabled:!!v||!!b||le.includes(R),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:v===R||b===R?"⏳ Launching...":"▶ Launch"})})]})]}),e.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",o.length+le.filter(M=>!o.some(ee=>ee.type===M&&xt(ee.status)!=="stopped")).length,")"]}),o.length===0&&at.length===0?e.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 ",x.plural," running"]}):e.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[at.map(M=>e.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:e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"text-lg",children:i(M)}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:g?Ze(M):E.get(M)||M}),e.jsx("div",{className:"text-[11px] text-text-muted",children:v===M?"Launching process...":"Waiting for process and session to register..."})]})]}),e.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:${M}`)),o.map(M=>{const ee=g?M:null,re=y?M:null,ce=!g&&!y?M:null,Pe=xt(M.status);return e.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[e.jsxs("div",{className:"flex justify-between items-center mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"text-lg",children:i(M.type)}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[de(M),(ee==null?void 0:ee.version)&&e.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",ee.version]})]}),e.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[e.jsx("span",{children:M.workspace||"—"}),(re==null?void 0:re.currentModel)&&e.jsxs("span",{className:"text-cyan-500",children:["🤖 ",re.currentModel]}),(re==null?void 0:re.currentPlan)&&e.jsxs("span",{style:{color:"var(--status-warning)"},children:["📋 ",re.currentPlan]}),(ce==null?void 0:ce.mode)&&e.jsx("span",{className:ce.mode==="chat"?"text-violet-400":"text-text-secondary",children:ce.mode==="chat"?"Chat view":"Terminal view"})]}),ce&&(ce.runtimeKey||ce.runtimeWriteOwner)&&e.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ce.runtimeKey&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),e.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",ce.runtimeKey]}),e.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var Me;(Me=navigator.clipboard)==null||Me.writeText(`adhdev attach ${ce.runtimeKey}`),A(ce.runtimeKey||null),window.setTimeout(()=>{A(Oe=>Oe===ce.runtimeKey?null:Oe)},1200)},children:N===ce.runtimeKey?"Copied":"Copy"})]}),ce.runtimeWriteOwner&&e.jsx("span",{style:{color:ce.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ce.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Vp(ce.runtimeWriteOwner)})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Pe==="stopped"?"bg-red-500/[0.08] text-red-500":Pe==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Pe}),g&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>{const Me=M.sessionId;if(Me){m(`/dashboard?activeTab=${encodeURIComponent(Me)}`,{state:{openRemoteForTabKey:Me}});return}m("/dashboard",{state:{openRemoteForTabKey:M.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:e.jsx(Nt,{size:13})}),e.jsx("button",{onClick:()=>{const Me=M.workspace||"",{options:Oe,selectedKey:rt}=Zt({machine:s,currentWorkspacePath:Me});wt({title:`Restart ${Ze(M.type)}?`,description:"Review or change the target workspace before restarting this IDE.",confirmLabel:"Restart",workspaceOptions:Oe,selectedWorkspaceKey:rt,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:Ze(M.type)}]},async()=>{const Ye=Oe.find(He=>He.key===Fe.current),qe=(Ye==null?void 0:Ye.workspacePath)??"";if(qe&&qe!==Me){await Ae({type:M.type,workspacePath:qe});return}await S(M)})},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:e.jsx(gs,{size:14})})]}),y&&e.jsx("button",{onClick:()=>{const Me=M.sessionId;Me&&k(Me)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"View chat",disabled:!M.sessionId,children:e.jsx(Kt,{size:14})}),ce&&Pe!=="stopped"&&e.jsxs(e.Fragment,{children:[ce.mode&&e.jsx(Sn,{mode:ce.mode,onChange:Me=>void De(ce,Me,!1),compact:!0}),e.jsx("button",{onClick:()=>{const Me=M.sessionId;Me&&k(Me)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"Open current view in dashboard",disabled:!M.sessionId,children:ce.mode==="chat"?e.jsx(Kt,{size:14}):e.jsx(Nt,{size:13})})]}),Pe==="stopped"?e.jsx("button",{onClick:()=>{const Me=M.workspace||"",Oe=g?Ze(M.type):de(M),{options:rt,selectedKey:Ye}=Zt({machine:s,currentWorkspacePath:Me});wt({title:`Launch ${Oe}?`,description:"Review or change the target workspace before launching this stopped session again.",confirmLabel:"Launch",workspaceOptions:rt,selectedWorkspaceKey:Ye,details:[{label:"Mode",value:x.label},{label:"Provider",value:Oe}]},async()=>{const qe=rt.find(He=>He.key===Fe.current);await Ae({type:M.type,workspaceId:(qe==null?void 0:qe.workspaceId)??null,workspacePath:(qe==null?void 0:qe.workspacePath)??"",useHome:!(qe!=null&&qe.workspaceId)&&!(qe!=null&&qe.workspacePath),model:re==null?void 0:re.currentModel})})},disabled:le.includes(M.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:le.includes(M.type)?"⏳":e.jsx(gn,{size:14})}):e.jsx("button",{onClick:()=>Ie(M),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:e.jsx(vt,{size:14})})]})]}),ee&&ee.aiAgents.length>0&&e.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:ee.aiAgents.map(Me=>e.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${mo(Me.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Me.name," · ",xt(Me.status)]},Me.id))}),ee&&(B[ee.type]||[]).length>0&&d&&e.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[e.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:(B[ee.type]||[]).map(Me=>e.jsxs("button",{disabled:q===`${ee.type}.${Me.type}`,onClick:async()=>{const Oe=`${ee.type}.${Me.type}`;O(Oe);try{await d(r,"set_ide_extension",{ideType:ee.type,extensionType:Me.type,enabled:!Me.enabled}),U(rt=>({...rt,[ee.type]:(rt[ee.type]||[]).map(Ye=>Ye.type===Me.type?{...Ye,enabled:!Ye.enabled}:Ye)}))}catch(rt){console.error("Extension toggle failed:",rt)}finally{O(null)}},className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-medium border transition-colors duration-150 cursor-pointer ${Me.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Me.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Me.name,e.jsx("span",{className:"text-[9px] font-normal",children:Me.enabled?"ON":"OFF"})]},Me.type))})]})]},M.id)})]}),J&&d&&e.jsx(Ar,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:ne,directories:ge,busy:ye,error:me,confirmLabel:"Use this folder",onClose:()=>pe(!1),onNavigate:M=>{it(M)},onConfirm:M=>{fe(M),te("__custom__"),pe(!1)}}),Le&&e.jsx(Rn,{title:Le.title,description:Le.description,details:Le.details,workspaceOptions:Le.workspaceOptions,selectedWorkspaceKey:st,onWorkspaceChange:M=>{Fe.current=M,ze(M)},confirmLabel:Le.confirmLabel,busy:dt,onConfirm:bt,onCancel:()=>{xe.current=null,Be(null)}}),oe&&Ct&&e.jsx(Cn,{activeConv:Ct,ides:[],isCreatingChat:!1,isRefreshingHistory:Y,savedSessions:H,isSavedSessionsLoading:Y,isResumingSavedSessionId:be,onClose:()=>W(!1),onNewChat:()=>{$(""),W(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{We(R)},onResumeSavedSession:M=>{if(!M.canResume||be)return;const ee=Re(M);$(M.providerSessionId),_e(M),X(M.providerSessionId),W(!1),Ae({type:M.providerType,workspaceId:ee.workspaceId,workspacePath:ee.workspacePath,useHome:ee.useHome,resumeSessionId:M.providerSessionId}).finally(()=>{X(re=>re===M.providerSessionId?null:re)})}})]})}const za=[{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 Yp({machine:t,machineId:s,providers:r,ideSessions:n,cliSessions:o,acpSessions:i,actions:c,getIcon:d,initialCategory:p="ide",initialWorkspaceId:f,initialWorkspacePath:m,sendDaemonCommand:h}){var u;const[w,S]=a.useState(p);a.useEffect(()=>{S(p)},[p]);const I=a.useMemo(()=>({ide:n.length,cli:o.length,acp:i.length}),[n.length,o.length,i.length]);return e.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[e.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[e.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),e.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[e.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:za.map(b=>e.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${w===b.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>S(b.id),children:[e.jsx("span",{children:b.label}),e.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${w===b.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:I[b.id]})]},b.id))}),e.jsx("div",{className:"text-xs text-text-muted italic",children:(u=za.find(b=>b.id===w))==null?void 0:u.helper})]}),w==="ide"&&e.jsx(Qr,{category:"ide",machine:t,machineId:s,providers:r,managedEntries:n,getIcon:d,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:m}),w==="cli"&&e.jsx(Qr,{category:"cli",machine:t,machineId:s,providers:r,managedEntries:o,getIcon:d,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:m}),w==="acp"&&e.jsx(Qr,{category:"acp",machine:t,machineId:s,providers:r,managedEntries:i,getIcon:d,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:m})]})}function Xp({onNicknameSynced:t}={}){var ae,fe,le,he,J,pe,ne,we,ge;const{id:s}=Hi(),r=bs(),n=fn(),{sendCommand:o}=St(),i=Hs(),c=wo(),d=c.ides||[],p=c.initialLoaded??!0,f=d.find(P=>P.id===s&&P.type==="adhdev-daemon"),m=d.some(P=>P.type==="adhdev-daemon"),[h,w]=a.useState("workspace"),[S,I]=a.useState("ide"),u=a.useRef(null),[b,v]=a.useState(null),l=a.useRef("__home__"),[N,A]=a.useState("__home__"),[k,x]=a.useState(!1),g=a.useRef(null);a.useEffect(()=>{!s||!f||!(!f.workspaces||!f.availableProviders||!f.detectedIdes||!f.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,f,s]),Od(s&&h==="overview"?[s]:[],{enabled:h==="overview",intervalMs:15e3});const y=()=>{if(m){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},j=Tp({machineId:s,registeredMachineId:(f==null?void 0:f.machineId)||null,sendDaemonCommand:o,onNicknameSynced:t,logsEndRef:g});a.useEffect(()=>ht.onToast(ye=>{c.setToasts(me=>{if(me.some(Le=>Le.message===ye.message&&ye.timestamp-Le.timestamp<3e3))return me;const xe={id:ye.id,message:ye.message,type:ye.type,timestamp:ye.timestamp,targetKey:ye.targetKey,actions:ye.actions};return[...me.slice(-4),xe]});const F=ye.duration||5e3;setTimeout(()=>c.setToasts(me=>me.filter(Ce=>Ce.id!==ye.id)),F)}),[c]);const E=(f==null?void 0:f.availableProviders)||[],R={};for(const P of E)R[P.type]=P.icon;const K=P=>R[P]||"",D=f?{id:f.id,hostname:fo(f,{fallbackId:f.id}),platform:((ae=f.machine)==null?void 0:ae.platform)||"unknown",arch:((fe=f.machine)==null?void 0:fe.arch)||"",cpus:((le=f.machine)==null?void 0:le.cpus)||0,totalMem:((he=f.machine)==null?void 0:he.totalMem)||0,freeMem:(J=f.machine)==null?void 0:J.freeMem,availableMem:(pe=f.machine)==null?void 0:pe.availableMem,loadavg:(ne=f.machine)==null?void 0:ne.loadavg,uptime:(we=f.machine)==null?void 0:we.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,V=d.filter(P=>P.daemonId===s&&P.type!=="adhdev-daemon").filter(P=>!$s(P)&&!ms(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,version:P.version||"",instanceId:P.instanceId||"",status:P.status,workspace:P.workspace||null,terminals:P.terminals||0,aiAgents:Zc(P.aiAgents||(P.agents||[]).map(ye=>({id:ye.name,name:ye.name,status:ye.status,version:ye.version}))),activeChat:P.activeChat||null,chats:P.chats||[],childSessions:P.childSessions||[],cdpConnected:P.cdpConnected||!1,daemonId:s})),_=d.filter(P=>P.daemonId===s&&$s(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,cliName:P.cliName||P.type,status:P.status,workspace:P.workspace||"",activeChat:P.activeChat||null,providerSessionId:P.providerSessionId,mode:P.mode,runtimeKey:P.runtimeKey,runtimeDisplayName:P.runtimeDisplayName,runtimeWorkspaceLabel:P.runtimeWorkspaceLabel,runtimeWriteOwner:P.runtimeWriteOwner||null,runtimeAttachedClients:P.runtimeAttachedClients||[],daemonId:s})),C=d.filter(P=>P.daemonId===s&&ms(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,acpName:P.cliName||P.type,status:P.status,workspace:P.workspace||"",activeChat:P.activeChat||null,providerSessionId:P.providerSessionId,currentModel:P.currentModel,currentPlan:P.currentPlan,daemonId:s})),T=f?kt(f,{fallbackId:s}):"",z="workspace",L=n.state,$=L==null?void 0:L.initialMachineTab,H=L==null?void 0:L.initialWorkspaceCategory,se=L==null?void 0:L.initialWorkspaceId,Y=L==null?void 0:L.initialWorkspacePath,ie=$==="ides"||$==="clis"||$==="acps"?"workspace":$||z,je=$==="ides"?"ide":$==="clis"?"cli":$==="acps"?"acp":H,G=[...V.map(P=>{var ye,F,me,Ce,xe;return{id:`ide:${P.type}:${P.workspace||""}`,label:((ye=P.activeChat)==null?void 0:ye.title)||P.type,kind:"ide",providerType:P.type,subtitle:P.workspace||void 0,workspace:P.workspace||void 0,timestamp:((xe=(Ce=(me=(F=P.activeChat)==null?void 0:F.messages)==null?void 0:me.at)==null?void 0:Ce.call(me,-1))==null?void 0:xe.timestamp)||0}}),..._.map(P=>{var ye,F,me,Ce,xe;return{id:`cli:${P.type}:${P.workspace||""}`,label:((ye=P.activeChat)==null?void 0:ye.title)||P.cliName,kind:"cli",providerType:P.type,providerSessionId:P.providerSessionId,subtitle:P.workspace||void 0,workspace:P.workspace||void 0,timestamp:((xe=(Ce=(me=(F=P.activeChat)==null?void 0:F.messages)==null?void 0:me.at)==null?void 0:Ce.call(me,-1))==null?void 0:xe.timestamp)||0}}),...C.map(P=>{var ye,F,me,Ce,xe;return{id:`acp:${P.type}:${P.workspace||""}`,label:((ye=P.activeChat)==null?void 0:ye.title)||P.acpName,kind:"acp",providerType:P.type,providerSessionId:P.providerSessionId,subtitle:P.currentModel||P.workspace||void 0,workspace:P.workspace||void 0,currentModel:P.currentModel,timestamp:((xe=(Ce=(me=(F=P.activeChat)==null?void 0:F.messages)==null?void 0:me.at)==null?void 0:Ce.call(me,-1))==null?void 0:xe.timestamp)||0}})].sort((P,ye)=>ye.timestamp-P.timestamp).map(({timestamp:P,...ye})=>ye),oe=((f==null?void 0:f.recentLaunches)||[]).length>0?((f==null?void 0:f.recentLaunches)||[]).map(P=>({id:P.id,label:P.title||P.providerName||P.providerType,kind:P.kind,providerType:P.providerType,providerSessionId:P.providerSessionId,subtitle:P.currentModel||P.workspace||void 0,workspace:P.workspace,currentModel:P.currentModel})):G,W=a.useMemo(()=>{var ye;const P=((ye=c.connectionStates)==null?void 0:ye[s||""])||void 0;return d.filter(F=>F.daemonId===s&&F.type!=="adhdev-daemon").flatMap(F=>In(F,{},{connectionStates:s&&P?{[s]:P}:void 0,defaultConnectionState:P})).filter(F=>!(F.transport==="pty"&&F.mode==="terminal")).sort((F,me)=>an(me)-an(F))},[d,c.connectionStates,s]),be=a.useCallback(P=>{const ye=P.sessionId||P.tabKey;ye&&r(`/dashboard?activeTab=${encodeURIComponent(ye)}`)},[r]),X=a.useCallback(()=>{u.current&&(x(!0),u.current().finally(()=>{u.current=null,x(!1),v(null)}))},[]),ue=a.useCallback(P=>{if(!D)return;const{options:ye,selectedKey:F}=Zt({machine:D,currentWorkspacePath:P.workspace}),me=async()=>{I(P.kind),w("workspace")};u.current=async()=>{const Ce=ye.find(Be=>Be.key===l.current),xe=(Ce==null?void 0:Ce.workspacePath)??null,Le=(Ce==null?void 0:Ce.workspaceId)??null;if(P.kind==="ide"&&P.providerType){await j.handleLaunchIde(P.providerType,xe?{workspace:xe}:void 0);return}if((P.kind==="cli"||P.kind==="acp")&&P.providerType){await j.runLaunchCliCore({cliType:P.providerType,dir:Le?void 0:xe||"",workspaceId:Le||void 0,model:P.kind==="acp"?P.currentModel:void 0,resumeSessionId:P.providerSessionId});return}await me()},l.current=F,A(F),v({title:`Launch ${P.label}?`,description:"Recent launches now require one more confirmation before they start.",confirmLabel:"Launch",workspaceOptions:ye,details:[{label:"Mode",value:P.kind.toUpperCase()},...P.providerType?[{label:"Provider",value:P.providerType}]:[]]})},[j,D]);if(a.useEffect(()=>{w(ie)},[z,ie,s]),a.useEffect(()=>{je&&I(je)},[je,s]),!D)return p?e.jsxs("div",{className:"p-10 text-center text-text-muted",children:[e.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),e.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),e.jsx("button",{onClick:y,className:"machine-btn-back",children:"← Back"})]}):e.jsx("div",{className:"p-10 text-center text-text-muted",children:e.jsx("p",{children:"⏳ Loading machine..."})});const te=[{id:"workspace",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Nt,{size:14})," Workspace"]}),count:V.length+_.length+C.length},{id:"session-host",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ut,{size:14})," Session Host"]})},{id:"providers",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(vr,{size:14})," Providers"]})},{id:"overview",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ic,{size:14})," System"]})},{id:"logs",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(nc,{size:14})," Logs"]})}];return e.jsxs("div",{className:"flex flex-col h-full",children:[e.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:[e.jsx("div",{className:"flex items-center justify-between w-full",children:e.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[e.jsx("button",{onClick:y,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:"←"}),e.jsxs("div",{className:"flex flex-col min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[j.editingNickname?e.jsxs("div",{className:"flex gap-1.5 items-center",children:[e.jsx("input",{autoFocus:!0,value:j.nicknameInput,onChange:P=>j.setNicknameInput(P.target.value),onKeyDown:P=>{P.key==="Enter"&&j.handleSaveNickname(),P.key==="Escape"&&j.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]"}),e.jsx("button",{onClick:j.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"}),e.jsx("button",{onClick:()=>j.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"})]}):e.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{j.setEditingNickname(!0),j.setNicknameInput(D.machineNickname||"")},title:"Click to set nickname",children:T}),e.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"})]}),e.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:[e.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[D.platform," · ",D.arch]}),e.jsxs("span",{children:[D.cpus," cores"]}),(f==null?void 0:f.version)&&e.jsxs("span",{children:["v",f.version]}),D.p2p.available&&e.jsxs("span",{children:["P2P ",D.p2p.state==="connected"?"connected":D.p2p.state]}),D.machineNickname&&e.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:D.hostname})]})]})]})}),e.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:te.map(P=>e.jsxs("button",{onClick:()=>w(P.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${h===P.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[P.label,P.count!==void 0&&e.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${h===P.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:P.count})]},P.id))})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:e.jsx("div",{className:"max-w-7xl mx-auto h-full",children:e.jsxs("div",{className:"h-full",children:[h==="workspace"&&e.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[e.jsx(Fp,{machineEntry:f,providers:E,recentLaunches:oe,currentConversations:W,onUpgradeDaemon:async()=>{try{await o(s,"daemon_upgrade",{})}catch{}},onOpenRecent:ue,onOpenConversation:be}),e.jsx(Yp,{machine:D,machineId:s,providers:E,ideSessions:V,cliSessions:_,acpSessions:C,actions:j,getIcon:K,initialCategory:S,initialWorkspaceId:se,initialWorkspacePath:Y,sendDaemonCommand:o})]}),h==="providers"&&e.jsx($p,{machineId:s,providers:E,sendDaemonCommand:o}),h==="overview"&&e.jsx(_p,{machineId:s,machine:D,ideSessions:V,cliSessions:_,acpSessions:C,actions:j,sendDaemonCommand:o}),h==="session-host"&&e.jsx(Up,{machineId:s,cliSessions:_,sendDaemonCommand:o}),h==="logs"&&e.jsx(Bp,{machineId:s,sendDaemonCommand:o})]})})}),j.launchPick&&D&&e.jsx(zp,{machine:D,launchPick:j.launchPick,actions:j}),b&&e.jsx(Rn,{title:b.title,description:b.description,details:b.details,workspaceOptions:b.workspaceOptions,selectedWorkspaceKey:N,onWorkspaceChange:P=>{l.current=P,A(P)},confirmLabel:b.confirmLabel,busy:k,onConfirm:X,onCancel:()=>{u.current=null,v(null)}}),e.jsx(Ao,{toasts:c.toasts||[],onDismiss:P=>c.setToasts(ye=>ye.filter(F=>F.id!==P)),onClickToast:P=>{P.targetKey&&r(`/dashboard?activeTab=${encodeURIComponent(P.targetKey)}`)}}),e.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 Jp{constructor(){nt(this,"adapters",new Map);nt(this,"states",new Map);nt(this,"runtimeListeners",new Map);nt(this,"screenshotCallbacks",new Map);nt(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 Et=new Jp;function Zp(){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 ar=Zp(),Fa=3e3,Qp=3e4;let Rt=null,em=0;const yr=new Map;let Gt=null,Ps=null;function Va(t,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${t}`,s)}catch{}}function Cs(t,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${t}`,s)}catch{}}function tm(t){return t==="connected"?"connected":t}async function dr(t,s,r){const n=Ul(t,r||{}),o=Rt;if(o&&o.readyState===WebSocket.OPEN){const i=`req_${++em}_${Date.now()}`;return new Promise((c,d)=>{const p=setTimeout(()=>{yr.delete(i),d(new Error(`WS command timeout: ${s}`))},3e4);yr.set(i,{resolve:f=>{clearTimeout(p),c(f)},reject:f=>{clearTimeout(p),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 mn(t,s){const r=Rt;if(!r||r.readyState!==WebSocket.OPEN)return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class sm{constructor(s){nt(this,"daemonId");nt(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 dr(this.daemonId,s,r)}async sendInput(s,r){return dr(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,Gt&&(clearInterval(Gt),Gt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await dr(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());Et.emitScreenshot(this.daemonId,o)}}catch{}};r(),Gt=setInterval(r,2e3)}stopScreenshots(s){Gt&&(clearInterval(Gt),Gt=null)}}let Mt=null;function rm(t){return(!Mt||Mt.daemonId!==t)&&(Mt=new sm(t)),Mt}function nm({children:t}){const s=a.useRef(pr()),r=pr();s.current=r;const{setUserName:n}=es(),o=a.useRef(n);o.current=n;const i=a.useRef(null),c=a.useRef(null),[,d]=a.useState("disconnected"),p=a.useCallback((u,b)=>{d(u),Ps==null||Ps(u,b)},[]),f=a.useRef(null),m=a.useRef(),h=a.useRef(Fa),w=a.useRef(!0),S=a.useRef(!1),I=a.useRef("initial_connect");return a.useEffect(()=>{w.current=!0,S.current=!1;function u(){var l,N;if(!w.current||((l=f.current)==null?void 0:l.readyState)===WebSocket.OPEN||((N=f.current)==null?void 0:N.readyState)===WebSocket.CONNECTING)return;p("connecting"),console.log(`[Standalone WS] Connecting to ${ar}...`),Cs("connect_attempt",{url:ar,reason:I.current,delayMs:h.current});let v;try{v=new WebSocket(ar)}catch(A){console.error("[Standalone WS] Failed to create WebSocket:",A),b();return}f.current=v,v.onopen=()=>{if(!w.current){v.close();return}p("connected"),h.current=Fa,Cs("open",{url:ar,reason:I.current}),Ot.resubscribeAll({sendData:mn}),console.log("[Standalone WS] Connected")},Rt=v,v.onmessage=A=>{var k,x;try{const g=JSON.parse(A.data);if((g.type==="command_result"||g.type==="error")&&g.requestId){const y=yr.get(g.requestId);y&&(yr.delete(g.requestId),g.type==="error"?y.reject(new Error(((k=g.data)==null?void 0:k.message)||"Command failed")):y.resolve(g.data));return}if(g.type==="session_output"){const y=g.sessionId||g.cliId||g.cliType;y&&Et.emitSessionOutput(y,typeof g.data=="string"?g.data:"",typeof g.seq=="number"?g.seq:void 0);return}if(g.type==="runtime_snapshot"){Et.emitRuntimeSnapshot(g.sessionId,typeof g.text=="string"?g.text:"",typeof g.seq=="number"?g.seq:0,!!g.truncated);return}if(g.type==="topic_update"){const y=g.update;y&&Ot.publish(y);return}if(g.type==="status"||g.type==="initial_state"){const y=g.data;if(!y)return;const{injectEntries:j,markLoaded:E,getIdes:R}=s.current,K=y.instanceId||"standalone",D=R().find(C=>C.id===K),V=rm(K);Et.register(K,V),Et.setState(K,"connected"),p("connected",K),Et.emitStatus(K,y);const _=fr(y,{daemonId:K,existingDaemon:D,existingEntries:R()});Va("ws_status",{type:g.type,daemonId:K,sessions:(y.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:(y.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),Va("entries",{daemonId:K,entries:_.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}))}),_.length>0&&j(_,{authoritativeDaemonIds:[K]}),E(),c.current!==K&&((x=i.current)==null||x.call(i),c.current=K,i.current=Ot.subscribe({sendData:mn},K,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${K}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const T=s.current.getIdes(),z=T.find($=>$.id===K),L=fr(C.status,{daemonId:K,existingDaemon:z,existingEntries:T,timestamp:C.timestamp});L.length>0&&s.current.injectEntries(L),C.userName&&o.current&&o.current(C.userName)}))}}catch(g){console.error("[Standalone WS] Parse error:",g)}},v.onclose=A=>{w.current&&(Mt==null||Mt.stopScreenshots(),Mt&&Et.setState(Mt.daemonId,"disconnected"),p("disconnected"),f.current=null,I.current=`close:${A.code}${A.wasClean?":clean":":unclean"}`,Cs("close",{code:A.code,reason:A.reason||"",wasClean:A.wasClean}),b())},v.onerror=A=>{S.current||!w.current||(I.current="error",Cs("error",{message:A instanceof Event?"event":String(A),readyState:v.readyState}),console.warn("[Standalone WS] Error, will reconnect:",A))}}function b(){if(!w.current)return;clearTimeout(m.current);const v=h.current;console.log(`[Standalone WS] Reconnecting in ${v}ms...`),Cs("schedule_reconnect",{reason:I.current,delayMs:v}),m.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,Qp),u()},v)}return u(),()=>{var v;w.current=!1,S.current=!0,(v=i.current)==null||v.call(i),i.current=null,c.current=null,clearTimeout(m.current),f.current&&(f.current.onerror=null,f.current.onclose=null,f.current.close(),f.current=null,Rt=null),Mt&&(Mt.stopScreenshots(),Et.unregister(Mt.daemonId))}},[]),e.jsx(e.Fragment,{children:t})}function am({children:t}){const[s,r]=a.useState("disconnected"),[n,o]=a.useState(null);a.useEffect(()=>(Ps=(c,d)=>{r(c),d&&o(d)},()=>{Ps=null}),[]);const i=a.useMemo(()=>{const c=s==="connected",d=tm(s),p={};return n&&(p[n]=d),p.standalone=d,{wsStatus:s,isConnected:c,connectionStates:p}},[s,n]);return e.jsx(Xi,{connectionOverrides:i,children:e.jsx(nm,{children:t})})}const om=[{id:"dashboard",path:"/dashboard",icon:e.jsx(eo,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:e.jsx(Ut,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:e.jsx(vr,{}),label:"Settings"}];function im({children:t}){const s=bs(),r=fn(),[n,o]=a.useState(!1),[i,c]=a.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),d=m=>{s(m),o(!1)},p=()=>{c(m=>{const h=!m;try{localStorage.setItem("sidebar-collapsed",h?"1":"0")}catch{}return h})},f=m=>`nav-item${r.pathname.startsWith(m)?" active":""} cursor-pointer ${i?"justify-center py-2.5 px-0":""}`;return e.jsxs("div",{className:`app-layout${n?" mobile-menu-open":""}${i?" sidebar-collapsed":""}`,children:[e.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:()=>o(!0),children:[e.jsx("span",{className:"mobile-menu-icon"}),e.jsx("span",{className:"mobile-menu-icon"}),e.jsx("span",{className:"mobile-menu-icon"})]}),n&&e.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:()=>o(!1),onKeyDown:m=>m.key==="Escape"&&o(!1)}),e.jsxs("aside",{className:`sidebar ${n?"sidebar-open":""}`,children:[e.jsxs("div",{className:"sidebar-header",children:[e.jsxs("div",{className:`sidebar-logo ${i?"justify-center gap-0":""}`,children:[e.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&e.jsx("span",{children:"ADHDev"})]}),e.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:()=>o(!1),children:"✕"})]}),e.jsx("nav",{className:"sidebar-nav",children:om.map(m=>e.jsxs("div",{className:f(m.path),id:`nav-${m.id}`,onClick:()=>d(m.path),title:i?m.label:void 0,children:[e.jsx("span",{className:"nav-icon",children:m.icon}),!i&&m.label]},m.id))}),e.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[e.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:[e.jsx("span",{className:"nav-icon",children:e.jsx(to,{})}),!i&&e.jsxs(e.Fragment,{children:["Docs",e.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]})]}),e.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:[e.jsx("span",{className:"nav-icon",children:e.jsx(so,{})}),!i&&"About"]}),!i&&e.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.50"]}),e.jsx(wd,{collapsed:i}),e.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:p,title:i?"Expand sidebar":"Collapse sidebar",children:[e.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&e.jsx("span",{className:"text-xs",children:"Collapse"})]})]})]}),e.jsx("main",{className:"main-content relative",children:e.jsx("div",{className:"main-content-inner",children:t})})]})}const cm=[{icon:e.jsx(Ut,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:e.jsx(Kt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:e.jsx(ro,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:e.jsx(Nt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:e.jsx(Rs,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:e.jsx(to,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],lm=[{icon:e.jsx(oo,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:e.jsx(eo,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:e.jsx(jr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:e.jsx(rc,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:e.jsx(hn,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:e.jsx(ac,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],dm=[{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 um(){return e.jsxs(Eo,{icon:e.jsx(so,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:e.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.50"]}),children:[e.jsx(Pt,{children:e.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[e.jsxs("div",{className:"max-w-2xl",children:[e.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),e.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."}),e.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."})]}),e.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[e.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 ↗"}),e.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 ↗"}),e.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 ↗"})]})]})}),e.jsx(Pt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:e.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:cm.map(t=>e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[e.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:t.icon}),t.title]}),e.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),e.jsx(Pt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:e.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:_o.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:Lo.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:Po.map(t=>`${t.icon} ${t.name}`)}].map(t=>e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[e.jsx("div",{className:"text-[10px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:t.label}),e.jsx("div",{className:"flex flex-col gap-1.5",children:t.items.map(s=>e.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))})]},t.label))})}),e.jsx(Pt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:e.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:lm.map(t=>e.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[e.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:t.icon}),t.title]}),e.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),e.jsx(Pt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:e.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:e.jsxs("table",{className:"w-full text-[13px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-bg-secondary",children:[e.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),e.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),e.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),e.jsx("tbody",{children:dm.map((t,s)=>e.jsxs("tr",{className:s%2===0?"bg-bg-glass":"bg-transparent",children:[e.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:t.feature}),e.jsx("td",{className:"px-4 py-2.5 text-center",children:t.selfhost?e.jsx("span",{className:"text-emerald-500",children:"✓"}):e.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),e.jsx("td",{className:"px-4 py-2.5 text-center",children:e.jsx("span",{className:"text-emerald-500",children:"✓"})})]},t.feature))})]})})}),e.jsx($o,{icon:e.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:e.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[e.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),e.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[e.jsx(yc,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function pm(){const{ides:t}=es(),s=t.find(h=>h.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=St(),{userName:o}=es(),[i,c]=a.useState(o||"");a.useEffect(()=>{o!==void 0&&c(o)},[o]);const d=h=>{const w=h.target.value.trim();s!=null&&s.id&&w!==o&&n(s.id,"set_user_name",{userName:w}).catch(console.error)},[p,f]=a.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),m=h=>{f(h);try{localStorage.setItem("adhdev_sound",h?"1":"0")}catch{}};return e.jsxs(Eo,{icon:e.jsx(vr,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[e.jsx(xd,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost."}),e.jsx(Pt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:e.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[e.jsx("span",{className:"text-text-muted",children:"Version"}),e.jsxs("span",{className:"font-mono text-xs",children:["v","0.8.50"]}),e.jsx("span",{className:"text-text-muted",children:"Status"}),e.jsx("span",{className:s?"text-green-400":"text-yellow-400",children:s?"● Running":"○ Not connected"}),e.jsx("span",{className:"text-text-muted",children:"WebSocket"}),e.jsx("span",{className:"font-mono text-xs",children:"ws://localhost:19222"}),e.jsx("span",{className:"text-text-muted",children:"HTTP"}),e.jsx("span",{className:"font-mono text-xs",children:"http://localhost:19280"})]})}),e.jsx(Pt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?e.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):e.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(h=>e.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${h.running?"bg-green-400":"bg-text-muted/30"}`}),e.jsx("span",{className:"text-sm font-medium",children:h.name})]}),e.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:h.type})]},h.type))})}),e.jsx(Pt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:e.jsx(Sd,{ides:t,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),e.jsx(Pt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode and theme.",children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),e.jsx(Md,{})]}),e.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[e.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),e.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."}),e.jsx($d,{})]}),e.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[e.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),e.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."}),e.jsx(Kd,{})]})]})}),e.jsx(Pt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx(jd,{}),e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(gc,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:p,onChange:m})]})}),e.jsx(Pt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:e.jsx("div",{className:"flex flex-col gap-3",children:e.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:[e.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[e.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(sc,{size:16,className:"text-text-secondary"})," Display Name"]}),e.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),e.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:h=>c(h.target.value),onBlur:d,onKeyDown:h=>{h.key==="Enter"&&h.currentTarget.blur()}})]})})})]})}vd();Dd();const mm=Za({baseUrl:""});function Ga(){const{ides:t,initialLoaded:s}=es();if(!s)return e.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=t.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?e.jsx(sn,{to:`/machines/${r.id}`,replace:!0}):e.jsx(sn,{to:"/dashboard",replace:!0})}function fm(){const t=a.useMemo(()=>({sendCommand:dr,sendData:mn}),[]);return e.jsx(Ui,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:e.jsx(Qi,{client:mm,children:e.jsx(am,{children:e.jsx(tc,{value:t,children:e.jsx(im,{children:e.jsxs(zi,{children:[e.jsx(Ft,{path:"/dashboard",element:e.jsx(Mp,{})}),e.jsx(Ft,{path:"/machine",element:e.jsx(Ga,{})}),e.jsx(Ft,{path:"/machines/:id",element:e.jsx(Xp,{})}),e.jsx(Ft,{path:"/machines",element:e.jsx(Ga,{})}),e.jsx(Ft,{path:"/about",element:e.jsx(um,{})}),e.jsx(Ft,{path:"/settings",element:e.jsx(pm,{})}),e.jsx(Ft,{path:"*",element:e.jsx(sn,{to:"/dashboard",replace:!0})})]})})})})})})}Sl({connectionManager:Et});Fi(document.getElementById("root")).render(e.jsx(fm,{}));
71
+ `})]})}class Jp{constructor(){nt(this,"adapters",new Map);nt(this,"states",new Map);nt(this,"runtimeListeners",new Map);nt(this,"screenshotCallbacks",new Map);nt(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 Et=new Jp;function Zp(){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 ar=Zp(),Fa=3e3,Qp=3e4;let Rt=null,em=0;const yr=new Map;let Gt=null,Ps=null;function Va(t,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${t}`,s)}catch{}}function Cs(t,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${t}`,s)}catch{}}function tm(t){return t==="connected"?"connected":t}async function dr(t,s,r){const n=Ul(t,r||{}),o=Rt;if(o&&o.readyState===WebSocket.OPEN){const i=`req_${++em}_${Date.now()}`;return new Promise((c,d)=>{const p=setTimeout(()=>{yr.delete(i),d(new Error(`WS command timeout: ${s}`))},3e4);yr.set(i,{resolve:f=>{clearTimeout(p),c(f)},reject:f=>{clearTimeout(p),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 mn(t,s){const r=Rt;if(!r||r.readyState!==WebSocket.OPEN)return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class sm{constructor(s){nt(this,"daemonId");nt(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 dr(this.daemonId,s,r)}async sendInput(s,r){return dr(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,Gt&&(clearInterval(Gt),Gt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await dr(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());Et.emitScreenshot(this.daemonId,o)}}catch{}};r(),Gt=setInterval(r,2e3)}stopScreenshots(s){Gt&&(clearInterval(Gt),Gt=null)}}let Mt=null;function rm(t){return(!Mt||Mt.daemonId!==t)&&(Mt=new sm(t)),Mt}function nm({children:t}){const s=a.useRef(pr()),r=pr();s.current=r;const{setUserName:n}=es(),o=a.useRef(n);o.current=n;const i=a.useRef(null),c=a.useRef(null),[,d]=a.useState("disconnected"),p=a.useCallback((u,b)=>{d(u),Ps==null||Ps(u,b)},[]),f=a.useRef(null),m=a.useRef(),h=a.useRef(Fa),w=a.useRef(!0),S=a.useRef(!1),I=a.useRef("initial_connect");return a.useEffect(()=>{w.current=!0,S.current=!1;function u(){var l,N;if(!w.current||((l=f.current)==null?void 0:l.readyState)===WebSocket.OPEN||((N=f.current)==null?void 0:N.readyState)===WebSocket.CONNECTING)return;p("connecting"),console.log(`[Standalone WS] Connecting to ${ar}...`),Cs("connect_attempt",{url:ar,reason:I.current,delayMs:h.current});let v;try{v=new WebSocket(ar)}catch(A){console.error("[Standalone WS] Failed to create WebSocket:",A),b();return}f.current=v,v.onopen=()=>{if(!w.current){v.close();return}p("connected"),h.current=Fa,Cs("open",{url:ar,reason:I.current}),Ot.resubscribeAll({sendData:mn}),console.log("[Standalone WS] Connected")},Rt=v,v.onmessage=A=>{var k,x;try{const g=JSON.parse(A.data);if((g.type==="command_result"||g.type==="error")&&g.requestId){const y=yr.get(g.requestId);y&&(yr.delete(g.requestId),g.type==="error"?y.reject(new Error(((k=g.data)==null?void 0:k.message)||"Command failed")):y.resolve(g.data));return}if(g.type==="session_output"){const y=g.sessionId||g.cliId||g.cliType;y&&Et.emitSessionOutput(y,typeof g.data=="string"?g.data:"",typeof g.seq=="number"?g.seq:void 0);return}if(g.type==="runtime_snapshot"){Et.emitRuntimeSnapshot(g.sessionId,typeof g.text=="string"?g.text:"",typeof g.seq=="number"?g.seq:0,!!g.truncated);return}if(g.type==="topic_update"){const y=g.update;y&&Ot.publish(y);return}if(g.type==="status"||g.type==="initial_state"){const y=g.data;if(!y)return;const{injectEntries:j,markLoaded:E,getIdes:R}=s.current,K=y.instanceId||"standalone",D=R().find(C=>C.id===K),V=rm(K);Et.register(K,V),Et.setState(K,"connected"),p("connected",K),Et.emitStatus(K,y);const _=fr(y,{daemonId:K,existingDaemon:D,existingEntries:R()});Va("ws_status",{type:g.type,daemonId:K,sessions:(y.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:(y.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),Va("entries",{daemonId:K,entries:_.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}))}),_.length>0&&j(_,{authoritativeDaemonIds:[K]}),E(),c.current!==K&&((x=i.current)==null||x.call(i),c.current=K,i.current=Ot.subscribe({sendData:mn},K,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${K}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const T=s.current.getIdes(),z=T.find($=>$.id===K),L=fr(C.status,{daemonId:K,existingDaemon:z,existingEntries:T,timestamp:C.timestamp});L.length>0&&s.current.injectEntries(L),C.userName&&o.current&&o.current(C.userName)}))}}catch(g){console.error("[Standalone WS] Parse error:",g)}},v.onclose=A=>{w.current&&(Mt==null||Mt.stopScreenshots(),Mt&&Et.setState(Mt.daemonId,"disconnected"),p("disconnected"),f.current=null,I.current=`close:${A.code}${A.wasClean?":clean":":unclean"}`,Cs("close",{code:A.code,reason:A.reason||"",wasClean:A.wasClean}),b())},v.onerror=A=>{S.current||!w.current||(I.current="error",Cs("error",{message:A instanceof Event?"event":String(A),readyState:v.readyState}),console.warn("[Standalone WS] Error, will reconnect:",A))}}function b(){if(!w.current)return;clearTimeout(m.current);const v=h.current;console.log(`[Standalone WS] Reconnecting in ${v}ms...`),Cs("schedule_reconnect",{reason:I.current,delayMs:v}),m.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,Qp),u()},v)}return u(),()=>{var v;w.current=!1,S.current=!0,(v=i.current)==null||v.call(i),i.current=null,c.current=null,clearTimeout(m.current),f.current&&(f.current.onerror=null,f.current.onclose=null,f.current.close(),f.current=null,Rt=null),Mt&&(Mt.stopScreenshots(),Et.unregister(Mt.daemonId))}},[]),e.jsx(e.Fragment,{children:t})}function am({children:t}){const[s,r]=a.useState("disconnected"),[n,o]=a.useState(null);a.useEffect(()=>(Ps=(c,d)=>{r(c),d&&o(d)},()=>{Ps=null}),[]);const i=a.useMemo(()=>{const c=s==="connected",d=tm(s),p={};return n&&(p[n]=d),p.standalone=d,{wsStatus:s,isConnected:c,connectionStates:p}},[s,n]);return e.jsx(Xi,{connectionOverrides:i,children:e.jsx(nm,{children:t})})}const om=[{id:"dashboard",path:"/dashboard",icon:e.jsx(eo,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:e.jsx(Ut,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:e.jsx(vr,{}),label:"Settings"}];function im({children:t}){const s=bs(),r=fn(),[n,o]=a.useState(!1),[i,c]=a.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),d=m=>{s(m),o(!1)},p=()=>{c(m=>{const h=!m;try{localStorage.setItem("sidebar-collapsed",h?"1":"0")}catch{}return h})},f=m=>`nav-item${r.pathname.startsWith(m)?" active":""} cursor-pointer ${i?"justify-center py-2.5 px-0":""}`;return e.jsxs("div",{className:`app-layout${n?" mobile-menu-open":""}${i?" sidebar-collapsed":""}`,children:[e.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:()=>o(!0),children:[e.jsx("span",{className:"mobile-menu-icon"}),e.jsx("span",{className:"mobile-menu-icon"}),e.jsx("span",{className:"mobile-menu-icon"})]}),n&&e.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:()=>o(!1),onKeyDown:m=>m.key==="Escape"&&o(!1)}),e.jsxs("aside",{className:`sidebar ${n?"sidebar-open":""}`,children:[e.jsxs("div",{className:"sidebar-header",children:[e.jsxs("div",{className:`sidebar-logo ${i?"justify-center gap-0":""}`,children:[e.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&e.jsx("span",{children:"ADHDev"})]}),e.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:()=>o(!1),children:"✕"})]}),e.jsx("nav",{className:"sidebar-nav",children:om.map(m=>e.jsxs("div",{className:f(m.path),id:`nav-${m.id}`,onClick:()=>d(m.path),title:i?m.label:void 0,children:[e.jsx("span",{className:"nav-icon",children:m.icon}),!i&&m.label]},m.id))}),e.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[e.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:[e.jsx("span",{className:"nav-icon",children:e.jsx(to,{})}),!i&&e.jsxs(e.Fragment,{children:["Docs",e.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]})]}),e.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:[e.jsx("span",{className:"nav-icon",children:e.jsx(so,{})}),!i&&"About"]}),!i&&e.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.51"]}),e.jsx(wd,{collapsed:i}),e.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:p,title:i?"Expand sidebar":"Collapse sidebar",children:[e.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&e.jsx("span",{className:"text-xs",children:"Collapse"})]})]})]}),e.jsx("main",{className:"main-content relative",children:e.jsx("div",{className:"main-content-inner",children:t})})]})}const cm=[{icon:e.jsx(Ut,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:e.jsx(Kt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:e.jsx(ro,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:e.jsx(Nt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:e.jsx(Rs,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:e.jsx(to,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],lm=[{icon:e.jsx(oo,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:e.jsx(eo,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:e.jsx(jr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:e.jsx(rc,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:e.jsx(hn,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:e.jsx(ac,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],dm=[{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 um(){return e.jsxs(Eo,{icon:e.jsx(so,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:e.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.51"]}),children:[e.jsx(Pt,{children:e.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[e.jsxs("div",{className:"max-w-2xl",children:[e.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),e.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."}),e.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."})]}),e.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[e.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 ↗"}),e.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 ↗"}),e.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 ↗"})]})]})}),e.jsx(Pt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:e.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:cm.map(t=>e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[e.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:t.icon}),t.title]}),e.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),e.jsx(Pt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:e.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:_o.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:Lo.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:Po.map(t=>`${t.icon} ${t.name}`)}].map(t=>e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[e.jsx("div",{className:"text-[10px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:t.label}),e.jsx("div",{className:"flex flex-col gap-1.5",children:t.items.map(s=>e.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))})]},t.label))})}),e.jsx(Pt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:e.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:lm.map(t=>e.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[e.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:t.icon}),t.title]}),e.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),e.jsx(Pt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:e.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:e.jsxs("table",{className:"w-full text-[13px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-bg-secondary",children:[e.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),e.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),e.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),e.jsx("tbody",{children:dm.map((t,s)=>e.jsxs("tr",{className:s%2===0?"bg-bg-glass":"bg-transparent",children:[e.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:t.feature}),e.jsx("td",{className:"px-4 py-2.5 text-center",children:t.selfhost?e.jsx("span",{className:"text-emerald-500",children:"✓"}):e.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),e.jsx("td",{className:"px-4 py-2.5 text-center",children:e.jsx("span",{className:"text-emerald-500",children:"✓"})})]},t.feature))})]})})}),e.jsx($o,{icon:e.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:e.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[e.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),e.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[e.jsx(yc,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function pm(){const{ides:t}=es(),s=t.find(h=>h.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=St(),{userName:o}=es(),[i,c]=a.useState(o||"");a.useEffect(()=>{o!==void 0&&c(o)},[o]);const d=h=>{const w=h.target.value.trim();s!=null&&s.id&&w!==o&&n(s.id,"set_user_name",{userName:w}).catch(console.error)},[p,f]=a.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),m=h=>{f(h);try{localStorage.setItem("adhdev_sound",h?"1":"0")}catch{}};return e.jsxs(Eo,{icon:e.jsx(vr,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[e.jsx(xd,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost."}),e.jsx(Pt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:e.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[e.jsx("span",{className:"text-text-muted",children:"Version"}),e.jsxs("span",{className:"font-mono text-xs",children:["v","0.8.51"]}),e.jsx("span",{className:"text-text-muted",children:"Status"}),e.jsx("span",{className:s?"text-green-400":"text-yellow-400",children:s?"● Running":"○ Not connected"}),e.jsx("span",{className:"text-text-muted",children:"WebSocket"}),e.jsx("span",{className:"font-mono text-xs",children:"ws://localhost:19222"}),e.jsx("span",{className:"text-text-muted",children:"HTTP"}),e.jsx("span",{className:"font-mono text-xs",children:"http://localhost:19280"})]})}),e.jsx(Pt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?e.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):e.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(h=>e.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${h.running?"bg-green-400":"bg-text-muted/30"}`}),e.jsx("span",{className:"text-sm font-medium",children:h.name})]}),e.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:h.type})]},h.type))})}),e.jsx(Pt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:e.jsx(Sd,{ides:t,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),e.jsx(Pt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode and theme.",children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),e.jsx(Md,{})]}),e.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[e.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),e.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."}),e.jsx($d,{})]}),e.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[e.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),e.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."}),e.jsx(Kd,{})]})]})}),e.jsx(Pt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx(jd,{}),e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(gc,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:p,onChange:m})]})}),e.jsx(Pt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:e.jsx("div",{className:"flex flex-col gap-3",children:e.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:[e.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[e.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(sc,{size:16,className:"text-text-secondary"})," Display Name"]}),e.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),e.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:h=>c(h.target.value),onBlur:d,onKeyDown:h=>{h.key==="Enter"&&h.currentTarget.blur()}})]})})})]})}vd();Dd();const mm=Za({baseUrl:""});function Ga(){const{ides:t,initialLoaded:s}=es();if(!s)return e.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=t.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?e.jsx(sn,{to:`/machines/${r.id}`,replace:!0}):e.jsx(sn,{to:"/dashboard",replace:!0})}function fm(){const t=a.useMemo(()=>({sendCommand:dr,sendData:mn}),[]);return e.jsx(Ui,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:e.jsx(Qi,{client:mm,children:e.jsx(am,{children:e.jsx(tc,{value:t,children:e.jsx(im,{children:e.jsxs(zi,{children:[e.jsx(Ft,{path:"/dashboard",element:e.jsx(Mp,{})}),e.jsx(Ft,{path:"/machine",element:e.jsx(Ga,{})}),e.jsx(Ft,{path:"/machines/:id",element:e.jsx(Xp,{})}),e.jsx(Ft,{path:"/machines",element:e.jsx(Ga,{})}),e.jsx(Ft,{path:"/about",element:e.jsx(um,{})}),e.jsx(Ft,{path:"/settings",element:e.jsx(pm,{})}),e.jsx(Ft,{path:"*",element:e.jsx(sn,{to:"/dashboard",replace:!0})})]})})})})})})}Sl({connectionManager:Et});Fi(document.getElementById("root")).render(e.jsx(fm,{}));