@adhdev/daemon-standalone 1.0.39-rc.7 → 1.0.39-rc.8

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.
@@ -64,9 +64,9 @@ Use this if you want to temporarily stop remote control.`,confirmLabel:o("machin
64
64
  This will:
65
65
  • Immediately disconnect the machine
66
66
  • Delete the machine registration
67
- • Require restarting ADHDev on that machine
67
+ • Require running \`adhdev setup\` again on that machine
68
68
 
69
- Use this if you want to permanently remove a machine.`,confirmLabel:o("machine.connectedMachines.remove"),confirmColor:"red",onConfirm:T,onCancel:()=>m(null)})]})}const VC=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function YC({daemonId:e,knownCliTypes:t=VC}){const{t:n}=Ce("common"),{sendCommand:a}=kt(),[r,o]=l.useState({}),[i,c]=l.useState({}),[d,p]=l.useState(!0),[u,m]=l.useState(null),[h,g]=l.useState(null),[S,f]=l.useState(""),x=l.useCallback(async()=>{if(e){p(!0),g(null);try{const C=await a(e,"list_coordinator_prompts",{}),k=C!=null&&C.result&&typeof C.result=="object"?C.result:C;if(!(k!=null&&k.success)){g((k==null?void 0:k.error)||"Failed to load");return}const y=k.entries||{};f(k.dir||"");const v={};for(const j of t)v[j]=y[j]||{override:"",append:""};for(const j of Object.keys(y))v[j]||(v[j]=y[j]);o(v),c(JSON.parse(JSON.stringify(v)))}catch(C){g((C==null?void 0:C.message)||String(C))}finally{p(!1)}}},[a,e,t]);l.useEffect(()=>{x()},[x]);const w=l.useCallback(async(C,k)=>{var y;if(e){m(`${C}:${k}`),g(null);try{const v=((y=r[C])==null?void 0:y[k])||"",j=await a(e,"write_coordinator_prompt",{key:C,kind:k,content:v}),N=j!=null&&j.result&&typeof j.result=="object"?j.result:j;if(!(N!=null&&N.success)){g((N==null?void 0:N.error)||"Save failed");return}c(A=>({...A,[C]:{...A[C]||{override:"",append:""},[k]:v}}))}catch(v){g((v==null?void 0:v.message)||String(v))}finally{m(null)}}},[a,e,r]),b=l.useMemo(()=>(C,k)=>{var y,v;return(((y=r[C])==null?void 0:y[k])||"")!==(((v=i[C])==null?void 0:v[k])||"")},[r,i]);return e?s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{className:"text-[12px] text-text-muted",children:[s.jsxs("p",{children:["Customize the coordinator prompt this daemon's mesh coordinator sessions get. ",s.jsx("span",{className:"font-mono text-[11px]",children:S||"~/.adhdev/coordinator-prompts/"})]}),s.jsxs("p",{className:"mt-1",children:[s.jsx(pi,{i18nKey:"settings.coordinatorPrompts.overrideDesc",ns:"common",components:{strong:s.jsx("strong",{})}})," ",s.jsx(pi,{i18nKey:"settings.coordinatorPrompts.appendDesc",ns:"common",components:{strong:s.jsx("strong",{})}}),"Leave a field empty + Save to remove it (reset to default). Supports placeholders: ","{{meshName}}",", ","{{repo}}",", ","{{nodes}}",", ","{{rules}}",", etc."]})]}),h&&s.jsx("div",{className:"text-[12px] text-status-error bg-status-error/10 border border-status-error/40 rounded px-3 py-2",children:h}),d&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"Loading…"}),s.jsx("div",{className:"flex flex-col gap-6",children:Object.entries(r).map(([C,k])=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-2",children:C}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:n("settings.coordinatorPrompts.overrideLabel")}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:4,value:k.override,onChange:y=>o(v=>({...v,[C]:{...v[C],override:y.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:u===`${C}:override`}),s.jsx("div",{className:"mt-1 mb-3 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void w(C,"override"),disabled:u===`${C}:override`||!b(C,"override"),children:u===`${C}:override`?"Saving…":b(C,"override")?"Save override":"Saved"})}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:n("settings.coordinatorPrompts.appendLabel")}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:3,value:k.append,onChange:y=>o(v=>({...v,[C]:{...v[C],append:y.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:u===`${C}:append`}),s.jsx("div",{className:"mt-1 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void w(C,"append"),disabled:u===`${C}:append`||!b(C,"append"),children:u===`${C}:append`?"Saving…":b(C,"append")?"Save append":"Saved"})})]},C))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const QC=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function JC(){const{preference:e,setPreference:t}=Xs();return s.jsx("div",{className:"flex gap-2",children:QC.map(n=>s.jsxs("button",{onClick:()=>t(n.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===n.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===n.id?{color:"var(--accent-on-primary)"}:void 0,children:[s.jsx("span",{children:n.icon}),n.label]},n.id))})}function XC(e){const t=e.trim();return/^#[0-9a-fA-F]{6}$/.test(t)?t:/^#[0-9a-fA-F]{3}$/.test(t)?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:null}function ZC(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Ro(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function od(e){const{r:t,g:n,b:a}=ZC(e);return .2126*Ro(t)+.7152*Ro(n)+.0722*Ro(a)}function id(e,t){const n=od(e),a=od(t),r=Math.max(n,a),o=Math.min(n,a);return(r+.05)/(o+.05)}function km(e){const t=XC(e);if(!t)return"#111827";const n="#111827",a="#ffffff";return id(t,n)>=id(t,a)?n:a}const Hi={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},$i={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},ej=[{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"}}}],Sm="adhdev-chat-theme",Cm="adhdev-chat-theme-custom";function fr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Sm)||"ember"}catch{return"ember"}}function us(e){try{const t=localStorage.getItem(Cm);if(t){const n=JSON.parse(t);return{...e==="dark"?Hi:$i,...n[e]}}}catch{}return e==="dark"?Hi:$i}function Qa(e,t){try{localStorage.setItem(Cm,JSON.stringify({dark:e,light:t}))}catch{}}function ts(e,t){const n=parseInt(e.slice(1,3),16),a=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16);return`rgba(${n}, ${a}, ${r}, ${t})`}function $r(e,t){const n=Math.min(255,parseInt(e.slice(1,3),16)+t),a=Math.min(255,parseInt(e.slice(3,5),16)+t),r=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}`}const tj={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function ka(e,t){var r;const n=(r=tj[e])==null?void 0:r[t];if(!n)return;const a=document.documentElement;a.style.setProperty("--accent-primary",n),a.style.setProperty("--accent-primary-light",$r(n,24)),a.style.setProperty("--accent-on-primary",km(n)),a.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${n}, ${$r(n,18)})`),a.style.setProperty("--border-accent",ts(n,.35)),a.style.setProperty("--nav-active-bg",ts(n,.1)),a.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${n}, 0 0 12px ${ts(n,.06)}`)}function un(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",ts(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",ts(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",ts(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",ts(e.borderSubtle,.5)),t.style.setProperty("--border-default",ts(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",$r(e.accentColor,30)),t.style.setProperty("--accent-on-primary",km(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${$r(e.accentColor,40)})`),t.style.setProperty("--border-accent",ts(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",ts(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${ts(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${ts(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function Cl(){const e=document.documentElement;["--bg-primary","--bg-secondary","--bg-card","--surface-primary","--surface-secondary","--bg-glass","--bg-glass-hover","--text-primary","--text-secondary","--text-muted","--border-subtle","--border-default","--accent-primary","--accent-primary-light","--accent-on-primary","--accent-gradient","--border-accent","--nav-active-bg","--nav-active-shadow","--chat-user-bg","--chat-user-color","--chat-user-radius","--chat-assistant-bg","--chat-assistant-color","--chat-assistant-radius","--chat-assistant-border","--chat-container-bg","--dashboard-pane-bg","--chat-thought-accent","--chat-tool-accent","--chat-action-color","--chat-send-bg","--chat-input-border"].forEach(n=>e.style.removeProperty(n))}function sj(e){try{localStorage.setItem(Sm,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=pn()?"dark":"light";un(us(t))}else Cl(),ka(e,pn()?"dark":"light")}function nj(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=fr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=pn()?"dark":"light";un(us(t))}else Cl(),ka(e,pn()?"dark":"light")}function pn(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Ot({label:e,value:t,onChange:n}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:a=>n(a.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,onChange:a=>{/^#[0-9a-fA-F]{0,6}$/.test(a.target.value)&&n(a.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 oa({title:e,children:t}){return s.jsxs("div",{style:{marginBottom:14},children:[s.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:t})]})}function aj({dark:e,onColorsChange:t}){const{t:n}=Ce("common"),a=e?"dark":"light",[r,o]=l.useState(()=>us(a));l.useEffect(()=>{o(us(a))},[a]);const i=l.useCallback((c,d)=>{o(p=>{const u={...p,[c]:d},h=us(a==="dark"?"light":"dark");return a==="dark"?Qa(u,h):Qa(h,u),un(u),t(u),u})},[a,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[n("settings.theme.customEditorTitle"),s.jsx("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:n(e?"settings.theme.darkMode":"settings.theme.lightMode")})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(oa,{title:n("settings.theme.sectionAppBackground"),children:[s.jsx(Ot,{label:n("settings.theme.colorBackground"),value:r.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(Ot,{label:n("settings.theme.colorSurface"),value:r.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(Ot,{label:n("settings.theme.colorCard"),value:r.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(oa,{title:n("settings.theme.sectionAppText"),children:[s.jsx(Ot,{label:n("settings.theme.colorPrimary"),value:r.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(Ot,{label:n("settings.theme.colorSecondary"),value:r.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(Ot,{label:n("settings.theme.colorMuted"),value:r.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(oa,{title:n("settings.theme.sectionBordersAccent"),children:[s.jsx(Ot,{label:n("settings.theme.colorBorderSubtle"),value:r.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(Ot,{label:n("settings.theme.colorBorderDefault"),value:r.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(Ot,{label:n("settings.theme.colorAccent"),value:r.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(oa,{title:n("settings.theme.sectionChatBubbles"),children:[s.jsx(Ot,{label:n("settings.theme.colorUserBubble"),value:r.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(Ot,{label:n("settings.theme.colorUserText"),value:r.userText,onChange:c=>i("userText",c)}),s.jsx(Ot,{label:n("settings.theme.colorAgentBubble"),value:r.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(Ot,{label:n("settings.theme.colorAgentText"),value:r.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(oa,{title:n("settings.theme.sectionChatLayout"),children:[s.jsx(Ot,{label:n("settings.theme.colorChatBg"),value:r.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(Ot,{label:n("settings.theme.colorSendButton"),value:r.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(Ot,{label:n("settings.theme.colorInputBorder"),value:r.inputBorder,onChange:c=>i("inputBorder",c)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:n("settings.theme.labelBubbleRadius")}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.jsx("input",{type:"range",min:4,max:24,value:r.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[r.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?Hi:$i,p=us(e?"light":"dark");e?Qa(c,p):Qa(p,c),o(c),un(c),t(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:n("settings.theme.resetToDefaults")})]})}function rj(){const{t:e}=Ce("common"),[t,n]=l.useState(fr),[a,r]=l.useState(!0),[o,i]=l.useState(()=>us("dark"));l.useEffect(()=>{r(pn());const p=new MutationObserver(()=>{const h=pn();r(h);const g=fr();g==="custom"?un(us(h?"dark":"light")):ka(g,h?"dark":"light")});p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const u=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const h=pn();r(h);const g=fr();g==="custom"?un(us(h?"dark":"light")):ka(g,h?"dark":"light")};return u.addEventListener("change",m),()=>{p.disconnect(),u.removeEventListener("change",m)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?un(us(a?"dark":"light")):(Cl(),ka(t,a?"dark":"light"))},[t,a]),l.useEffect(()=>{i(us(a?"dark":"light"))},[a]);const c=p=>{n(p),sj(p)},d=[...ej,{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 s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:d.map(p=>{const u=t===p.id,m=a?p.preview.dark:p.preview.light,h=p.id==="honey"||p.id==="ember"?"#1a1a1a":p.id==="custom"?o.userText:"#fff";return s.jsxs("button",{onClick:()=>c(p.id),className:"text-left rounded-xl p-3 transition-all",style:{background:u?"var(--bg-glass-hover)":"var(--bg-glass)",border:u?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:u?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[s.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:e("settings.theme.helloHelp")}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.userBubble,color:h},children:e("settings.theme.fixBug")}),s.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:e("settings.theme.onIt")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[u&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:p.id==="custom"?e("settings.theme.customLabel"):p.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:p.description})]})]})]},p.id)})}),t==="custom"&&s.jsx(aj,{dark:a,onColorsChange:p=>i(p)})]})}const jl="adhdev_mobileDashboardMode_v1",Fi="adhdev:mobile-dashboard-mode-change";function Nl(){try{return localStorage.getItem(jl)==="workspace"?"workspace":"chat"}catch{return"chat"}}function oj(e){if(typeof window>"u")return()=>{};const t=r=>{e(r??Nl())},n=r=>{const o=r.detail;t(o)},a=r=>{r.key&&r.key!==jl||t()};return window.addEventListener(Fi,n),window.addEventListener("storage",a),()=>{window.removeEventListener(Fi,n),window.removeEventListener("storage",a)}}function ij(e){try{localStorage.setItem(jl,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Fi,{detail:e}))}function lj(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(Nl()==="chat")},[]),s.jsx(rn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(yn,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:n=>{t(n),ij(n?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const cj="Choose a preset or create a fully custom theme. Custom themes control the entire app — backgrounds, text, borders, and chat bubbles.",dj="Choose whether the dashboard opens like a chat app on phones or keeps the full workspace layout.";function uj({themeDescription:e=cj,mobileDescription:t=dj,fontsSlot:n}){const{t:a}=Ce("common");return s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:a("settings.appearance.modeLabel")}),s.jsx(JC,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:a("settings.appearance.themeLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:e}),s.jsx(rj,{})]}),n,s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:a("settings.appearance.mobileLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:t}),s.jsx(lj,{})]})]})}const Eo=new Map,ld=new Map;function pj(e){if(!e||typeof e!="object")return null;const t=e,n=t.result&&typeof t.result=="object"?t.result:t,a=n.machine;return!a||typeof a!="object"?null:{machine:a,timestamp:typeof n.timestamp=="number"?n.timestamp:void 0}}function mj(e,t,n,a){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:a,platform:n.platform,machine:n}}function jm(){const{sendCommand:e}=kt(),{injectEntries:t,getIdes:n}=ja();return l.useCallback(async(a,r)=>{if(!a)return;const o=(r==null?void 0:r.minFreshMs)??yk,i=ld.get(a)||0;if(!(r!=null&&r.force)&&i>0&&Date.now()-i<o)return;const c=Eo.get(a);if(c)return c;const d=(async()=>{const p=await e(a,"get_machine_runtime_stats"),u=pj(p);if(!u)return;const m=n().find(g=>g.id===a),h=mj(m,a,u.machine,u.timestamp||Date.now());t([h]),ld.set(a,Date.now())})().finally(()=>{Eo.delete(a)});return Eo.set(a,d),d},[n,t,e])}function hj(e,t,n){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:n.timestamp,platform:n.machine.platform,machine:{...(e==null?void 0:e.machine)||{},...n.machine}}}function fj(e,t){const{sendData:n}=kt(),{injectEntries:a,getIdes:r}=ja(),o=Array.from(new Set(e.filter(Boolean))).join("|");l.useEffect(()=>{if(!(t!=null&&t.enabled)||!n)return;const i=o?o.split("|"):[];if(i.length===0)return;const c=i.map(d=>ms.subscribe({sendData:n},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const m=r().find(g=>g.id===d),h=hj(m,d,u);a([h])}));return()=>{c.forEach(d=>d())}},[o,r,a,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,n])}function bj(e,t){const{sendData:n}=kt(),[a,r]=l.useState(null),[o,i]=l.useState(!1);return l.useEffect(()=>{if(!e){r(null),i(!1);return}if(!(t!=null&&t.enabled)||!n){i(!1);return}r(null),i(!0);let c=null;const d=ms.subscribe({sendData:n},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},p=>{c&&(clearTimeout(c),c=null),r(p.diagnostics),i(!1)});return d.initialSendAccepted?c=setTimeout(()=>{i(!1)},Sk):i(!1),()=>{c&&clearTimeout(c),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,n]),{diagnostics:a,loading:o,applyDiagnostics:r}}function gj(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Nm(e){const{sendData:t}=kt(),[n,a]=l.useState({});return l.useEffect(()=>{const r=gj(e);if(!r||!e.sessionId||!t){a({});return}const o=ms.subscribe({sendData:t},r,{type:"subscribe",topic:"session.modal",key:`daemon:${r}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},i=>{a({status:i.status,modalMessage:i.modalMessage,modalButtons:i.modalButtons}),_n.record({interactionId:i.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:i.status,modalButtonCount:Array.isArray(i.modalButtons)?i.modalButtons.length:0}})});return o.initialSendAccepted||a({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),n}function xj(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function vj(e){const t=(e==null?void 0:e.result)??e;return typeof(t==null?void 0:t.error)=="string"?t.error:"Interactive prompt response failed"}async function yj(e,t,n){const a=await n(`/api/v1/sessions/${encodeURIComponent(e)}/interactive-prompt/resolve`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!a.ok){let r=`HTTP ${a.status}`;try{const o=await a.json();typeof(o==null?void 0:o.error)=="string"&&(r=o.error)}catch{}throw new Error(r)}}async function wj({promptSession:e,response:t,useP2PCommand:n,sendCommand:a,fetchImpl:r=fetch}){if(n){const o=await a(e.routeId,"interactive_prompt_response",{targetSessionId:e.sessionId,sessionId:e.sessionId,response:t});if(!xj(o))throw new Error(vj(o));return}await yj(e.sessionId,t,r)}function Am(e){const{ides:t,isP2PActive:n,p2pStates:a}=Ts(),{sendCommand:r}=kt(),[o,i]=l.useState(null),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useRef(!1),h=l.useMemo(()=>ug(t,e),[t,e]),g=!!h,S=l.useMemo(()=>h?h.prompt.promptId===o?null:h:null,[o,h]),f=l.useCallback(async b=>{if(!S||m.current)return;m.current=!0;const C=Qu(S.prompt,b);d(!0),u(null);try{const k=(a==null?void 0:a[S.daemonId])==="connected"||n===!0;await wj({promptSession:S,response:C,useP2PCommand:k,sendCommand:r}),i(S.prompt.promptId)}catch(k){throw u(k instanceof Error?k.message:String(k)),k}finally{d(!1),m.current=!1}},[n,a,S,r]),x=l.useCallback(()=>{S&&i(S.prompt.promptId)},[S]),w=l.useCallback(()=>{i(null),u(null)},[]);return{promptSession:S,hasActivePrompt:g,responseError:p,isSubmitting:c,submit:f,cancel:x,reopen:w}}function Tm(e){return e instanceof Error?e.message:String(e||"")}function kj(e){const t=Tm(e);return t.includes("P2P command timeout")||t.includes("P2P not connected")||t.includes("P2P channel not open")||t.includes("P2P not available")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}function Sj(e){const t=Tm(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Mm({conversation:e,mode:t,ides:n,sendDaemonCommand:a,setCliViewModeOverrides:r}){if(!e||!ht(e)||pt(e))return;const o=Yn(e);if(o===t)return;const i=e.sessionId;i&&r(c=>({...c,[i]:t}));try{await a(Bs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:As(e),mode:t})}catch(c){const d=Sj(c);i&&!d&&r(p=>{const u={...p};return o===jj(n,i)?delete u[i]:u[i]=o,u}),kj(c)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",c instanceof Error?c.message:String(c)):console.error("Failed to switch CLI view mode:",c)}}function cd(e,t){const n=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!n||e.transport!=="pty")return e;const a=t[n];return!a||e.mode===a?e:{...e,mode:a}}function Cj(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let n=!1;const a=e.map(r=>{const o=cd(r,t),i=Array.isArray(r.childSessions)?r.childSessions.map(d=>cd(d,t)):r.childSessions,c=i!==r.childSessions;return o!==r||c?(n=!0,{...o,...c?{childSessions:i}:{}}):r});return n?a:e}function jj(e,t){if(!t)return null;for(const n of e){if(n.sessionId===t&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal";for(const a of n.childSessions||[])if(a.id===t&&a.transport==="pty")return a.mode==="chat"?"chat":"terminal"}return null}function Nj({visibleConversations:e,clearedTabs:t,setClearedTabs:n,setActionLogs:a,isConversationMuted:r}){l.useEffect(()=>{pp()},[]);const o=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:Zp(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null,target:{providerSessionId:i.providerSessionId,sessionId:i.sessionId,tabKey:i.tabKey,routeId:i.routeId},muted:r?r(i):!1})),[e,r]);return Ow(o),l.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{n(d=>{const p=Date.now(),u={};for(const[m,h]of Object.entries(d))p-h<5e3&&(u[m]=h);return Object.keys(u).length===Object.keys(d).length?d:u})},5500);return()=>clearTimeout(c)},[t,n]),l.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;a(d=>{const p=d.filter(u=>u.timestamp>c).slice(-100);return p.length===d.length?d:p})},6e4);return()=>clearInterval(i)},[a]),null}function dd(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function mn(e){const t=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1],n=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,a=dd(t==null?void 0:t.receivedAt)||dd(t==null?void 0:t.timestamp)||0;return Math.max(n,a)}function Bi(e,t=0){return mn(e)||e.lastUpdated||t||0}function Dm(e){return mn(e)||e.lastUpdated||0}function Pm(e,t,n=Dm){const a=n(t)-n(e);if(a!==0)return a;const r=(e.machineName||"").localeCompare(t.machineName||"");if(r!==0)return r;const o=e.displayPrimary.localeCompare(t.displayPrimary);if(o!==0)return o;const i=e.displaySecondary.localeCompare(t.displaySecondary);return i!==0?i:e.tabKey.localeCompare(t.tabKey)}function Wi(e){var n;const t=ns(e.status,{activeModal:(n=e.modalButtons)!=null&&n.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function Aj(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!Wi(e)&&!e.title.trim()}function Tj(e){return e.length===0?null:[...e].sort((t,n)=>{const a=Number(Wi(n))-Number(Wi(t));if(a!==0)return a;const r=n.messages.length-t.messages.length;return r!==0?r:Pm(t,n)})[0]||null}function hs(e,t){const n=e.filter(i=>i.routeId===t);if(n.length===0)return null;const a=n.find(i=>i.streamSource==="native")||null,r=n.filter(i=>i.streamSource==="agent-stream"),o=Tj(r);return a?o&&Aj(a)?o:a:o||n[0]||null}function Mj(e){const t=e.filter(r=>r.type!=="adhdev-daemon"),n=new Set;for(const r of t){if(!Ni(r))continue;const o=op(r);o&&n.add(o)}const a=new Map;for(const r of t){const o=vw(r,n),i=a.get(o);if(!i){a.set(o,r);continue}const c=m=>(m.workspace?1:0)+(m.activeChat?1:0)+(m.lastMessagePreview?1:0),d=c(i),p=c(r),u=p>d||p===d&&(r.timestamp||0)>(i.timestamp||0)?r:i;a.set(o,Dj(u,u===r?i:r))}return Array.from(a.values())}function Dj(e,t){const n=Ni(t),a=Ni(e);if(!n&&!a)return e;const r=a?n?void 0:t:e,o=a?e:n?t:void 0,i=r&&String(r.daemonId||"").trim()||String(e.ownerDaemonId||"").trim()||String(t.ownerDaemonId||"").trim()||void 0,c=String(e.ownerMachineName||"").trim()||String(t.ownerMachineName||"").trim()||void 0,d=o==null?void 0:o.settings;return{...e,...i&&{ownerDaemonId:i},...c&&!e.ownerMachineName&&{ownerMachineName:c},...d&&!a&&{settings:{...d,...e.settings??{}}}}}function _o(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function Pj(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function ud(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],n=t[t.length-1],a=n?Pj(Hn(n.content)):"";return[e.id||"",e.title||"",e.status||"",t.length,String((n==null?void 0:n.id)||""),String((n==null?void 0:n.index)??""),String((n==null?void 0:n.receivedAt)??(n==null?void 0:n.timestamp)??""),a].join(":")}function Ij(e){const t=Array.isArray(e.childSessions)?e.childSessions:[];return[e.id,e.sessionId||"",e.providerSessionId||"",e.transport||"",e.mode||"",e.status||"",e.workspace||"",e.lastMessageHash||"",String(e.lastMessageAt||""),e.lastMessagePreview||"",e.lastMessageRole||"",String(e.lastUpdated||""),ud(e.activeChat),...t.map(n=>[n.id||"",n.providerSessionId||"",n.transport||"",n.mode||"",n.status||"",n.title||"",n.lastMessageHash||"",String(n.lastMessageAt||""),n.lastMessagePreview||"",n.lastMessageRole||"",String(n.lastUpdated||""),ud(n.activeChat)].join(":"))].join("|")}function Lj(e,t){const n=Date.now();return e.map(a=>{const r=t[a.tabKey];return r&&n-r<5e3?{...a,messages:[],title:""}:a})}function Rj(e,t){const n=new Map;for(const a of e){const r=t.get(a.routeId)||a;for(const o of xa({routeId:a.routeId}))n.set(o,r);for(const o of xa({providerSessionId:a.providerSessionId,sessionId:a.sessionId}))n.set(o,a.streamSource==="native"?r:a);for(const o of xa({tabKey:a.tabKey}))n.set(o,a)}return n}function Ej(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function _j(e){const t=Ej(e);if(!t)return`empty:${e.messages.length}`;if(t.id)return`id:${String(t.id)}`;if(t._localId)return`local:${String(t._localId)}`;const n=String(t.role||""),a=Hn(t.content).slice(0,240);return`${e.messages.length}:${n}:${a}`}function Hj({ides:e,connectionStates:t,clearedTabs:n}){const a=l.useMemo(()=>Mj(e),[e]),r=l.useMemo(()=>Zu(e),[e]),o=l.useMemo(()=>dm(e),[e]),i=l.useRef([]),c=l.useRef([]),d=l.useRef([]),p=l.useRef(new Map),u=l.useRef(new Map),m=l.useMemo(()=>{const k=new Map,y=[];for(const A of a){const{connectionState:T="new",machineName:P}=um(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),M=Ij(A),D=p.current.get(A.id);if(D&&D.ide===A&&D.sourceSignature===M&&D.connectionState===T&&D.machineName===P){k.set(A.id,D),y.push(...D.conversations);continue}const L=kl(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),O={ide:A,sourceSignature:M,connectionState:T,machineName:P,conversations:L};k.set(A.id,O),y.push(...L)}p.current=k;const v=new Map,j=A=>{const T=_j(A),P=u.current.get(A.tabKey);if(P&&P.signature===T)return v.set(A.tabKey,P),P.timestamp;const M={signature:T,timestamp:Dm(A)||(P==null?void 0:P.timestamp)||0};return v.set(A.tabKey,M),M.timestamp},N=[...y].sort((A,T)=>Pm(A,T,j));return u.current=v,N},[a,t,o]),h=l.useMemo(()=>{const k=Lj(m,n);return _o(i.current,k)?i.current:(i.current=k,k)},[m,n]),g=l.useMemo(()=>{const k=new Map,y=Array.from(new Set(h.map(v=>v.routeId)));for(const v of y){const j=hs(h,v);j&&k.set(v,j)}return k},[h]),S=l.useMemo(()=>{const k=new Map;for(const y of h){const v=g.get(y.routeId),j=y.streamSource==="native"&&v?v:y;for(const N of xa({providerSessionId:y.providerSessionId,sessionId:y.sessionId,tabKey:y.tabKey}))k.set(N,j)}return k},[h,g]),f=l.useMemo(()=>Rj(h,g),[h,g]),x=l.useCallback(k=>{if(k)return S.get(k)},[S]),w=l.useCallback(k=>{if(k)return f.get(k)},[f]),b=l.useMemo(()=>{const k=h.filter(y=>!Js(y,r).surfaceHidden);return _o(c.current,k)?c.current:(c.current=k,k)},[h,r]),C=l.useMemo(()=>{const k=b.map(y=>y.tabKey);return _o(d.current,k)?d.current:(d.current=k,k)},[b]);return{chatIdes:a,conversations:h,visibleConversations:b,visibleTabKeys:C,resolveConversationBySessionId:x,resolveConversationByTarget:w}}function $j({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:n,setSearchParams:a}){const r=l.useMemo(()=>{var c;return e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),o=l.useMemo(()=>{var c;return!e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),i=l.useCallback(()=>{t&&a(c=>{const d=new URLSearchParams(c);return d.delete("activeTab"),d},{replace:!0})},[a,t]);return{requestedDesktopTabKey:r,requestedMobileTabKey:o,consumeRequestedActiveTab:i}}function Fj({ides:e,sendDaemonCommand:t,setToasts:n,resolveConversationByTarget:a}){l.useEffect(()=>{ft.setIdes(e)},[e]),l.useEffect(()=>{ft.setResolveAction((r,o,i)=>{t(r,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const r=ft.onToast(o=>{n(c=>c.some(p=>p.message===o.message&&o.timestamp-p.timestamp<3e3)?c:[...c.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const i=o.duration||5e3;setTimeout(()=>n(c=>c.filter(d=>d.id!==o.id)),i)});return()=>{r()}},[n]),l.useEffect(()=>{const r=Yp.on("status_event",o=>{ft.handleRawEvent(o,"ws")});return()=>{r()}},[]),l.useEffect(()=>{var o;const r=i=>{var f;const c=i.data;if((c==null?void 0:c.type)!=="notification_action"||typeof c.action!="string"||!c.action.startsWith("approval_")||!(c.daemonId||c.targetSessionId||c.targetKey))return;const d=c.targetSessionId||c.targetKey||c.daemonId,p=a(d),u=(p==null?void 0:p.routeId)||c.daemonId;if(!u)return;const m=Number(c.buttonIndex),h=c.button||((f=p==null?void 0:p.modalButtons)==null?void 0:f[m])||"Approve",g=String(h).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),S=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(g);t(u,"resolve_action",{action:S?"approve":"reject",button:h,...Number.isFinite(m)&&{buttonIndex:m},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(x=>console.error("[SW Action] approval failed:",x))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",r),()=>{var i;return(i=navigator.serviceWorker)==null?void 0:i.removeEventListener("message",r)}},[a,t])}const Bj="adhdev_dashboardLayout_v1",Wj="adhdev_dashboardDockview_v1",Oj="adhdev_dashboardDockviewHiddenRestore_v1",ia={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Al(e,t){try{const n=localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}}function Uj(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Im(e){return`${Bj}:${e}`}function qj(e){const t=Im(e);return Al(t,null)}function Gj(e,t){try{const n=t.groupAssignments.length===0&&t.focusedGroup===0&&Object.keys(t.groupActiveTabIds).length===0&&Object.keys(t.groupTabOrders).length===0&&t.groupSizes.length===0,a=Im(e);if(n){localStorage.removeItem(a);return}localStorage.setItem(a,JSON.stringify(t))}catch{}}function Lm(e){return`${Wj}:${e}`}function zj(e){const t=Lm(e);return Al(t,null)}function Kj(e,t){try{const n=Lm(e);if(!t){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Rm(e){return`${Oj}:${e}`}function Vj(e){const t=Rm(e);return Al(t,{})}function Yj(e,t){try{const n=Rm(e);if(Object.keys(t).length===0){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Qj(){return{groupAssignments:[...ia.groupAssignments],focusedGroup:ia.focusedGroup,groupActiveTabIds:{...ia.groupActiveTabIds},groupTabOrders:{...ia.groupTabOrders},groupSizes:[...ia.groupSizes]}}function Jj(e,t){return e?e.length===t.length&&e.every((n,a)=>n===t[a]):t.length===0}function Xj(){const[e]=l.useState(()=>Uj(typeof window<"u"?window.innerWidth:1280)),[t,n]=l.useState(()=>new Map),[a,r]=l.useState(0),[o,i]=l.useState({}),[c,d]=l.useState({}),[p,u]=l.useState([]),[m,h]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[g,S]=l.useState(!1),f=l.useCallback(()=>{if(g)return;const A=qj(e)??Qj();n(new Map(A.groupAssignments)),r(A.focusedGroup),i(A.groupActiveTabIds),d(A.groupTabOrders),u(A.groupSizes),S(!0)},[g,e]);l.useEffect(()=>{g&&Gj(e,{groupAssignments:[...t.entries()],focusedGroup:a,groupActiveTabIds:o,groupTabOrders:c,groupSizes:p})},[g,e,t,a,o,c,p]),l.useEffect(()=>{const A=window.matchMedia("(max-width: 767px)"),T=P=>h(P.matches);return A.addEventListener("change",T),()=>A.removeEventListener("change",T)},[]);const x=l.useCallback(A=>{n(A)},[]),w=l.useCallback(A=>{r(A)},[]),b=l.useCallback(A=>{i(A)},[]),C=l.useCallback(A=>{d(A)},[]),k=l.useCallback(A=>{u(A)},[]),y=l.useCallback(A=>{w(A)},[w]),v=l.useCallback((A,T)=>{i(P=>(P[A]??null)===(T??null)?P:{...P,[A]:T})},[]),j=l.useCallback((A,T)=>{d(P=>{const M=P[A];return Jj(M,T)?P:{...P,[A]:T}})},[]),N=l.useCallback((A,T)=>{const P=T.get(A)??0;return v(P,A),y(P),P},[y,v]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:x,focusedGroup:a,updateFocusedGroup:w,focusGroup:y,groupActiveTabIds:o,updateGroupActiveTabIds:b,setGroupActiveTab:v,groupTabOrders:c,updateGroupTabOrders:C,setGroupTabOrder:j,groupSizes:p,updateGroupSizes:k,isMobile:m,hasHydratedStoredLayout:g,hydrateStoredLayout:f,focusConversationTab:N}}function Zj(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0],a=Yr(t);return typeof(n==null?void 0:n.id)=="string"&&a.includes(n.id)}function e1({urlActiveTab:e,conversations:t,resolveConversationBySessionId:n,normalizedGroupAssignments:a,hasHydratedStoredLayout:r,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:c,historyModalOpen:d,activeConv:p,isRefreshingHistory:u,ides:m,handleRefreshHistory:h}){const g=l.useRef(!1),S=l.useRef(!1),f=l.useRef(null),x=l.useRef(!1);l.useEffect(()=>{if(!e||g.current||t.length===0)return;if(!r){o();return}const w=n(e);w&&(i(w.tabKey,a),g.current=!0,S.current=!0,f.current!=null&&(window.clearTimeout(f.current),f.current=null),c(b=>{const C=new URLSearchParams(b);return C.delete("activeTab"),C},{replace:!0}))},[e,t,n,a,r,o,i,c]),l.useEffect(()=>{if(!(S.current||r)&&t.length!==0){if(!e){o(),S.current=!0;return}if(g.current){S.current=!0;return}if(f.current==null)return f.current=window.setTimeout(()=>{f.current=null,!(S.current||r)&&(o(),S.current=!0)},1500),()=>{f.current!=null&&(window.clearTimeout(f.current),f.current=null)}}},[e,t.length,r,o]),l.useEffect(()=>{if(!d){x.current=!1;return}if(!p||x.current||u)return;const w=m.find(b=>b.id===p.routeId);w&&(!w.chats||w.chats.length===0||Zj(w.chats,p))&&(x.current=!0,h())},[d,p,u,m,h])}function Ho(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0];if((n==null?void 0:n.active)===!0)return!0;const a=Yr(t);return typeof(n==null?void 0:n.id)=="string"&&a.includes(n.id)}function Em({sendDaemonCommand:e,activeConv:t,chats:n,updateRouteChats:a,setToasts:r,setClearedTabs:o}){const[i,c]=l.useState(!1),[d,p]=l.useState(!1),u=l.useCallback(async S=>{try{await e("standalone","launch_ide",{ideType:S,enableCdp:!0})}catch(f){console.error("Launch failed",f)}},[e]),m=l.useCallback(async(S,f)=>{try{const x=S||(t==null?void 0:t.daemonId)||"",w=await e(x,"switch_chat",{id:f,sessionId:f,...ln(t)}),b=w==null?void 0:w.result;if((w==null?void 0:w.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?Tn(r,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?Tn(r,`⚠️ Switch error: ${b}`):Tn(r,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),Tn(r,`❌ Switch failed: ${x.message||"connection error"}`)}},[t,e,r]),h=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const S=cn(t);await e(S,"new_chat",{...ln(t)}),Ok(S,t.sessionId,Yr(t)[0]),o(f=>({...f,[t.tabKey]:Date.now()}))}catch(S){console.error("New chat failed",S)}finally{c(!1)}}},[t,i,e,o]),g=l.useCallback(async()=>{var S,f;if(!(!t||d)){p(!0);try{const x=cn(t),w=async()=>e(x,"list_chats",{forceExpand:!0,...ln(t)});let b=await w(),C=(b==null?void 0:b.chats)||((S=b==null?void 0:b.result)==null?void 0:S.chats);Ho(C,t)&&(await new Promise(k=>setTimeout(k,450)),b=await w(),C=(b==null?void 0:b.chats)||((f=b==null?void 0:b.result)==null?void 0:f.chats)),b!=null&&b.success&&Array.isArray(C)&&(a(t.routeId,C),Ho(C,t)&&!Ho(n,t)&&Tn(r,"⚠️ History dialog did not fully open — try once more"))}catch(x){console.error("Refresh history failed",x)}finally{p(!1)}}},[t,n,d,e,a,r]);return{isCreatingChat:i,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:m,handleNewChat:h,handleRefreshHistory:g}}function t1(e,t){if(e.size!==t.size)return!1;for(const[n,a]of e)if(t.get(n)!==a)return!1;return!0}function s1(e,t){return e.length!==t.length?!1:e.every((n,a)=>n===t[a])}function pd(e,t){const n=Object.keys(e),a=Object.keys(t);return n.length!==a.length?!1:n.every(r=>t[Number(r)]===e[Number(r)])}function Ja(e,t){const n=new Set(t),a=t.length>0?[0]:[];for(const[i,c]of e)!n.has(i)||c<=0||a.includes(c)||a.push(c);a.sort((i,c)=>i-c);const r={};a.forEach((i,c)=>{r[i]=c}),a.length===0&&(r[0]=0);const o=new Map;for(const[i,c]of e){if(!n.has(i)||c<=0)continue;const d=r[c];typeof d=="number"&&d>0&&o.set(i,d)}return{assignments:o,groupCount:Math.max(1,a.length),mapping:r,usedGroups:a}}function md(e,t){const n={};for(const[a,r]of Object.entries(e)){const o=t[Number(a)];typeof o=="number"&&(n[o]=r)}return n}function n1(e,t,n){if(t.length===0)return 0;if(typeof n[e]=="number")return n[e];const a=[...t].reverse().find(r=>r<e)??t[0];return n[a]??0}function a1(e,t,n){if(t.length<=1)return[];const a=t.map(i=>e[i]).filter(i=>Number.isFinite(i)),r=a.length===t.length?a:Array(n).fill(100/n),o=r.reduce((i,c)=>i+c,0);return o>0?r.map(i=>i/o*100):Array(n).fill(100/n)}function hd(e,t){const n={};for(const[a,r]of Object.entries(e)){const o=Number(a);n[o>=t?o+1:o]=r}return n}function fd(e){return Array(e).fill(100/e)}function r1({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:n,updateGroupActiveTabIds:a,updateGroupTabOrders:r,groupSizes:o,updateGroupSizes:i,isMobile:c,visibleConversations:d,visibleTabKeys:p}){const u=l.useRef(null),m=l.useMemo(()=>Ja(e,p),[e,p]),h=m.assignments,g=l.useMemo(()=>c?1:m.groupCount,[m.groupCount,c]),S=g>1,f=l.useCallback((y,v)=>{t(j=>{const N=new Map(Ja(j,p).assignments);return v===0?N.delete(y):N.set(y,v),N}),a(j=>({...j,[v]:y})),n(v)},[t,p,a,n]),x=l.useCallback(y=>{t(v=>{const j=Ja(v,p).assignments,N=new Map;for(const[A,T]of j)T!==y&&(T>y?N.set(A,T-1):N.set(A,T));return N}),i(v=>{if(v.length<=1)return[];const j=[...v];j.splice(y,1);const N=j.reduce((A,T)=>A+T,0);return N>0?j.map(A=>A/N*100):[]}),n(0)},[t,p,i,n]),w=l.useCallback((y,v)=>{v.preventDefault();const j=u.current;if(!j)return;const N=v.clientX,A=j.offsetWidth,T=o.length===g?[...o]:fd(g),P=D=>{const O=(D.clientX-N)/A*100,E=[...T];E[y]=Math.max(15,T[y]+O),E[y+1]=Math.max(15,T[y+1]-O),i(E)},M=()=>{document.removeEventListener("mousemove",P),document.removeEventListener("mouseup",M),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",P),document.addEventListener("mouseup",M)},[o,g,i]),b=l.useCallback((y,v,j)=>{if(g>=4)return;const N=j==="left"?v:v+1;t(A=>{const T=Ja(A,p).assignments,P=new Map;for(const M of d){const D=T.get(M.tabKey)??0,L=D>=N?D+1:D;L>0&&P.set(M.tabKey,L)}return N>0&&P.set(y,N),P}),i(A=>{const T=A.length===g?[...A]:fd(g),P=T[v]??100/g,M=Math.max(15,P/2),D=Math.max(15,P/2),L=[...T];L[v]=M,L.splice(N,0,D);const O=L.reduce((E,I)=>E+I,0);return L.map(E=>E/O*100)}),a(A=>{const T=hd(A,N);return T[N]=y,T}),r(A=>{const T=hd(A,N);return T[N]=[y],T}),n(N)},[g,t,p,d,i,a,r,n]);l.useEffect(()=>{t1(e,h)||t(h)},[e,h,t]),l.useEffect(()=>{const{mapping:y,usedGroups:v}=m;a(j=>{const N=md(j,y);return pd(j,N)?j:N}),r(j=>{const N=md(j,y);return pd(j,N)?j:N}),n(j=>{const N=c?0:n1(j,v,y);return j===N?j:N}),i(j=>{const N=c?[]:a1(j,v,m.groupCount);return s1(j,N)?j:N})},[m,c,a,r,n,i]);const C=l.useMemo(()=>{const y=Array.from({length:g},()=>[]);for(const v of d){const j=h.get(v.tabKey)??0,N=Math.min(j,g-1);y[N].push(v)}return y},[d,h,g]),k=l.useCallback(()=>{t(new Map),n(0)},[t,n]);return{containerRef:u,normalizedGroupAssignments:h,numGroups:g,isSplitMode:S,groupedConvs:C,moveTabToGroup:f,closeGroup:x,handleResizeStart:w,splitTabRelative:b,clearAllSplits:k}}function o1({ides:e,sendDaemonCommand:t}){const n="1.0.38",a=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:no(m,qs(m,n))).sort((m,h)=>Number(wa(h,qs(h,n)))-Number(wa(m,qs(m,n)))),[n,e]),r=l.useMemo(()=>a.some(m=>wa(m,qs(m,n))),[n,a]),o=l.useMemo(()=>a.map(m=>qs(m,n)).find(m=>typeof m=="string"&&m.trim().length>0)||n,[n,a]),[i,c]=l.useState(!1),[d,p]=l.useState({}),u=l.useCallback(async m=>{var S,f;const h=e.find(x=>x.id===m);if(!h)return;p(x=>({...x,[m]:"upgrading"}));const g=ao(h);if(!g){p(x=>({...x,[m]:"error"}));return}try{const x=await t(m,"daemon_upgrade",g);(S=x==null?void 0:x.result)!=null&&S.upgraded||(f=x==null?void 0:x.result)!=null&&f.success?p(w=>({...w,[m]:"done"})):p(w=>({...w,[m]:"error"}))}catch{p(x=>({...x,[m]:"error"}))}},[e,t]);return{versionMismatchDaemons:a,hasRequiredVersionDaemons:r,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:u}}const _m=80;function br(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function i1(e){return{...e,createdAt:br(e.createdAt),updatedAt:br(e.updatedAt,e.createdAt),lastEventAt:br(e.lastEventAt,e.updatedAt||e.createdAt)}}function l1(e){const t=rp(e);return t==="unknown:"?e.id:t}function c1(e){return[e.type,ap(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function d1(e,t=_m){const n=new Map;for(const a of e){if(a.deletedAt)continue;const r=l1(a),o=n.get(r);if(!o){n.set(r,a);continue}(a.updatedAt>o.updatedAt||a.updatedAt===o.updatedAt&&a.createdAt>o.createdAt)&&n.set(r,a)}return Array.from(n.values()).sort((a,r)=>{const o=r.updatedAt-a.updatedAt;return o!==0?o:r.createdAt-a.createdAt}).slice(0,Math.max(0,t))}function u1(e,t){const n=Date.now(),a=[];for(const r of e){const o=r.sessionId?t.get(r.sessionId):void 0;if(o!=null&&o.surfaceHidden||o!=null&&o.muted)continue;const i=Vr(r,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const d=br(r.lastMessageAt||(o==null?void 0:o.lastUpdated)||r.lastUpdated,n),p=c1({type:c,sessionId:r.sessionId,providerSessionId:r.providerSessionId,tabKey:r.tabKey,lastMessageHash:r.lastMessageHash,lastMessageAt:r.lastMessageAt,lastUpdated:(o==null?void 0:o.lastUpdated)||r.lastUpdated});a.push(i1({id:p,dedupKey:p,type:c,routeId:r.routeId,machineId:r.daemonId||r.routeId,sessionId:r.sessionId,providerSessionId:r.providerSessionId,tabKey:r.tabKey,title:Np(r),preview:ek(r),createdAt:d,updatedAt:d,lastEventAt:d}))}return d1(a)}function p1(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function m1(e){const{conversations:t,liveSessionInboxState:n,maxItems:a=_m}=e,r=l.useMemo(()=>u1(t,n).slice(0,Math.max(0,a)),[t,n,a]),o=l.useMemo(()=>p1(r),[r]);return{notifications:r,unreadCount:o}}function h1({notifications:e,sendDaemonCommand:t}){const n=l.useCallback(o=>{const i=e.find(d=>d.id===o),c=Math.max(Date.now(),(i==null?void 0:i.updatedAt)||0);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_session_seen",{sessionId:i.sessionId,seenAt:c}).catch(()=>{})},[e,t]),a=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_notification_unread",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]),r=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"delete_notification",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:n,handleMarkDashboardNotificationUnread:a,handleDeleteDashboardNotification:r}}function Tl(...e){const t=new Set,n=[],a=r=>{const o=typeof r=="string"?r.trim():"";if(!o)return;const i=o.toLowerCase();t.has(i)||(t.add(i),n.push(o))};for(const r of e){if(Array.isArray(r)){for(const o of r)a(o);continue}a(r)}return n}function f1(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const n=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(n){const a=n[1].toUpperCase(),r=(n[2]||"").replace(/[\\/]+/g,"\\");return r?`${a}:\\${r}`:`${a}:\\`}return null}function Ml(e,t=[]){if(e==="win32"){for(const n of t){if(typeof n!="string")continue;const a=f1(n);if(a)return a}return"C:\\"}for(const n of t){const a=typeof n=="string"?n.trim():"";if(a)return a}return"~"}function b1(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const n=t.includes("\\")?"\\":"/",a=t.split(/[\\/]/);return/^[A-Za-z]:$/.test(a[0]||"")?a.length<=2?`${a[0]}\\`:a.slice(0,-1).join("\\"):a.length<=2?n:a.slice(0,-1).join(n)||n}function g1(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Dl(e,t,n){const a=await e(t,"file_list_browse",{path:n}),r=g1(a);if(!(r!=null&&r.success))throw new Error((r==null?void 0:r.error)||(a==null?void 0:a.error)||"Could not browse folder");const o=typeof(r==null?void 0:r.path)=="string"?r.path:n,i=o.includes("\\")?"\\":"/",c=(p,u)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${u}`:p==="/"||p==="\\"?`${i}${u}`:`${p.replace(/[\\/]+$/,"")}${i}${u}`,d=Array.isArray(r==null?void 0:r.files)?r.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:typeof(p==null?void 0:p.path)=="string"&&p.path.trim()?p.path:c(o,p.name)})).sort((p,u)=>p.name.localeCompare(u.name)):[];return{path:o,directories:d}}function bd(e,t){const n=t.meshId||"",a={meshId:n,workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp",adhdevMcpArgs:t.adhdevMcpArgs||`mcp --mode ipc --repo-mesh ${n}`};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand|adhdevMcpArgs)\s*\}\}/g,(r,o)=>a[o]||"")}function Hm(e,t={}){const n=e==null?void 0:e.mcpConfig;if((n==null?void 0:n.mode)!=="manual")return null;const r=bd(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"}).trim();return!r.includes(`
69
+ The machine's IDE, workspace and provider settings are kept.`,confirmLabel:o("machine.connectedMachines.remove"),confirmColor:"red",onConfirm:T,onCancel:()=>m(null)})]})}const VC=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function YC({daemonId:e,knownCliTypes:t=VC}){const{t:n}=Ce("common"),{sendCommand:a}=kt(),[r,o]=l.useState({}),[i,c]=l.useState({}),[d,p]=l.useState(!0),[u,m]=l.useState(null),[h,g]=l.useState(null),[S,f]=l.useState(""),x=l.useCallback(async()=>{if(e){p(!0),g(null);try{const C=await a(e,"list_coordinator_prompts",{}),k=C!=null&&C.result&&typeof C.result=="object"?C.result:C;if(!(k!=null&&k.success)){g((k==null?void 0:k.error)||"Failed to load");return}const y=k.entries||{};f(k.dir||"");const v={};for(const j of t)v[j]=y[j]||{override:"",append:""};for(const j of Object.keys(y))v[j]||(v[j]=y[j]);o(v),c(JSON.parse(JSON.stringify(v)))}catch(C){g((C==null?void 0:C.message)||String(C))}finally{p(!1)}}},[a,e,t]);l.useEffect(()=>{x()},[x]);const w=l.useCallback(async(C,k)=>{var y;if(e){m(`${C}:${k}`),g(null);try{const v=((y=r[C])==null?void 0:y[k])||"",j=await a(e,"write_coordinator_prompt",{key:C,kind:k,content:v}),N=j!=null&&j.result&&typeof j.result=="object"?j.result:j;if(!(N!=null&&N.success)){g((N==null?void 0:N.error)||"Save failed");return}c(A=>({...A,[C]:{...A[C]||{override:"",append:""},[k]:v}}))}catch(v){g((v==null?void 0:v.message)||String(v))}finally{m(null)}}},[a,e,r]),b=l.useMemo(()=>(C,k)=>{var y,v;return(((y=r[C])==null?void 0:y[k])||"")!==(((v=i[C])==null?void 0:v[k])||"")},[r,i]);return e?s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{className:"text-[12px] text-text-muted",children:[s.jsxs("p",{children:["Customize the coordinator prompt this daemon's mesh coordinator sessions get. ",s.jsx("span",{className:"font-mono text-[11px]",children:S||"~/.adhdev/coordinator-prompts/"})]}),s.jsxs("p",{className:"mt-1",children:[s.jsx(pi,{i18nKey:"settings.coordinatorPrompts.overrideDesc",ns:"common",components:{strong:s.jsx("strong",{})}})," ",s.jsx(pi,{i18nKey:"settings.coordinatorPrompts.appendDesc",ns:"common",components:{strong:s.jsx("strong",{})}}),"Leave a field empty + Save to remove it (reset to default). Supports placeholders: ","{{meshName}}",", ","{{repo}}",", ","{{nodes}}",", ","{{rules}}",", etc."]})]}),h&&s.jsx("div",{className:"text-[12px] text-status-error bg-status-error/10 border border-status-error/40 rounded px-3 py-2",children:h}),d&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"Loading…"}),s.jsx("div",{className:"flex flex-col gap-6",children:Object.entries(r).map(([C,k])=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-2",children:C}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:n("settings.coordinatorPrompts.overrideLabel")}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:4,value:k.override,onChange:y=>o(v=>({...v,[C]:{...v[C],override:y.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:u===`${C}:override`}),s.jsx("div",{className:"mt-1 mb-3 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void w(C,"override"),disabled:u===`${C}:override`||!b(C,"override"),children:u===`${C}:override`?"Saving…":b(C,"override")?"Save override":"Saved"})}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:n("settings.coordinatorPrompts.appendLabel")}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:3,value:k.append,onChange:y=>o(v=>({...v,[C]:{...v[C],append:y.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:u===`${C}:append`}),s.jsx("div",{className:"mt-1 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void w(C,"append"),disabled:u===`${C}:append`||!b(C,"append"),children:u===`${C}:append`?"Saving…":b(C,"append")?"Save append":"Saved"})})]},C))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const QC=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function JC(){const{preference:e,setPreference:t}=Xs();return s.jsx("div",{className:"flex gap-2",children:QC.map(n=>s.jsxs("button",{onClick:()=>t(n.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===n.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===n.id?{color:"var(--accent-on-primary)"}:void 0,children:[s.jsx("span",{children:n.icon}),n.label]},n.id))})}function XC(e){const t=e.trim();return/^#[0-9a-fA-F]{6}$/.test(t)?t:/^#[0-9a-fA-F]{3}$/.test(t)?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:null}function ZC(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Ro(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function od(e){const{r:t,g:n,b:a}=ZC(e);return .2126*Ro(t)+.7152*Ro(n)+.0722*Ro(a)}function id(e,t){const n=od(e),a=od(t),r=Math.max(n,a),o=Math.min(n,a);return(r+.05)/(o+.05)}function km(e){const t=XC(e);if(!t)return"#111827";const n="#111827",a="#ffffff";return id(t,n)>=id(t,a)?n:a}const Hi={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},$i={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},ej=[{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"}}}],Sm="adhdev-chat-theme",Cm="adhdev-chat-theme-custom";function fr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Sm)||"ember"}catch{return"ember"}}function us(e){try{const t=localStorage.getItem(Cm);if(t){const n=JSON.parse(t);return{...e==="dark"?Hi:$i,...n[e]}}}catch{}return e==="dark"?Hi:$i}function Qa(e,t){try{localStorage.setItem(Cm,JSON.stringify({dark:e,light:t}))}catch{}}function ts(e,t){const n=parseInt(e.slice(1,3),16),a=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16);return`rgba(${n}, ${a}, ${r}, ${t})`}function $r(e,t){const n=Math.min(255,parseInt(e.slice(1,3),16)+t),a=Math.min(255,parseInt(e.slice(3,5),16)+t),r=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}`}const tj={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function ka(e,t){var r;const n=(r=tj[e])==null?void 0:r[t];if(!n)return;const a=document.documentElement;a.style.setProperty("--accent-primary",n),a.style.setProperty("--accent-primary-light",$r(n,24)),a.style.setProperty("--accent-on-primary",km(n)),a.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${n}, ${$r(n,18)})`),a.style.setProperty("--border-accent",ts(n,.35)),a.style.setProperty("--nav-active-bg",ts(n,.1)),a.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${n}, 0 0 12px ${ts(n,.06)}`)}function un(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",ts(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",ts(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",ts(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",ts(e.borderSubtle,.5)),t.style.setProperty("--border-default",ts(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",$r(e.accentColor,30)),t.style.setProperty("--accent-on-primary",km(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${$r(e.accentColor,40)})`),t.style.setProperty("--border-accent",ts(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",ts(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${ts(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${ts(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function Cl(){const e=document.documentElement;["--bg-primary","--bg-secondary","--bg-card","--surface-primary","--surface-secondary","--bg-glass","--bg-glass-hover","--text-primary","--text-secondary","--text-muted","--border-subtle","--border-default","--accent-primary","--accent-primary-light","--accent-on-primary","--accent-gradient","--border-accent","--nav-active-bg","--nav-active-shadow","--chat-user-bg","--chat-user-color","--chat-user-radius","--chat-assistant-bg","--chat-assistant-color","--chat-assistant-radius","--chat-assistant-border","--chat-container-bg","--dashboard-pane-bg","--chat-thought-accent","--chat-tool-accent","--chat-action-color","--chat-send-bg","--chat-input-border"].forEach(n=>e.style.removeProperty(n))}function sj(e){try{localStorage.setItem(Sm,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=pn()?"dark":"light";un(us(t))}else Cl(),ka(e,pn()?"dark":"light")}function nj(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=fr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=pn()?"dark":"light";un(us(t))}else Cl(),ka(e,pn()?"dark":"light")}function pn(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Ot({label:e,value:t,onChange:n}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:a=>n(a.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,onChange:a=>{/^#[0-9a-fA-F]{0,6}$/.test(a.target.value)&&n(a.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 oa({title:e,children:t}){return s.jsxs("div",{style:{marginBottom:14},children:[s.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:t})]})}function aj({dark:e,onColorsChange:t}){const{t:n}=Ce("common"),a=e?"dark":"light",[r,o]=l.useState(()=>us(a));l.useEffect(()=>{o(us(a))},[a]);const i=l.useCallback((c,d)=>{o(p=>{const u={...p,[c]:d},h=us(a==="dark"?"light":"dark");return a==="dark"?Qa(u,h):Qa(h,u),un(u),t(u),u})},[a,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[n("settings.theme.customEditorTitle"),s.jsx("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:n(e?"settings.theme.darkMode":"settings.theme.lightMode")})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(oa,{title:n("settings.theme.sectionAppBackground"),children:[s.jsx(Ot,{label:n("settings.theme.colorBackground"),value:r.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(Ot,{label:n("settings.theme.colorSurface"),value:r.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(Ot,{label:n("settings.theme.colorCard"),value:r.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(oa,{title:n("settings.theme.sectionAppText"),children:[s.jsx(Ot,{label:n("settings.theme.colorPrimary"),value:r.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(Ot,{label:n("settings.theme.colorSecondary"),value:r.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(Ot,{label:n("settings.theme.colorMuted"),value:r.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(oa,{title:n("settings.theme.sectionBordersAccent"),children:[s.jsx(Ot,{label:n("settings.theme.colorBorderSubtle"),value:r.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(Ot,{label:n("settings.theme.colorBorderDefault"),value:r.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(Ot,{label:n("settings.theme.colorAccent"),value:r.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(oa,{title:n("settings.theme.sectionChatBubbles"),children:[s.jsx(Ot,{label:n("settings.theme.colorUserBubble"),value:r.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(Ot,{label:n("settings.theme.colorUserText"),value:r.userText,onChange:c=>i("userText",c)}),s.jsx(Ot,{label:n("settings.theme.colorAgentBubble"),value:r.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(Ot,{label:n("settings.theme.colorAgentText"),value:r.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(oa,{title:n("settings.theme.sectionChatLayout"),children:[s.jsx(Ot,{label:n("settings.theme.colorChatBg"),value:r.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(Ot,{label:n("settings.theme.colorSendButton"),value:r.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(Ot,{label:n("settings.theme.colorInputBorder"),value:r.inputBorder,onChange:c=>i("inputBorder",c)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:n("settings.theme.labelBubbleRadius")}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.jsx("input",{type:"range",min:4,max:24,value:r.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[r.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?Hi:$i,p=us(e?"light":"dark");e?Qa(c,p):Qa(p,c),o(c),un(c),t(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:n("settings.theme.resetToDefaults")})]})}function rj(){const{t:e}=Ce("common"),[t,n]=l.useState(fr),[a,r]=l.useState(!0),[o,i]=l.useState(()=>us("dark"));l.useEffect(()=>{r(pn());const p=new MutationObserver(()=>{const h=pn();r(h);const g=fr();g==="custom"?un(us(h?"dark":"light")):ka(g,h?"dark":"light")});p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const u=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const h=pn();r(h);const g=fr();g==="custom"?un(us(h?"dark":"light")):ka(g,h?"dark":"light")};return u.addEventListener("change",m),()=>{p.disconnect(),u.removeEventListener("change",m)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?un(us(a?"dark":"light")):(Cl(),ka(t,a?"dark":"light"))},[t,a]),l.useEffect(()=>{i(us(a?"dark":"light"))},[a]);const c=p=>{n(p),sj(p)},d=[...ej,{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 s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:d.map(p=>{const u=t===p.id,m=a?p.preview.dark:p.preview.light,h=p.id==="honey"||p.id==="ember"?"#1a1a1a":p.id==="custom"?o.userText:"#fff";return s.jsxs("button",{onClick:()=>c(p.id),className:"text-left rounded-xl p-3 transition-all",style:{background:u?"var(--bg-glass-hover)":"var(--bg-glass)",border:u?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:u?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[s.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:e("settings.theme.helloHelp")}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.userBubble,color:h},children:e("settings.theme.fixBug")}),s.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:e("settings.theme.onIt")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[u&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:p.id==="custom"?e("settings.theme.customLabel"):p.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:p.description})]})]})]},p.id)})}),t==="custom"&&s.jsx(aj,{dark:a,onColorsChange:p=>i(p)})]})}const jl="adhdev_mobileDashboardMode_v1",Fi="adhdev:mobile-dashboard-mode-change";function Nl(){try{return localStorage.getItem(jl)==="workspace"?"workspace":"chat"}catch{return"chat"}}function oj(e){if(typeof window>"u")return()=>{};const t=r=>{e(r??Nl())},n=r=>{const o=r.detail;t(o)},a=r=>{r.key&&r.key!==jl||t()};return window.addEventListener(Fi,n),window.addEventListener("storage",a),()=>{window.removeEventListener(Fi,n),window.removeEventListener("storage",a)}}function ij(e){try{localStorage.setItem(jl,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Fi,{detail:e}))}function lj(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(Nl()==="chat")},[]),s.jsx(rn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(yn,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:n=>{t(n),ij(n?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const cj="Choose a preset or create a fully custom theme. Custom themes control the entire app — backgrounds, text, borders, and chat bubbles.",dj="Choose whether the dashboard opens like a chat app on phones or keeps the full workspace layout.";function uj({themeDescription:e=cj,mobileDescription:t=dj,fontsSlot:n}){const{t:a}=Ce("common");return s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:a("settings.appearance.modeLabel")}),s.jsx(JC,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:a("settings.appearance.themeLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:e}),s.jsx(rj,{})]}),n,s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:a("settings.appearance.mobileLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:t}),s.jsx(lj,{})]})]})}const Eo=new Map,ld=new Map;function pj(e){if(!e||typeof e!="object")return null;const t=e,n=t.result&&typeof t.result=="object"?t.result:t,a=n.machine;return!a||typeof a!="object"?null:{machine:a,timestamp:typeof n.timestamp=="number"?n.timestamp:void 0}}function mj(e,t,n,a){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:a,platform:n.platform,machine:n}}function jm(){const{sendCommand:e}=kt(),{injectEntries:t,getIdes:n}=ja();return l.useCallback(async(a,r)=>{if(!a)return;const o=(r==null?void 0:r.minFreshMs)??yk,i=ld.get(a)||0;if(!(r!=null&&r.force)&&i>0&&Date.now()-i<o)return;const c=Eo.get(a);if(c)return c;const d=(async()=>{const p=await e(a,"get_machine_runtime_stats"),u=pj(p);if(!u)return;const m=n().find(g=>g.id===a),h=mj(m,a,u.machine,u.timestamp||Date.now());t([h]),ld.set(a,Date.now())})().finally(()=>{Eo.delete(a)});return Eo.set(a,d),d},[n,t,e])}function hj(e,t,n){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:n.timestamp,platform:n.machine.platform,machine:{...(e==null?void 0:e.machine)||{},...n.machine}}}function fj(e,t){const{sendData:n}=kt(),{injectEntries:a,getIdes:r}=ja(),o=Array.from(new Set(e.filter(Boolean))).join("|");l.useEffect(()=>{if(!(t!=null&&t.enabled)||!n)return;const i=o?o.split("|"):[];if(i.length===0)return;const c=i.map(d=>ms.subscribe({sendData:n},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const m=r().find(g=>g.id===d),h=hj(m,d,u);a([h])}));return()=>{c.forEach(d=>d())}},[o,r,a,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,n])}function bj(e,t){const{sendData:n}=kt(),[a,r]=l.useState(null),[o,i]=l.useState(!1);return l.useEffect(()=>{if(!e){r(null),i(!1);return}if(!(t!=null&&t.enabled)||!n){i(!1);return}r(null),i(!0);let c=null;const d=ms.subscribe({sendData:n},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},p=>{c&&(clearTimeout(c),c=null),r(p.diagnostics),i(!1)});return d.initialSendAccepted?c=setTimeout(()=>{i(!1)},Sk):i(!1),()=>{c&&clearTimeout(c),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,n]),{diagnostics:a,loading:o,applyDiagnostics:r}}function gj(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Nm(e){const{sendData:t}=kt(),[n,a]=l.useState({});return l.useEffect(()=>{const r=gj(e);if(!r||!e.sessionId||!t){a({});return}const o=ms.subscribe({sendData:t},r,{type:"subscribe",topic:"session.modal",key:`daemon:${r}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},i=>{a({status:i.status,modalMessage:i.modalMessage,modalButtons:i.modalButtons}),_n.record({interactionId:i.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:i.status,modalButtonCount:Array.isArray(i.modalButtons)?i.modalButtons.length:0}})});return o.initialSendAccepted||a({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),n}function xj(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function vj(e){const t=(e==null?void 0:e.result)??e;return typeof(t==null?void 0:t.error)=="string"?t.error:"Interactive prompt response failed"}async function yj(e,t,n){const a=await n(`/api/v1/sessions/${encodeURIComponent(e)}/interactive-prompt/resolve`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!a.ok){let r=`HTTP ${a.status}`;try{const o=await a.json();typeof(o==null?void 0:o.error)=="string"&&(r=o.error)}catch{}throw new Error(r)}}async function wj({promptSession:e,response:t,useP2PCommand:n,sendCommand:a,fetchImpl:r=fetch}){if(n){const o=await a(e.routeId,"interactive_prompt_response",{targetSessionId:e.sessionId,sessionId:e.sessionId,response:t});if(!xj(o))throw new Error(vj(o));return}await yj(e.sessionId,t,r)}function Am(e){const{ides:t,isP2PActive:n,p2pStates:a}=Ts(),{sendCommand:r}=kt(),[o,i]=l.useState(null),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useRef(!1),h=l.useMemo(()=>ug(t,e),[t,e]),g=!!h,S=l.useMemo(()=>h?h.prompt.promptId===o?null:h:null,[o,h]),f=l.useCallback(async b=>{if(!S||m.current)return;m.current=!0;const C=Qu(S.prompt,b);d(!0),u(null);try{const k=(a==null?void 0:a[S.daemonId])==="connected"||n===!0;await wj({promptSession:S,response:C,useP2PCommand:k,sendCommand:r}),i(S.prompt.promptId)}catch(k){throw u(k instanceof Error?k.message:String(k)),k}finally{d(!1),m.current=!1}},[n,a,S,r]),x=l.useCallback(()=>{S&&i(S.prompt.promptId)},[S]),w=l.useCallback(()=>{i(null),u(null)},[]);return{promptSession:S,hasActivePrompt:g,responseError:p,isSubmitting:c,submit:f,cancel:x,reopen:w}}function Tm(e){return e instanceof Error?e.message:String(e||"")}function kj(e){const t=Tm(e);return t.includes("P2P command timeout")||t.includes("P2P not connected")||t.includes("P2P channel not open")||t.includes("P2P not available")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}function Sj(e){const t=Tm(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Mm({conversation:e,mode:t,ides:n,sendDaemonCommand:a,setCliViewModeOverrides:r}){if(!e||!ht(e)||pt(e))return;const o=Yn(e);if(o===t)return;const i=e.sessionId;i&&r(c=>({...c,[i]:t}));try{await a(Bs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:As(e),mode:t})}catch(c){const d=Sj(c);i&&!d&&r(p=>{const u={...p};return o===jj(n,i)?delete u[i]:u[i]=o,u}),kj(c)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",c instanceof Error?c.message:String(c)):console.error("Failed to switch CLI view mode:",c)}}function cd(e,t){const n=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!n||e.transport!=="pty")return e;const a=t[n];return!a||e.mode===a?e:{...e,mode:a}}function Cj(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let n=!1;const a=e.map(r=>{const o=cd(r,t),i=Array.isArray(r.childSessions)?r.childSessions.map(d=>cd(d,t)):r.childSessions,c=i!==r.childSessions;return o!==r||c?(n=!0,{...o,...c?{childSessions:i}:{}}):r});return n?a:e}function jj(e,t){if(!t)return null;for(const n of e){if(n.sessionId===t&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal";for(const a of n.childSessions||[])if(a.id===t&&a.transport==="pty")return a.mode==="chat"?"chat":"terminal"}return null}function Nj({visibleConversations:e,clearedTabs:t,setClearedTabs:n,setActionLogs:a,isConversationMuted:r}){l.useEffect(()=>{pp()},[]);const o=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:Zp(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null,target:{providerSessionId:i.providerSessionId,sessionId:i.sessionId,tabKey:i.tabKey,routeId:i.routeId},muted:r?r(i):!1})),[e,r]);return Ow(o),l.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{n(d=>{const p=Date.now(),u={};for(const[m,h]of Object.entries(d))p-h<5e3&&(u[m]=h);return Object.keys(u).length===Object.keys(d).length?d:u})},5500);return()=>clearTimeout(c)},[t,n]),l.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;a(d=>{const p=d.filter(u=>u.timestamp>c).slice(-100);return p.length===d.length?d:p})},6e4);return()=>clearInterval(i)},[a]),null}function dd(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function mn(e){const t=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1],n=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,a=dd(t==null?void 0:t.receivedAt)||dd(t==null?void 0:t.timestamp)||0;return Math.max(n,a)}function Bi(e,t=0){return mn(e)||e.lastUpdated||t||0}function Dm(e){return mn(e)||e.lastUpdated||0}function Pm(e,t,n=Dm){const a=n(t)-n(e);if(a!==0)return a;const r=(e.machineName||"").localeCompare(t.machineName||"");if(r!==0)return r;const o=e.displayPrimary.localeCompare(t.displayPrimary);if(o!==0)return o;const i=e.displaySecondary.localeCompare(t.displaySecondary);return i!==0?i:e.tabKey.localeCompare(t.tabKey)}function Wi(e){var n;const t=ns(e.status,{activeModal:(n=e.modalButtons)!=null&&n.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function Aj(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!Wi(e)&&!e.title.trim()}function Tj(e){return e.length===0?null:[...e].sort((t,n)=>{const a=Number(Wi(n))-Number(Wi(t));if(a!==0)return a;const r=n.messages.length-t.messages.length;return r!==0?r:Pm(t,n)})[0]||null}function hs(e,t){const n=e.filter(i=>i.routeId===t);if(n.length===0)return null;const a=n.find(i=>i.streamSource==="native")||null,r=n.filter(i=>i.streamSource==="agent-stream"),o=Tj(r);return a?o&&Aj(a)?o:a:o||n[0]||null}function Mj(e){const t=e.filter(r=>r.type!=="adhdev-daemon"),n=new Set;for(const r of t){if(!Ni(r))continue;const o=op(r);o&&n.add(o)}const a=new Map;for(const r of t){const o=vw(r,n),i=a.get(o);if(!i){a.set(o,r);continue}const c=m=>(m.workspace?1:0)+(m.activeChat?1:0)+(m.lastMessagePreview?1:0),d=c(i),p=c(r),u=p>d||p===d&&(r.timestamp||0)>(i.timestamp||0)?r:i;a.set(o,Dj(u,u===r?i:r))}return Array.from(a.values())}function Dj(e,t){const n=Ni(t),a=Ni(e);if(!n&&!a)return e;const r=a?n?void 0:t:e,o=a?e:n?t:void 0,i=r&&String(r.daemonId||"").trim()||String(e.ownerDaemonId||"").trim()||String(t.ownerDaemonId||"").trim()||void 0,c=String(e.ownerMachineName||"").trim()||String(t.ownerMachineName||"").trim()||void 0,d=o==null?void 0:o.settings;return{...e,...i&&{ownerDaemonId:i},...c&&!e.ownerMachineName&&{ownerMachineName:c},...d&&!a&&{settings:{...d,...e.settings??{}}}}}function _o(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function Pj(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function ud(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],n=t[t.length-1],a=n?Pj(Hn(n.content)):"";return[e.id||"",e.title||"",e.status||"",t.length,String((n==null?void 0:n.id)||""),String((n==null?void 0:n.index)??""),String((n==null?void 0:n.receivedAt)??(n==null?void 0:n.timestamp)??""),a].join(":")}function Ij(e){const t=Array.isArray(e.childSessions)?e.childSessions:[];return[e.id,e.sessionId||"",e.providerSessionId||"",e.transport||"",e.mode||"",e.status||"",e.workspace||"",e.lastMessageHash||"",String(e.lastMessageAt||""),e.lastMessagePreview||"",e.lastMessageRole||"",String(e.lastUpdated||""),ud(e.activeChat),...t.map(n=>[n.id||"",n.providerSessionId||"",n.transport||"",n.mode||"",n.status||"",n.title||"",n.lastMessageHash||"",String(n.lastMessageAt||""),n.lastMessagePreview||"",n.lastMessageRole||"",String(n.lastUpdated||""),ud(n.activeChat)].join(":"))].join("|")}function Lj(e,t){const n=Date.now();return e.map(a=>{const r=t[a.tabKey];return r&&n-r<5e3?{...a,messages:[],title:""}:a})}function Rj(e,t){const n=new Map;for(const a of e){const r=t.get(a.routeId)||a;for(const o of xa({routeId:a.routeId}))n.set(o,r);for(const o of xa({providerSessionId:a.providerSessionId,sessionId:a.sessionId}))n.set(o,a.streamSource==="native"?r:a);for(const o of xa({tabKey:a.tabKey}))n.set(o,a)}return n}function Ej(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function _j(e){const t=Ej(e);if(!t)return`empty:${e.messages.length}`;if(t.id)return`id:${String(t.id)}`;if(t._localId)return`local:${String(t._localId)}`;const n=String(t.role||""),a=Hn(t.content).slice(0,240);return`${e.messages.length}:${n}:${a}`}function Hj({ides:e,connectionStates:t,clearedTabs:n}){const a=l.useMemo(()=>Mj(e),[e]),r=l.useMemo(()=>Zu(e),[e]),o=l.useMemo(()=>dm(e),[e]),i=l.useRef([]),c=l.useRef([]),d=l.useRef([]),p=l.useRef(new Map),u=l.useRef(new Map),m=l.useMemo(()=>{const k=new Map,y=[];for(const A of a){const{connectionState:T="new",machineName:P}=um(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),M=Ij(A),D=p.current.get(A.id);if(D&&D.ide===A&&D.sourceSignature===M&&D.connectionState===T&&D.machineName===P){k.set(A.id,D),y.push(...D.conversations);continue}const L=kl(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),O={ide:A,sourceSignature:M,connectionState:T,machineName:P,conversations:L};k.set(A.id,O),y.push(...L)}p.current=k;const v=new Map,j=A=>{const T=_j(A),P=u.current.get(A.tabKey);if(P&&P.signature===T)return v.set(A.tabKey,P),P.timestamp;const M={signature:T,timestamp:Dm(A)||(P==null?void 0:P.timestamp)||0};return v.set(A.tabKey,M),M.timestamp},N=[...y].sort((A,T)=>Pm(A,T,j));return u.current=v,N},[a,t,o]),h=l.useMemo(()=>{const k=Lj(m,n);return _o(i.current,k)?i.current:(i.current=k,k)},[m,n]),g=l.useMemo(()=>{const k=new Map,y=Array.from(new Set(h.map(v=>v.routeId)));for(const v of y){const j=hs(h,v);j&&k.set(v,j)}return k},[h]),S=l.useMemo(()=>{const k=new Map;for(const y of h){const v=g.get(y.routeId),j=y.streamSource==="native"&&v?v:y;for(const N of xa({providerSessionId:y.providerSessionId,sessionId:y.sessionId,tabKey:y.tabKey}))k.set(N,j)}return k},[h,g]),f=l.useMemo(()=>Rj(h,g),[h,g]),x=l.useCallback(k=>{if(k)return S.get(k)},[S]),w=l.useCallback(k=>{if(k)return f.get(k)},[f]),b=l.useMemo(()=>{const k=h.filter(y=>!Js(y,r).surfaceHidden);return _o(c.current,k)?c.current:(c.current=k,k)},[h,r]),C=l.useMemo(()=>{const k=b.map(y=>y.tabKey);return _o(d.current,k)?d.current:(d.current=k,k)},[b]);return{chatIdes:a,conversations:h,visibleConversations:b,visibleTabKeys:C,resolveConversationBySessionId:x,resolveConversationByTarget:w}}function $j({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:n,setSearchParams:a}){const r=l.useMemo(()=>{var c;return e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),o=l.useMemo(()=>{var c;return!e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),i=l.useCallback(()=>{t&&a(c=>{const d=new URLSearchParams(c);return d.delete("activeTab"),d},{replace:!0})},[a,t]);return{requestedDesktopTabKey:r,requestedMobileTabKey:o,consumeRequestedActiveTab:i}}function Fj({ides:e,sendDaemonCommand:t,setToasts:n,resolveConversationByTarget:a}){l.useEffect(()=>{ft.setIdes(e)},[e]),l.useEffect(()=>{ft.setResolveAction((r,o,i)=>{t(r,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const r=ft.onToast(o=>{n(c=>c.some(p=>p.message===o.message&&o.timestamp-p.timestamp<3e3)?c:[...c.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const i=o.duration||5e3;setTimeout(()=>n(c=>c.filter(d=>d.id!==o.id)),i)});return()=>{r()}},[n]),l.useEffect(()=>{const r=Yp.on("status_event",o=>{ft.handleRawEvent(o,"ws")});return()=>{r()}},[]),l.useEffect(()=>{var o;const r=i=>{var f;const c=i.data;if((c==null?void 0:c.type)!=="notification_action"||typeof c.action!="string"||!c.action.startsWith("approval_")||!(c.daemonId||c.targetSessionId||c.targetKey))return;const d=c.targetSessionId||c.targetKey||c.daemonId,p=a(d),u=(p==null?void 0:p.routeId)||c.daemonId;if(!u)return;const m=Number(c.buttonIndex),h=c.button||((f=p==null?void 0:p.modalButtons)==null?void 0:f[m])||"Approve",g=String(h).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),S=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(g);t(u,"resolve_action",{action:S?"approve":"reject",button:h,...Number.isFinite(m)&&{buttonIndex:m},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(x=>console.error("[SW Action] approval failed:",x))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",r),()=>{var i;return(i=navigator.serviceWorker)==null?void 0:i.removeEventListener("message",r)}},[a,t])}const Bj="adhdev_dashboardLayout_v1",Wj="adhdev_dashboardDockview_v1",Oj="adhdev_dashboardDockviewHiddenRestore_v1",ia={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Al(e,t){try{const n=localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}}function Uj(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Im(e){return`${Bj}:${e}`}function qj(e){const t=Im(e);return Al(t,null)}function Gj(e,t){try{const n=t.groupAssignments.length===0&&t.focusedGroup===0&&Object.keys(t.groupActiveTabIds).length===0&&Object.keys(t.groupTabOrders).length===0&&t.groupSizes.length===0,a=Im(e);if(n){localStorage.removeItem(a);return}localStorage.setItem(a,JSON.stringify(t))}catch{}}function Lm(e){return`${Wj}:${e}`}function zj(e){const t=Lm(e);return Al(t,null)}function Kj(e,t){try{const n=Lm(e);if(!t){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Rm(e){return`${Oj}:${e}`}function Vj(e){const t=Rm(e);return Al(t,{})}function Yj(e,t){try{const n=Rm(e);if(Object.keys(t).length===0){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Qj(){return{groupAssignments:[...ia.groupAssignments],focusedGroup:ia.focusedGroup,groupActiveTabIds:{...ia.groupActiveTabIds},groupTabOrders:{...ia.groupTabOrders},groupSizes:[...ia.groupSizes]}}function Jj(e,t){return e?e.length===t.length&&e.every((n,a)=>n===t[a]):t.length===0}function Xj(){const[e]=l.useState(()=>Uj(typeof window<"u"?window.innerWidth:1280)),[t,n]=l.useState(()=>new Map),[a,r]=l.useState(0),[o,i]=l.useState({}),[c,d]=l.useState({}),[p,u]=l.useState([]),[m,h]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[g,S]=l.useState(!1),f=l.useCallback(()=>{if(g)return;const A=qj(e)??Qj();n(new Map(A.groupAssignments)),r(A.focusedGroup),i(A.groupActiveTabIds),d(A.groupTabOrders),u(A.groupSizes),S(!0)},[g,e]);l.useEffect(()=>{g&&Gj(e,{groupAssignments:[...t.entries()],focusedGroup:a,groupActiveTabIds:o,groupTabOrders:c,groupSizes:p})},[g,e,t,a,o,c,p]),l.useEffect(()=>{const A=window.matchMedia("(max-width: 767px)"),T=P=>h(P.matches);return A.addEventListener("change",T),()=>A.removeEventListener("change",T)},[]);const x=l.useCallback(A=>{n(A)},[]),w=l.useCallback(A=>{r(A)},[]),b=l.useCallback(A=>{i(A)},[]),C=l.useCallback(A=>{d(A)},[]),k=l.useCallback(A=>{u(A)},[]),y=l.useCallback(A=>{w(A)},[w]),v=l.useCallback((A,T)=>{i(P=>(P[A]??null)===(T??null)?P:{...P,[A]:T})},[]),j=l.useCallback((A,T)=>{d(P=>{const M=P[A];return Jj(M,T)?P:{...P,[A]:T}})},[]),N=l.useCallback((A,T)=>{const P=T.get(A)??0;return v(P,A),y(P),P},[y,v]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:x,focusedGroup:a,updateFocusedGroup:w,focusGroup:y,groupActiveTabIds:o,updateGroupActiveTabIds:b,setGroupActiveTab:v,groupTabOrders:c,updateGroupTabOrders:C,setGroupTabOrder:j,groupSizes:p,updateGroupSizes:k,isMobile:m,hasHydratedStoredLayout:g,hydrateStoredLayout:f,focusConversationTab:N}}function Zj(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0],a=Yr(t);return typeof(n==null?void 0:n.id)=="string"&&a.includes(n.id)}function e1({urlActiveTab:e,conversations:t,resolveConversationBySessionId:n,normalizedGroupAssignments:a,hasHydratedStoredLayout:r,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:c,historyModalOpen:d,activeConv:p,isRefreshingHistory:u,ides:m,handleRefreshHistory:h}){const g=l.useRef(!1),S=l.useRef(!1),f=l.useRef(null),x=l.useRef(!1);l.useEffect(()=>{if(!e||g.current||t.length===0)return;if(!r){o();return}const w=n(e);w&&(i(w.tabKey,a),g.current=!0,S.current=!0,f.current!=null&&(window.clearTimeout(f.current),f.current=null),c(b=>{const C=new URLSearchParams(b);return C.delete("activeTab"),C},{replace:!0}))},[e,t,n,a,r,o,i,c]),l.useEffect(()=>{if(!(S.current||r)&&t.length!==0){if(!e){o(),S.current=!0;return}if(g.current){S.current=!0;return}if(f.current==null)return f.current=window.setTimeout(()=>{f.current=null,!(S.current||r)&&(o(),S.current=!0)},1500),()=>{f.current!=null&&(window.clearTimeout(f.current),f.current=null)}}},[e,t.length,r,o]),l.useEffect(()=>{if(!d){x.current=!1;return}if(!p||x.current||u)return;const w=m.find(b=>b.id===p.routeId);w&&(!w.chats||w.chats.length===0||Zj(w.chats,p))&&(x.current=!0,h())},[d,p,u,m,h])}function Ho(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0];if((n==null?void 0:n.active)===!0)return!0;const a=Yr(t);return typeof(n==null?void 0:n.id)=="string"&&a.includes(n.id)}function Em({sendDaemonCommand:e,activeConv:t,chats:n,updateRouteChats:a,setToasts:r,setClearedTabs:o}){const[i,c]=l.useState(!1),[d,p]=l.useState(!1),u=l.useCallback(async S=>{try{await e("standalone","launch_ide",{ideType:S,enableCdp:!0})}catch(f){console.error("Launch failed",f)}},[e]),m=l.useCallback(async(S,f)=>{try{const x=S||(t==null?void 0:t.daemonId)||"",w=await e(x,"switch_chat",{id:f,sessionId:f,...ln(t)}),b=w==null?void 0:w.result;if((w==null?void 0:w.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?Tn(r,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?Tn(r,`⚠️ Switch error: ${b}`):Tn(r,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),Tn(r,`❌ Switch failed: ${x.message||"connection error"}`)}},[t,e,r]),h=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const S=cn(t);await e(S,"new_chat",{...ln(t)}),Ok(S,t.sessionId,Yr(t)[0]),o(f=>({...f,[t.tabKey]:Date.now()}))}catch(S){console.error("New chat failed",S)}finally{c(!1)}}},[t,i,e,o]),g=l.useCallback(async()=>{var S,f;if(!(!t||d)){p(!0);try{const x=cn(t),w=async()=>e(x,"list_chats",{forceExpand:!0,...ln(t)});let b=await w(),C=(b==null?void 0:b.chats)||((S=b==null?void 0:b.result)==null?void 0:S.chats);Ho(C,t)&&(await new Promise(k=>setTimeout(k,450)),b=await w(),C=(b==null?void 0:b.chats)||((f=b==null?void 0:b.result)==null?void 0:f.chats)),b!=null&&b.success&&Array.isArray(C)&&(a(t.routeId,C),Ho(C,t)&&!Ho(n,t)&&Tn(r,"⚠️ History dialog did not fully open — try once more"))}catch(x){console.error("Refresh history failed",x)}finally{p(!1)}}},[t,n,d,e,a,r]);return{isCreatingChat:i,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:m,handleNewChat:h,handleRefreshHistory:g}}function t1(e,t){if(e.size!==t.size)return!1;for(const[n,a]of e)if(t.get(n)!==a)return!1;return!0}function s1(e,t){return e.length!==t.length?!1:e.every((n,a)=>n===t[a])}function pd(e,t){const n=Object.keys(e),a=Object.keys(t);return n.length!==a.length?!1:n.every(r=>t[Number(r)]===e[Number(r)])}function Ja(e,t){const n=new Set(t),a=t.length>0?[0]:[];for(const[i,c]of e)!n.has(i)||c<=0||a.includes(c)||a.push(c);a.sort((i,c)=>i-c);const r={};a.forEach((i,c)=>{r[i]=c}),a.length===0&&(r[0]=0);const o=new Map;for(const[i,c]of e){if(!n.has(i)||c<=0)continue;const d=r[c];typeof d=="number"&&d>0&&o.set(i,d)}return{assignments:o,groupCount:Math.max(1,a.length),mapping:r,usedGroups:a}}function md(e,t){const n={};for(const[a,r]of Object.entries(e)){const o=t[Number(a)];typeof o=="number"&&(n[o]=r)}return n}function n1(e,t,n){if(t.length===0)return 0;if(typeof n[e]=="number")return n[e];const a=[...t].reverse().find(r=>r<e)??t[0];return n[a]??0}function a1(e,t,n){if(t.length<=1)return[];const a=t.map(i=>e[i]).filter(i=>Number.isFinite(i)),r=a.length===t.length?a:Array(n).fill(100/n),o=r.reduce((i,c)=>i+c,0);return o>0?r.map(i=>i/o*100):Array(n).fill(100/n)}function hd(e,t){const n={};for(const[a,r]of Object.entries(e)){const o=Number(a);n[o>=t?o+1:o]=r}return n}function fd(e){return Array(e).fill(100/e)}function r1({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:n,updateGroupActiveTabIds:a,updateGroupTabOrders:r,groupSizes:o,updateGroupSizes:i,isMobile:c,visibleConversations:d,visibleTabKeys:p}){const u=l.useRef(null),m=l.useMemo(()=>Ja(e,p),[e,p]),h=m.assignments,g=l.useMemo(()=>c?1:m.groupCount,[m.groupCount,c]),S=g>1,f=l.useCallback((y,v)=>{t(j=>{const N=new Map(Ja(j,p).assignments);return v===0?N.delete(y):N.set(y,v),N}),a(j=>({...j,[v]:y})),n(v)},[t,p,a,n]),x=l.useCallback(y=>{t(v=>{const j=Ja(v,p).assignments,N=new Map;for(const[A,T]of j)T!==y&&(T>y?N.set(A,T-1):N.set(A,T));return N}),i(v=>{if(v.length<=1)return[];const j=[...v];j.splice(y,1);const N=j.reduce((A,T)=>A+T,0);return N>0?j.map(A=>A/N*100):[]}),n(0)},[t,p,i,n]),w=l.useCallback((y,v)=>{v.preventDefault();const j=u.current;if(!j)return;const N=v.clientX,A=j.offsetWidth,T=o.length===g?[...o]:fd(g),P=D=>{const O=(D.clientX-N)/A*100,E=[...T];E[y]=Math.max(15,T[y]+O),E[y+1]=Math.max(15,T[y+1]-O),i(E)},M=()=>{document.removeEventListener("mousemove",P),document.removeEventListener("mouseup",M),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",P),document.addEventListener("mouseup",M)},[o,g,i]),b=l.useCallback((y,v,j)=>{if(g>=4)return;const N=j==="left"?v:v+1;t(A=>{const T=Ja(A,p).assignments,P=new Map;for(const M of d){const D=T.get(M.tabKey)??0,L=D>=N?D+1:D;L>0&&P.set(M.tabKey,L)}return N>0&&P.set(y,N),P}),i(A=>{const T=A.length===g?[...A]:fd(g),P=T[v]??100/g,M=Math.max(15,P/2),D=Math.max(15,P/2),L=[...T];L[v]=M,L.splice(N,0,D);const O=L.reduce((E,I)=>E+I,0);return L.map(E=>E/O*100)}),a(A=>{const T=hd(A,N);return T[N]=y,T}),r(A=>{const T=hd(A,N);return T[N]=[y],T}),n(N)},[g,t,p,d,i,a,r,n]);l.useEffect(()=>{t1(e,h)||t(h)},[e,h,t]),l.useEffect(()=>{const{mapping:y,usedGroups:v}=m;a(j=>{const N=md(j,y);return pd(j,N)?j:N}),r(j=>{const N=md(j,y);return pd(j,N)?j:N}),n(j=>{const N=c?0:n1(j,v,y);return j===N?j:N}),i(j=>{const N=c?[]:a1(j,v,m.groupCount);return s1(j,N)?j:N})},[m,c,a,r,n,i]);const C=l.useMemo(()=>{const y=Array.from({length:g},()=>[]);for(const v of d){const j=h.get(v.tabKey)??0,N=Math.min(j,g-1);y[N].push(v)}return y},[d,h,g]),k=l.useCallback(()=>{t(new Map),n(0)},[t,n]);return{containerRef:u,normalizedGroupAssignments:h,numGroups:g,isSplitMode:S,groupedConvs:C,moveTabToGroup:f,closeGroup:x,handleResizeStart:w,splitTabRelative:b,clearAllSplits:k}}function o1({ides:e,sendDaemonCommand:t}){const n="1.0.38",a=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:no(m,qs(m,n))).sort((m,h)=>Number(wa(h,qs(h,n)))-Number(wa(m,qs(m,n)))),[n,e]),r=l.useMemo(()=>a.some(m=>wa(m,qs(m,n))),[n,a]),o=l.useMemo(()=>a.map(m=>qs(m,n)).find(m=>typeof m=="string"&&m.trim().length>0)||n,[n,a]),[i,c]=l.useState(!1),[d,p]=l.useState({}),u=l.useCallback(async m=>{var S,f;const h=e.find(x=>x.id===m);if(!h)return;p(x=>({...x,[m]:"upgrading"}));const g=ao(h);if(!g){p(x=>({...x,[m]:"error"}));return}try{const x=await t(m,"daemon_upgrade",g);(S=x==null?void 0:x.result)!=null&&S.upgraded||(f=x==null?void 0:x.result)!=null&&f.success?p(w=>({...w,[m]:"done"})):p(w=>({...w,[m]:"error"}))}catch{p(x=>({...x,[m]:"error"}))}},[e,t]);return{versionMismatchDaemons:a,hasRequiredVersionDaemons:r,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:u}}const _m=80;function br(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function i1(e){return{...e,createdAt:br(e.createdAt),updatedAt:br(e.updatedAt,e.createdAt),lastEventAt:br(e.lastEventAt,e.updatedAt||e.createdAt)}}function l1(e){const t=rp(e);return t==="unknown:"?e.id:t}function c1(e){return[e.type,ap(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function d1(e,t=_m){const n=new Map;for(const a of e){if(a.deletedAt)continue;const r=l1(a),o=n.get(r);if(!o){n.set(r,a);continue}(a.updatedAt>o.updatedAt||a.updatedAt===o.updatedAt&&a.createdAt>o.createdAt)&&n.set(r,a)}return Array.from(n.values()).sort((a,r)=>{const o=r.updatedAt-a.updatedAt;return o!==0?o:r.createdAt-a.createdAt}).slice(0,Math.max(0,t))}function u1(e,t){const n=Date.now(),a=[];for(const r of e){const o=r.sessionId?t.get(r.sessionId):void 0;if(o!=null&&o.surfaceHidden||o!=null&&o.muted)continue;const i=Vr(r,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const d=br(r.lastMessageAt||(o==null?void 0:o.lastUpdated)||r.lastUpdated,n),p=c1({type:c,sessionId:r.sessionId,providerSessionId:r.providerSessionId,tabKey:r.tabKey,lastMessageHash:r.lastMessageHash,lastMessageAt:r.lastMessageAt,lastUpdated:(o==null?void 0:o.lastUpdated)||r.lastUpdated});a.push(i1({id:p,dedupKey:p,type:c,routeId:r.routeId,machineId:r.daemonId||r.routeId,sessionId:r.sessionId,providerSessionId:r.providerSessionId,tabKey:r.tabKey,title:Np(r),preview:ek(r),createdAt:d,updatedAt:d,lastEventAt:d}))}return d1(a)}function p1(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function m1(e){const{conversations:t,liveSessionInboxState:n,maxItems:a=_m}=e,r=l.useMemo(()=>u1(t,n).slice(0,Math.max(0,a)),[t,n,a]),o=l.useMemo(()=>p1(r),[r]);return{notifications:r,unreadCount:o}}function h1({notifications:e,sendDaemonCommand:t}){const n=l.useCallback(o=>{const i=e.find(d=>d.id===o),c=Math.max(Date.now(),(i==null?void 0:i.updatedAt)||0);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_session_seen",{sessionId:i.sessionId,seenAt:c}).catch(()=>{})},[e,t]),a=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_notification_unread",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]),r=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"delete_notification",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:n,handleMarkDashboardNotificationUnread:a,handleDeleteDashboardNotification:r}}function Tl(...e){const t=new Set,n=[],a=r=>{const o=typeof r=="string"?r.trim():"";if(!o)return;const i=o.toLowerCase();t.has(i)||(t.add(i),n.push(o))};for(const r of e){if(Array.isArray(r)){for(const o of r)a(o);continue}a(r)}return n}function f1(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const n=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(n){const a=n[1].toUpperCase(),r=(n[2]||"").replace(/[\\/]+/g,"\\");return r?`${a}:\\${r}`:`${a}:\\`}return null}function Ml(e,t=[]){if(e==="win32"){for(const n of t){if(typeof n!="string")continue;const a=f1(n);if(a)return a}return"C:\\"}for(const n of t){const a=typeof n=="string"?n.trim():"";if(a)return a}return"~"}function b1(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const n=t.includes("\\")?"\\":"/",a=t.split(/[\\/]/);return/^[A-Za-z]:$/.test(a[0]||"")?a.length<=2?`${a[0]}\\`:a.slice(0,-1).join("\\"):a.length<=2?n:a.slice(0,-1).join(n)||n}function g1(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Dl(e,t,n){const a=await e(t,"file_list_browse",{path:n}),r=g1(a);if(!(r!=null&&r.success))throw new Error((r==null?void 0:r.error)||(a==null?void 0:a.error)||"Could not browse folder");const o=typeof(r==null?void 0:r.path)=="string"?r.path:n,i=o.includes("\\")?"\\":"/",c=(p,u)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${u}`:p==="/"||p==="\\"?`${i}${u}`:`${p.replace(/[\\/]+$/,"")}${i}${u}`,d=Array.isArray(r==null?void 0:r.files)?r.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:typeof(p==null?void 0:p.path)=="string"&&p.path.trim()?p.path:c(o,p.name)})).sort((p,u)=>p.name.localeCompare(u.name)):[];return{path:o,directories:d}}function bd(e,t){const n=t.meshId||"",a={meshId:n,workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp",adhdevMcpArgs:t.adhdevMcpArgs||`mcp --mode ipc --repo-mesh ${n}`};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand|adhdevMcpArgs)\s*\}\}/g,(r,o)=>a[o]||"")}function Hm(e,t={}){const n=e==null?void 0:e.mcpConfig;if((n==null?void 0:n.mode)!=="manual")return null;const r=bd(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"}).trim();return!r.includes(`
70
70
  `)&&!r.startsWith("{")?null:{serverName:n.serverName||"adhdev-mesh",configFormat:n.format,configPathCommand:n.configPathCommand,requiresRestart:n.requiresRestart===!0,instructions:n.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:bd(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"})}}function x1(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.instructions=="string"?t.instructions:"",a=typeof t.template=="string"?t.template:"";return!n&&!a?null:{serverName:typeof t.serverName=="string"?t.serverName:void 0,configFormat:typeof t.configFormat=="string"?t.configFormat:void 0,configPathCommand:typeof t.configPathCommand=="string"?t.configPathCommand:void 0,requiresRestart:t.requiresRestart===!0,instructions:n||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:a}}function Ia(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function $m(e){return Qr(e)||e.tabKey||e.routeId||null}function Fm(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",n=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",a=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",r=e.conversations.find(o=>{if(a&&o.routeId!==a)return!1;const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey].map(c=>typeof c=="string"?c.trim():"").filter(Boolean);return!!(t&&i.includes(t)||n&&i.includes(n)||a&&o.routeId===a)});if(r!=null&&r.tabKey)return r.tabKey;if(a){const o=hs(e.conversations,a)||e.conversations.find(i=>i.routeId===a);if(o!=null&&o.tabKey)return o.tabKey}return t||n||a||null}function Gs(e){return String(e||"").trim()}function Bm(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Fr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function v1(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function y1(e,t){const n=Gs(e.providerSessionId),a=Gs(e.targetSessionId),r=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(Gs).filter(Boolean);return!!(n&&i.includes(n)||a&&i.includes(a))});return r?r.tabKey:a||n||null}function w1(e,t,n){if(t.event!=="agent:generating_completed")return null;const a=Bm(t.daemonId);if(a&&a!==e.machineId)return null;const r=Gs(t.providerType);if(e.providerType&&r!==e.providerType)return null;const o=Gs(e.resumeSessionId),i=Gs(e.launchedSessionId),c=Gs(t.providerSessionId),d=Gs(t.targetSessionId);if(o&&o!==c&&o!==d||i&&i!==c&&i!==d)return null;const p=Fr(e.workspacePath);if(p){const u=Fr(t.workspaceName);if(u&&!v1(u,p))return null}return y1(t,n)}function gd(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function k1({ides:e,conversations:t,onOpenSession:n}){const[a,r]=l.useState(null),o=l.useRef(null),i=l.useCallback(()=>{o.current=null,r(null)},[]),c=l.useCallback(d=>{o.current=d,r(d)},[]);return l.useEffect(()=>{if(!a)return;const d=Fr(a.workspacePath),p=e.find(m=>{var x,w,b,C;if(!m||m.type==="adhdev-daemon"||Bm(m.daemonId||m.id)!==a.machineId||(Ma(m)?"cli":Rn(m)?"acp":"ide")!==a.kind)return!1;const S=String(m.agentType||m.type||"");if(a.providerType&&S!==a.providerType)return!1;if(a.resumeSessionId)return String(m.providerSessionId||"")===a.resumeSessionId;if(a.launchedSessionId){const k=String(a.launchedSessionId||"");return[m.providerSessionId,m.sessionId,m.instanceId,m.id].map(v=>String(v||"")).filter(Boolean).includes(k)}if(d){const k=Fr(m.workspace||m.runtimeWorkspaceLabel);return k?k===d:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((C=(b=(w=(x=m.activeChat)==null?void 0:x.messages)==null?void 0:w.at)==null?void 0:b.call(w,-1))==null?void 0:C.timestamp)||0)>=a.startedAt-5e3});if(!p)return;const u=Fm({entrySessionId:p.sessionId,entryInstanceId:p.instanceId,entryRouteId:p.id,conversations:t});u&&(i(),n(u))},[i,t,e,n,a]),l.useEffect(()=>ft.onStatusEvent(d=>{const p=o.current;if(!p)return;const u=w1(p,d,t);u&&(i(),n(u))}),[i,t,n]),l.useEffect(()=>{if(!a)return;const d=window.setTimeout(()=>{r(p=>!p||p.startedAt!==a.startedAt?p:(o.current=null,null))},45e3);return()=>window.clearTimeout(d)},[a]),{trackPendingLaunch:c}}function S1(e,t){var a,r,o,i;const n={cliType:e};return(a=t==null?void 0:t.workspacePath)!=null&&a.trim()?n.dir=t.workspacePath.trim():t!=null&&t.workspaceId?n.workspaceId=t.workspaceId:t!=null&&t.useHome&&(n.useHome=!0),(r=t==null?void 0:t.resumeSessionId)!=null&&r.trim()&&(n.resumeSessionId=t.resumeSessionId.trim()),Array.isArray(t==null?void 0:t.cliArgs)&&t.cliArgs.length>0&&(n.cliArgs=t.cliArgs),(o=t==null?void 0:t.initialModel)!=null&&o.trim()&&(n.initialModel=t.initialModel.trim()),(i=t==null?void 0:t.initialThinkingLevel)!=null&&i.trim()&&(n.initialThinkingLevel=t.initialThinkingLevel.trim()),t!=null&&t.settings&&(n.settings=t.settings),n}function C1(e,t,n){var i,c,d,p;const a={meshId:e.trim()};t.trim()&&(a.cliType=t.trim());const r=(i=n==null?void 0:n.initialModel)==null?void 0:i.trim(),o=(c=n==null?void 0:n.initialThinkingLevel)==null?void 0:c.trim();return r&&(a.initialModel=r),o&&(a.initialThinkingLevel=o),(d=n==null?void 0:n.settings)!=null&&d.autoApproveMode?a.autoApproveMode=n.settings.autoApproveMode:typeof((p=n==null?void 0:n.settings)==null?void 0:p.autoApprove)=="boolean"&&(a.autoApprove=n.settings.autoApprove),a}function j1({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:n,activeConv:a,ides:r,setCliViewModeOverrides:o}){const i=pl(),{launchCli:c}=qr(),d=l.useCallback(async(x,w)=>Dl(e,x,w),[e]),p=l.useCallback(async(x,w)=>{if(!w.trim())return{ok:!1,error:"Choose a workspace path first."};try{const b=await e(x,"workspace_add",{path:w.trim()});return b!=null&&b.success?{ok:!0}:{ok:!1,error:(b==null?void 0:b.error)||"Could not save workspace"}}catch(b){return{ok:!1,error:b instanceof Error?b.message:"Could not save workspace"}}},[e]),u=l.useCallback(async(x,w,b)=>{var C;try{const k={ideType:w,enableCdp:!0};(C=b==null?void 0:b.workspacePath)!=null&&C.trim()&&(k.workspace=b.workspacePath.trim());const y=await e(x,"launch_ide",k);return!(y!=null&&y.success)&&(y==null?void 0:y.success)!==void 0?{ok:!1,error:(y==null?void 0:y.error)||"Could not launch IDE"}:(t({machineId:x,kind:"ide",providerType:w,workspacePath:(b==null?void 0:b.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(k){return{ok:!1,error:k instanceof Error?k.message:"Could not launch IDE"}}},[e,t]),m=l.useCallback(async(x,w,b,C)=>{const k=Date.now();try{const y=S1(b,C),v=await c(x,y),j=(v==null?void 0:v.result)||v,N=(j==null?void 0:j.sessionId)||(j==null?void 0:j.id);return v!=null&&v.success&&N?(t({machineId:x,kind:w,providerType:b,workspacePath:(C==null?void 0:C.workspacePath)||null,resumeSessionId:(C==null?void 0:C.resumeSessionId)||null,launchedSessionId:N,startedAt:k}),{ok:!0}):v!=null&&v.success?(t({machineId:x,kind:w,providerType:b,workspacePath:(C==null?void 0:C.workspacePath)||null,resumeSessionId:(C==null?void 0:C.resumeSessionId)||null,startedAt:k}),{ok:!0}):{ok:!1,error:(v==null?void 0:v.error)||(j==null?void 0:j.error)||`Could not launch ${w.toUpperCase()} session`,code:(v==null?void 0:v.code)||(j==null?void 0:j.code)||void 0}}catch(y){return gd(y)?(t({machineId:x,kind:w,providerType:b,workspacePath:(C==null?void 0:C.workspacePath)||null,resumeSessionId:(C==null?void 0:C.resumeSessionId)||null,startedAt:k}),{ok:!0}):{ok:!1,error:y instanceof Error?y.message:`Could not launch ${w.toUpperCase()} session`}}},[c,e,t]),h=l.useCallback(async x=>{var w;if(i!=null&&i.listMeshes)return i.listMeshes(x);if(!x)return[];try{const b=await e(x,"list_meshes",{}),C=(b==null?void 0:b.result)??b;if((C==null?void 0:C.success)===!1)throw new Error((C==null?void 0:C.error)||"Could not load meshes");return(Array.isArray(C==null?void 0:C.meshes)?C.meshes:Array.isArray((w=C==null?void 0:C.result)==null?void 0:w.meshes)?C.result.meshes:[]).map(y=>{var v;return{id:String((y==null?void 0:y.id)||""),name:String((y==null?void 0:y.name)||(y==null?void 0:y.id)||"Untitled mesh"),repoIdentity:(y==null?void 0:y.repoIdentity)||(y==null?void 0:y.repo_identity)||null,workspace:Array.isArray(y==null?void 0:y.nodes)&&y.nodes.length>0?String(((v=y.nodes[0])==null?void 0:v.workspace)||""):null,nodesCount:Array.isArray(y==null?void 0:y.nodes)?y.nodes.length:void 0,status:(y==null?void 0:y.status)||null}}).filter(y=>y.id)}catch(b){throw console.error("List meshes failed",b),b}},[i,e]),g=l.useCallback(async(x,w,b,C)=>{if(!w.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(x,w,b,C);const k=Date.now();try{const y=C1(w,b,C),v=await e(x,"launch_mesh_coordinator",y),j=(v==null?void 0:v.result)??v;if((j==null?void 0:j.success)===!1||(v==null?void 0:v.success)===!1){const A=String((j==null?void 0:j.code)||(v==null?void 0:v.code)||""),T=x1((j==null?void 0:j.meshCoordinatorSetup)||(j==null?void 0:j.manualSetup)||(v==null?void 0:v.meshCoordinatorSetup)||(v==null?void 0:v.manualSetup));return{ok:!1,error:(j==null?void 0:j.error)||(v==null?void 0:v.error)||"Could not launch mesh coordinator",code:A||void 0,manualSetup:T}}const N=(j==null?void 0:j.sessionId)||(j==null?void 0:j.id);return N?n(N):t({machineId:x,kind:"cli",providerType:(j==null?void 0:j.cliType)||b.trim()||void 0,workspacePath:(j==null?void 0:j.workspace)||null,startedAt:k}),{ok:!0}}catch(y){return gd(y)?(t({machineId:x,kind:"cli",providerType:b.trim()||void 0,startedAt:k}),{ok:!0}):{ok:!1,error:y instanceof Error?y.message:"Could not launch mesh coordinator"}}},[i,n,e,t]),S=l.useCallback(async(x,w)=>{if(!x||!w)return[];try{const b=await e(x,"list_saved_sessions",{providerType:w,kind:"cli",limit:30}),C=(b==null?void 0:b.result)??b;return Array.isArray(C==null?void 0:C.sessions)?C.sessions:[]}catch(b){return console.error("List saved sessions failed",b),[]}},[e]),f=l.useCallback(async x=>{await Mm({conversation:a,mode:x,ides:r,sendDaemonCommand:e,setCliViewModeOverrides:o})},[a,r,e,o]);return{handleBrowseMachineDirectory:d,handleSaveMachineWorkspace:p,handleLaunchMachineIde:u,handleLaunchMachineProvider:m,handleListMachineMeshes:h,handleLaunchMeshCoordinator:g,handleListMachineSavedSessions:S,setActiveCliViewMode:f}}function N1(e){switch(e){case"notification-open":case"toast-open":case"conversation-open":case"requested-tab":return!0;case"dockview-shortcut":case"dockview-focus":case"dockview-move":case"dockview-split":case"stored-layout-restore":case"passive-tab-sync":return!1;default:return!1}}function A1(e,t,n=Date.now()){return!e||!N1(t)?null:{tabKey:e,nonce:n}}function T1({isMobile:e,conversations:t,visibleConversations:n,groupActiveTabIds:a,focusedGroup:r,groupedConvs:o,setSearchParams:i}){const[c,d]=l.useState(null),[p,u]=l.useState(null),m=l.useMemo(()=>{var x,w;if(!e){if(c){const b=t.find(C=>C.tabKey===c);if(b)return b}return n[0]}const f=a[r];if(f){const b=t.find(C=>C.tabKey===f);if(b)return b}return((x=o[r])==null?void 0:x[0])||((w=o[0])==null?void 0:w[0])},[t,c,r,a,o,e,n]),h=l.useCallback(f=>{d(f)},[]),g=l.useCallback(f=>{d(f.tabKey),i(x=>{const w=new URLSearchParams(x),b=sk(f);return b?w.set("activeTab",b):w.delete("activeTab"),w},{replace:!0})},[i]),S=l.useCallback((f,x)=>{const w=A1(f,x);w&&u(w)},[]);return{activeConv:m,openDesktopConversation:g,requestScrollToBottom:S,scrollToBottomRequest:p,setDesktopActiveTab:h}}function M1(e){const t=e.completedKey||null,n=e.pendingKey||null;return e.shouldMarkSeen?t===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:n!==null&&n!==e.autoReadKey,nextPendingKey:n===e.autoReadKey?n:null}:n===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:!1,nextPendingKey:n}:{shouldSchedule:!0,shouldCancelPending:n!==null&&n!==e.autoReadKey,nextPendingKey:e.autoReadKey}:{shouldSchedule:!1,shouldCancelPending:!!n,nextPendingKey:null}}function D1(e){const t=String(e.liveState.completionMarker||""),n=String(e.liveState.seenCompletionMarker||""),a=String(e.liveState.inboxBucket||"idle"),r=!!e.liveState.unread,o=[e.tabKey,e.historySessionId||"",t,n,a,r?"1":"0"].join(":");return{shouldMarkSeen:!!(a==="task_complete"&&r&&(!t||t!==n)),autoReadKey:o,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function P1({activeConv:e,isMobile:t,liveSessionInboxState:n,sendDaemonCommand:a}){const r=l.useRef(null),o=l.useRef(null),i=l.useRef(null),c=l.useRef(null),d=l.useRef(null);l.useEffect(()=>{const p=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),o.current=null};if(t){p(),r.current=null;return}if(!(e!=null&&e.sessionId)){p(),r.current=null;return}const u=Js(e,n),m=D1({tabKey:e.tabKey,historySessionId:Qr(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:mn(e),liveState:u}),h=m.autoReadKey,g=M1({autoReadKey:h,shouldMarkSeen:m.shouldMarkSeen,completedKey:r.current,pendingKey:o.current});if(!m.shouldMarkSeen){g.shouldCancelPending&&p(),r.current=h;return}if(!g.shouldSchedule)return;g.shouldCancelPending&&p();const S=()=>{if(document.visibilityState!=="visible"||r.current===h)return;r.current=h,o.current=null,i.current=null,c.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const x=m.readAt;a(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:x,completionMarker:m.completionMarker}).catch(()=>{})};if(o.current=g.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(S,1500);const x=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};d.current=x,document.addEventListener("visibilitychange",x);return}const f=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(S,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=f,document.addEventListener("visibilitychange",f)},[e,t,n,a]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function $o(e){if(!e)return"";const t=String(e.workspacePath||"").trim();if(t)return t;const n=String(e.workspaceName||"").trim();return/^(?:~\/|\/|[A-Za-z]:[\\/])/.test(n)?n:""}function I1({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:n,ides:a,sendDaemonCommand:r,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:d}){var _;const{launchCli:p}=qr(),[u,m]=l.useState(!1),[h,g]=l.useState([]),[S,f]=l.useState(()=>Ut()),[x,w]=l.useState(!1),[b,C]=l.useState(null),k=l.useRef(null),y=l.useMemo(()=>n||t||e,[e,n,t]),v=!!y&&ht(y)&&!pt(y),j=l.useMemo(()=>{if(!y||!v)return null;const H=y.daemonId||y.routeId||"",B=As(y),$=$o(y);return`${H}:${B}:${y.providerSessionId||""}:${$}`},[y,v]),N=l.useMemo(()=>!y||!v?"":$o(y),[y,v]),{isCreatingChat:A,isRefreshingHistory:T,handleSwitchSession:P,handleNewChat:M,handleRefreshHistory:D}=Em({sendDaemonCommand:r,activeConv:y,chats:(_=a.find(H=>H.id===(y==null?void 0:y.routeId)))==null?void 0:_.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),L=l.useCallback(()=>{m(!0)},[]),O=l.useCallback(()=>{m(!1)},[]),E=l.useCallback(async()=>{if(!(!y||!v||x)){w(!0);try{const H=y.daemonId||y.routeId,B=As(y),$=$o(y),F=await r(H,"list_saved_sessions",{agentType:B,providerType:B,kind:"cli",limit:50,...y.providerSessionId?{providerSessionId:y.providerSessionId}:{},...$?{workspace:$}:{}}),W=(F==null?void 0:F.result)??F;g(Array.isArray(W==null?void 0:W.sessions)?W.sessions:[])}catch(H){console.error("Refresh saved sessions failed",H),g([])}finally{w(!1)}}},[y,x,v,r]);l.useEffect(()=>{if(!u){k.current=null;return}if(!v){k.current=null,g([]),w(!1);return}!j||x||k.current!==j&&(k.current=j,E())},[E,u,x,v,j]);const I=l.useCallback(async H=>{if(!y||!v||!H.providerSessionId||!H.workspace)return;const B=y.daemonId||y.routeId,$=As(y);try{C(H.providerSessionId);const F=await p(B,{cliType:$,dir:H.workspace,resumeSessionId:H.providerSessionId,initialModel:dp(H.summaryMetadata,"model",{preferShortValue:!0})||void 0}),W=(F==null?void 0:F.result)??F,Y=typeof(W==null?void 0:W.sessionId)=="string"?W.sessionId:typeof(W==null?void 0:W.id)=="string"?W.id:"";Y&&d(V=>{const ee=new URLSearchParams(V);return ee.set("activeTab",Y),ee},{replace:!0}),O()}catch(F){console.error("Resume saved session failed",F)}finally{C(null)}},[O,y,v,r,d]);return{historyModalOpen:u,openHistoryModal:L,closeHistoryModal:O,historyTargetConv:y,isSavedSessionHistoryTarget:v,isHistoryCreatingChat:A,isHistoryRefreshingHistory:T,handleHistorySwitchSession:P,handleHistoryNewChat:M,handleHistoryRefresh:D,savedHistorySessions:h,savedHistoryFilters:S,setSavedHistoryFilters:f,missingWorkspaceResumePath:N,isSavedHistoryLoading:x,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:E,handleResumeSavedHistorySession:I}}function L1({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c}){const[d,p]=l.useState(null),[u,m]=l.useState(null),h=l.useMemo(()=>{if(e||!a)return null;const w=c(a);return w&&!ht(w)&&!pt(w)?w:null},[e,a,c]),g=l.useMemo(()=>{const w=d==null?void 0:d.routeId;if(!w)return null;const b=d!=null&&d.tabKey?o.find(C=>C.tabKey===d.tabKey):r?o.find(C=>C.tabKey===r):null;return(b==null?void 0:b.routeId)===w?b:hs(o,w)},[o,d,r]),S=l.useMemo(()=>{if(g)return i.find(w=>w.id===g.routeId)},[i,g]);l.useEffect(()=>{h&&(p({routeId:h.routeId,tabKey:Mc(h)}),m(h),n({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,n,h]);const f=l.useCallback(w=>{w&&(p({routeId:w.routeId,tabKey:Mc(w)}),m(w))},[]),x=l.useCallback(()=>{p(null),m(null)},[]);return{remoteDialogConv:g,remoteDialogIdeEntry:S,remoteDialogActiveConv:u,setRemoteDialogActiveConv:m,openRemoteDialog:f,closeRemoteDialog:x}}function R1({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:p}){const{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:h,setRemoteDialogActiveConv:g,openRemoteDialog:S,closeRemoteDialog:f}=L1({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c}),[x,w]=l.useState(!1),[b,C]=l.useState(null),k=l.useCallback(async j=>{const N=j||d;!N||!ht(N)&&!pt(N)||(C(N),w(!0))},[d]),y=l.useCallback(()=>{w(!1),C(null)},[]),v=l.useCallback(async j=>{const N=b||d;if(!N||!ht(N)&&!pt(N)){y();return}w(!1);try{const A=As(N),T=N.routeId||N.daemonId||"";await p(T,"stop_cli",{cliType:A,targetSessionId:N.sessionId,mode:j,...Zr(N)})}catch(A){console.error("Stop CLI failed:",A)}finally{C(null)}},[d,y,b,p]);return{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:h,setRemoteDialogActiveConv:g,openRemoteDialog:S,closeRemoteDialog:f,cliStopDialogOpen:x,cliStopTargetConv:b,requestCliStop:k,cancelCliStop:y,confirmCliStop:v}}function Fo(e,t=!0){return(e??!0)&&t}const Pl=l.memo(function({activeConv:t,clearToken:n,isCliTerminal:a,ideEntry:r,terminalRef:o,handleModalButton:i,handleRelaunch:c,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m=null,handleFocusAgent:h,isFocusingAgent:g,actionLogs:S,userName:f,scrollToBottomRequestNonce:x,isInputActive:w=!0,isVisible:b=!0}){const C=a,k=!a,y=Fo(b,C),v=Fo(b,k),j=Fo(b),N=Nm(t),A=N.status||N.modalMessage||N.modalButtons?{...t,...N.status?{status:N.status}:{},...N.modalMessage!==void 0?{modalMessage:N.modalMessage}:{},...N.modalButtons!==void 0?{modalButtons:N.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(ep,{activeConv:A,onModalButton:i}),A.transport!=="pty"&&A.transport!=="acp"&&A.cdpConnected===!1?s.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:s.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[s.jsx("span",{className:"text-sm",children:s.jsx(fn,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:c,children:"Relaunch with CDP"})]})}):null,A.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!a,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:C?"visible":"hidden",pointerEvents:C?"auto":"none"},children:s.jsx(HS,{activeConv:A,clearToken:n,terminalRef:o,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,isVisible:y,isInputActive:w&&y})}),s.jsx("div",{"aria-hidden":a,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:k?"visible":"hidden",pointerEvents:k?"auto":"none"},children:s.jsx(Li,{activeConv:A,ideEntry:r,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:h,isFocusingAgent:g,actionLogs:S,userName:f,scrollToBottomRequestNonce:x,isInputActive:w&&v,isVisible:v})})]}):s.jsx(Li,{activeConv:A,ideEntry:r,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:h,isFocusingAgent:g,actionLogs:S,userName:f,scrollToBottomRequestNonce:x,isInputActive:w&&j,isVisible:j})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.handleForceSendChat===t.handleForceSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function E1({conversation:e,className:t="",onOpenNativeConversation:n,onOpenMachine:a,interactive:r=!0,meshOnly:o=!1}){var k,y,v;const{t:i}=Ce("common"),c=Ea(),d=Bs(e),p=o?null:jp(e),u=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),m=!o&&e.streamSource==="agent-stream"&&!!e.agentName,h=!o&&!m&&(e.transport==="pty"||e.transport==="acp"),g=Wn(e),S=tk(e),f=(k=e.settings)==null?void 0:k.meshNodeFor,x=e.meshQueueStats,w=((y=e.coordinator)==null?void 0:y.meshId)||((v=e.settings)==null?void 0:v.meshCoordinatorFor),b=l.useCallback(()=>{if(a){a();return}d&&c("/dashboard",{state:{openMachineId:d}})},[d,c,a]),C=l.useCallback(()=>{if(n){n();return}const j=$m(e);j&&c(Ia(j))},[e,c,n]);return!u&&!m&&!h&&!p&&!f&&!x?null:s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[u&&(r?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:C,title:S,children:[s.jsx(bs,{size:12}),s.jsx("span",{children:S})]}):s.jsxs("span",{className:"conversation-meta-chip",title:S,children:[s.jsx(bs,{size:12}),s.jsx("span",{children:S})]})),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(Na,{size:12}),s.jsx("span",{children:g})]}),h&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(Na,{size:12}),s.jsx("span",{children:g})]}),p&&(r?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:b,title:p,children:[s.jsx(Ys,{size:12}),s.jsx("span",{children:p})]}):s.jsxs("span",{className:"conversation-meta-chip",title:p,children:[s.jsx(Ys,{size:12}),s.jsx("span",{children:p})]})),f&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(Ys,{size:12}),s.jsx("span",{children:i("dashboard.metaChips.meshNode")})]}),w&&x&&s.jsxs("span",{className:`conversation-meta-chip ${x.pending>0?"is-active":""}`,style:x.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${x.pending} pending, ${x.assigned} assigned, ${x.completed} completed, ${x.failed} failed`,children:[s.jsx(gb,{size:12}),s.jsxs("span",{children:[x.pending," Pending"]})]})]})}function _1({selectedConversation:e,isAcp:t,isStandalone:n,selectedIdeEntry:a,actionLogs:r,userName:o,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:d,onBack:p,onOpenNativeConversation:u,onOpenMachine:m,onOpenHistory:h,onOpenRemote:g,onOpenMeshGraph:S,onStopCli:f,cliViewMode:x,onSetCliViewMode:w,handleSendChat:b,handleForceSendChat:C,handleFocusAgent:k,handleModalButton:y,handleRelaunch:v}){var M,D;const j=l.useRef(null),N=ht(e)&&!t,A=N&&x==="terminal",T=!!e.daemonId&&!!((M=e.coordinator)!=null&&M.meshId||(D=e.settings)!=null&&D.meshCoordinatorFor),P=n?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${P} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:s.jsx(Zi,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:wt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(E1,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>m(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[N&&x&&s.jsx(sm,{mode:x,onChange:w,compact:!0}),N&&f&&s.jsx("button",{onClick:()=>{f(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(Pt,{size:14})}),T&&S&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(as,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>h(e),type:"button",children:s.jsx(tl,{size:14})}),!t&&!N&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:s.jsx(bs,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(Pl,{activeConv:e,clearToken:0,isCliTerminal:A,ideEntry:a,terminalRef:j,handleModalButton:y,handleRelaunch:v,handleSendChat:b,handleForceSendChat:C,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:k,isFocusingAgent:d,actionLogs:r,userName:o})})]})}const Bo={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 H1(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Wm(){const[e,t]=l.useState("unix"),[n,a]=l.useState("powershell"),[r,o]=l.useState(!1),i=e==="unix"?"unix":n;l.useEffect(()=>{t(H1())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(Bo[i].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!1),2e3)},[i]);return s.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("unix"),children:"🍎🐧 macOS / Linux"}),s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("windows"),children:"🪟 Windows"})]}),e==="windows"&&s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${n==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>a("powershell"),children:"⚡ PowerShell"}),s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${n==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>a("cmd"),children:">_ CMD"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:c,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:Bo[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Bo[i].cmd}),s.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:r?"✓":"📋"})]}),s.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",s.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function Om({section:e,onSectionChange:t}){const n=[{key:"machines",label:"Machines",icon:bs},{key:"chats",label:"Chats",icon:yn}];return s.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:s.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:n.map(({key:a,label:r,icon:o})=>{const i=e===a;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${i?"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:i?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(a),type:"button","aria-pressed":i,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${i?"text-accent-primary":"bg-transparent text-current"}`,style:i?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(o,{size:15})}),s.jsx("span",{children:r})]},a)})})})}function Xa({title:e,className:t=""}){return s.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${t}`,children:s.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function jn({children:e,className:t=""}){return s.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${t}`,children:e})}function sn({icon:e,title:t,subtitle:n,children:a}){return s.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[s.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:n}),a]})}function $1({conversation:e,onCancel:t,onConfirm:n}){const{t:a}=Ce(),r=wt(e);return s.jsx(Yt,{children:s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:t,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-hide-confirm-title",className:"card fade-in mobile-compact-dialog relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-bg-primary",children:[s.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base md:text-lg font-extrabold",children:a("mobileInbox.hideTitle",{title:r})}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:a("mobileInbox.hideDescription")})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s.jsx("button",{onClick:n,className:"btn btn-primary w-full justify-center min-h-[42px]",children:a("mobileInbox.hide")}),s.jsx("button",{onClick:t,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:a("common.cancel")})]})]})]})})}function Za({item:e,type:t,getAvatarText:n,onOpenConversation:a,onRequestHideConversation:r,onRequestStopCli:o,onOpenMeshGraph:i,onCollectChatDebugBundle:c,isMuted:d,onToggleMute:p}){const{t:u}=Ce(),m=t==="needs_attention"||t==="task_complete",h=t==="working",g=t==="earlier",S=t==="task_complete",{isReconnecting:f,isConnecting:x}=wn(e.conversation),w=wt(e.conversation),b=On(e.conversation),C=Xp(e.conversation,{requiresAction:t==="needs_attention"}),k=m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":h?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":g?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",y=m?"bg-accent-primary shadow-glow":h?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":g?"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",v=g?"text-text-secondary":"text-text-primary",j=g?"text-text-muted":"text-text-secondary",N=g?"text-text-secondary opacity-80":"text-text-muted",A=g?"text-text-muted opacity-80":"text-text-muted",T=!h&&!S,P=Qp(e.conversation),M="text-[color:var(--status-warning)]",D=L=>{if(!c)return;L.preventDefault(),L.stopPropagation();const O=c==null?void 0:c(e.conversation);Promise.resolve(O).catch(E=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",E)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${k}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[m||h?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${y}`,style:m?{color:"var(--accent-on-primary)"}:void 0,children:n(w)}),P&&i&&s.jsx("button",{type:"button",className:"mobile-inbox-mesh-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:L=>{L.preventDefault(),L.stopPropagation(),i(e.conversation)},"aria-label":u("mobileInbox.openMeshGraphFor",{title:w}),title:u("mobileInbox.openLiveMeshGraph"),children:s.jsx(as,{size:13})})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>a(e.conversation),onContextMenu:D,type:"button",children:[s.jsx("div",{className:"flex items-center gap-2 pr-[124px]",children:s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${v}`,children:w})}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${j}`,children:[s.jsx("span",{className:"truncate",children:b}),s.jsx(Pr,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),f?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${M} animate-pulse`,children:u("mobileInbox.reconnectingItem")})]}):x?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:u("mobileInbox.connectingItem")})]}):C==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:M,children:u("mobileInbox.actionNeeded")})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${N}`,children:e.preview})]}),s.jsxs("div",{className:"mobile-inbox-corner-actions absolute top-3 right-3 flex items-center gap-1.5",children:[T&&s.jsx("span",{className:`mr-0.5 text-[11px] font-medium shrink-0 ${A}`,children:Xu(e.timestamp)}),S&&s.jsx("span",{className:"rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:u("mobileInbox.done")}),p&&s.jsx("button",{type:"button",className:`mobile-inbox-mute-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border transition-colors ${d?"border-amber-500/60 bg-amber-500 text-white hover:bg-amber-600":"border-border-subtle bg-bg-primary/70 text-text-muted hover:border-border-default hover:text-text-primary"}`,onClick:L=>{L.preventDefault(),L.stopPropagation(),p()},"aria-label":d?u("mobileInbox.unmute",{title:w}):u("mobileInbox.mute",{title:w}),title:u(d?"mobileInbox.mutedTitle":"mobileInbox.muteNotifications"),children:d?s.jsx(Bu,{size:13}):s.jsx(Vn,{size:13})}),r&&s.jsx("button",{type:"button",className:"mobile-inbox-hide-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:L=>{L.preventDefault(),L.stopPropagation(),r()},"aria-label":u("mobileInbox.hideConversationAria",{title:w}),title:u("mobileInbox.hideConversationTitle"),children:s.jsx(sl,{size:13})}),o&&s.jsx("button",{type:"button",className:"mobile-inbox-stop-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-status-error/30 bg-bg-primary/70 text-status-error transition-colors hover:border-status-error/60 hover:bg-status-error/10",onClick:L=>{L.preventDefault(),L.stopPropagation(),o()},"aria-label":u("mobileInbox.stopSessionAria",{title:w}),title:u("mobileInbox.stopSessionTitle"),children:s.jsx(Pt,{size:13})})]})]})},e.conversation.tabKey)}function er({size:e=32}){return s.jsx("div",{className:"flex flex-col items-center gap-2.5",children:s.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}})})}function xd({count:e,label:t}){return e<=0?null:s.jsxs("span",{className:"inline-flex items-center gap-1.5 text-accent-primary","aria-live":"polite",children:[s.jsxs("span",{className:"relative flex h-2 w-2 shrink-0",children:[s.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-accent-primary/60"}),s.jsx("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-accent-primary"})]}),s.jsx("span",{className:"font-semibold",children:t})]})}function F1({section:e,attentionItems:t,unreadItems:n,workingItems:a,completedItems:r,hiddenConversations:o,machineCards:i,getAvatarText:c,actionLogs:d,sendDaemonCommand:p,onOpenConversation:u,onShowAllHidden:m,onHideConversation:h,onOpenMeshGraph:g,onStopCli:S,onOpenNewSession:f,onOpenMachine:x,onOpenSettings:w,onSectionChange:b,wsStatus:C="connected",initialDataLoaded:k=!0,isStandalone:y=!1,onCollectChatDebugBundle:v,isConversationMuted:j,onToggleMuteConversation:N}){const{t:A}=Ce(),[T,P]=l.useState(null),M=C==="disconnected"||C==="reconnecting"||C==="offline"||C==="auth_failed",D=!M&&!k,L=i.length>0,O=t.length>0||n.length>0||a.length>0||r.length>0,E=A(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),I=y?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",_=y?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",H=l.useCallback(async F=>{const W=cn(F);if(!W)return;const Y=Array.isArray(F.messages)?F.messages:[],V=Ip({activeConv:F,visibleMessages:Y,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:Y.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),ee=await p(W,"get_chat_debug_bundle",{...ln(F),delivery:"daemon_file",frontendSnapshot:V}),le=ya(ee),ie=Ep(le),Z=await Rp(ie);Z==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),ft.showToast(Lp(le,{locatorCopyStatus:Z}),Z==="failed"?"warning":"success")},[d,p]),B=v||H,$=l.useCallback(()=>{T&&(h==null||h(T),P(null))},[T,h]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${I}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:E}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||n.length>0)&&s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[s.jsx(Vn,{size:13}),s.jsx("span",{children:t.length+n.length})]}),s.jsx("button",{onClick:w,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:s.jsx(Gr,{size:18})})]})]})}),s.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${_}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:M?s.jsx(sn,{icon:s.jsx(er,{}),title:A(C==="offline"?"mobileInbox.networkOffline":C==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:A(C==="offline"?"mobileInbox.waitingForNetwork":C==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):D?s.jsx(sn,{icon:s.jsx(er,{}),title:A("mobileInbox.loading"),subtitle:A("mobileInbox.loadingSubtitle")}):i.length===0?s.jsx(sn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:A(y?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:A(y?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!y&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(Wm,{})})}):s.jsx(jn,{children:i.map((F,W)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${W>0?"border-t border-border-subtle/70":""}`,onClick:()=>x(F.id),type:"button",children:[s.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:c(F.label)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:F.label}),s.jsxs("span",{className:"flex items-center gap-2 text-[11px] font-medium text-text-muted shrink-0",children:[s.jsx(xd,{count:F.generatingCount,label:A("mobileInbox.generatingCount",{count:F.generatingCount})}),F.unread>0?s.jsx("span",{className:"text-accent-primary",children:A("mobileInbox.newCount",{count:F.unread})}):F.total>0?A("mobileInbox.chatCount",{count:F.total}):A("mobileInbox.idle")]})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:F.subtitle}),F.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[A("mobileInbox.chatCount",{count:F.total}),F.unread>0?A("mobileInbox.unreadSuffix",{count:F.unread}):"",F.generatingCount>0?A("mobileInbox.collapsedGeneratingSuffix",{count:F.generatingCount}):""]}):F.generatingCount>0?s.jsx("div",{className:"text-[13px] text-accent-primary mt-0.5 font-medium",children:A("mobileInbox.generatingCount",{count:F.generatingCount})}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:A("mobileInbox.noActiveChats")})]})]},F.id))})}),e==="chats"&&t.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(Xa,{title:A("mobileInbox.needsAttention"),className:"mb-0"}),s.jsx(jn,{children:t.map((F,W)=>s.jsx("div",{className:W>0?"border-t border-border-subtle/70":"",children:s.jsx(Za,{item:F,type:"needs_attention",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:h?()=>P(F.conversation):void 0,onRequestStopCli:S?()=>S(F.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:B,isMuted:j==null?void 0:j(F.conversation),onToggleMute:N?()=>N(F.conversation):void 0})},F.conversation.tabKey))})]}),e==="chats"&&n.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(Xa,{title:A("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),s.jsx(jn,{children:n.map((F,W)=>s.jsx("div",{className:W>0?"border-t border-border-subtle/70":"",children:s.jsx(Za,{item:F,type:"task_complete",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:h?()=>P(F.conversation):void 0,onRequestStopCli:S?()=>S(F.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:B,isMuted:j==null?void 0:j(F.conversation),onToggleMute:N?()=>N(F.conversation):void 0})},F.conversation.tabKey))})]}),e==="chats"&&a.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(Xa,{title:A("mobileInbox.workingNow"),className:"mb-0 mt-2"}),s.jsx(jn,{children:a.map((F,W)=>s.jsx("div",{className:W>0?"border-t border-border-subtle/70":"",children:s.jsx(Za,{item:F,type:"working",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:h?()=>P(F.conversation):void 0,onRequestStopCli:S?()=>S(F.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:B,isMuted:j==null?void 0:j(F.conversation),onToggleMute:N?()=>N(F.conversation):void 0})},F.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[r.length>0&&s.jsx(Xa,{title:A("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),r.length>0?s.jsx(jn,{children:r.map((F,W)=>s.jsx("div",{className:W>0?"border-t border-border-subtle/70":"",children:s.jsx(Za,{item:F,type:"earlier",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:h?()=>P(F.conversation):void 0,onRequestStopCli:S?()=>S(F.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:B,isMuted:j==null?void 0:j(F.conversation),onToggleMute:N?()=>N(F.conversation):void 0})},F.conversation.tabKey))}):O?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:A("mobileInbox.allCaughtUp")}):M?s.jsx(sn,{icon:s.jsx(er,{size:28}),title:A("mobileInbox.connecting"),subtitle:A("mobileInbox.connectingSubtitle")}):D?s.jsx(sn,{icon:s.jsx(er,{size:28}),title:A("mobileInbox.loading"),subtitle:A("mobileInbox.loadingSubtitle")}):L?s.jsx(sn,{icon:s.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:s.jsx(yn,{size:20})}),title:A("mobileInbox.noConversations"),subtitle:A("paneGroup.newSessionDescription"),children:f&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:f,"aria-label":A("paneGroup.newSession"),title:A("paneGroup.newSession"),children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s.jsx("span",{children:A("paneGroup.newSession")})]})}):s.jsx(sn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:A("mobileInbox.noMachinesConnected"),subtitle:A("mobileInbox.noMachinesSubtitle")})]}),e==="chats"&&o.length>0&&(()=>{const F=gg(o);return s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(jn,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:A("mobileInbox.hiddenTabs")}),s.jsx(xd,{count:F,label:A("mobileInbox.generatingCount",{count:F})})]}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[A("mobileInbox.collapsedCount",{count:o.length}),F>0?A("mobileInbox.collapsedGeneratingSuffix",{count:F}):""]})]}),s.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-[12px] font-semibold text-accent-primary hover:border-border-default",onClick:m,children:A("mobileInbox.restoreAll")})]})})})})()]}),e==="chats"&&f&&O&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:f,"aria-label":A("paneGroup.newSession"),title:A("paneGroup.newSession"),children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),T&&s.jsx($1,{conversation:T,onCancel:()=>P(null),onConfirm:$}),s.jsx(Om,{section:e,onSectionChange:b})]})}function B1(e){if(!e)return"";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(e))}catch{return new Date(e).toLocaleString()}}function Um(e){const t=[e.workspace||"Workspace unknown"],n=bn(e.summaryMetadata);n&&t.push(n),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const a=B1(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:a?`Updated ${a}`:"",preview:(e.preview||"").trim()}}function Il({title:e,description:t,currentPath:n,directories:a,busy:r=!1,error:o="",confirmLabel:i="Use this folder",onClose:c,onNavigate:d,onConfirm:p}){const[u,m]=l.useState(n),{t:h}=Ce("common");l.useEffect(()=>{m(n)},[n]);const g=b1(n),S=u.trim();return s.jsx(Yt,{children:s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:c,"aria-label":"Close folder browser",children:s.jsx(Pt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!g||r||d(g)},disabled:!g||r,children:[s.jsx(Zi,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:h("machine.workspaceBrowse.currentFolder")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:f=>m(f.target.value),onKeyDown:f=>{f.key!=="Enter"||!S||r||(f.preventDefault(),d(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"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!S||r||d(S)},disabled:!S||r,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:r?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):a.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:a.map(f=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>d(f.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx($n,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:f.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:f.path})]})]},f.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:c,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(S||n),disabled:!S&&!n||r,children:i})]})]})})})}function ro({title:e,description:t,details:n,workspaceOptions:a,selectedWorkspaceKey:r,onWorkspaceChange:o,confirmLabel:i,busyLabel:c,busy:d=!1,showArgsInput:p,argsValue:u,onArgsChange:m,showModelInput:h,modelValue:g,onModelChange:S,historyProviderNode:f,onConfirm:x,onCancel:w}){const{t:b}=Ce("common"),C=i??b("machine.launchConfirm.launch"),k=c??b("machine.launchConfirm.launching"),y=a==null?void 0:a.find(j=>j.key===r),v=s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:w,"aria-label":b("machine.launchConfirm.closeAria"),children:s.jsx(Pt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[a&&a.length>0&&o&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.workspace")}),s.jsx("select",{value:r||"",onChange:j=>o(j.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:a.map(j=>s.jsx("option",{value:j.key,children:j.label},j.key))}),(y==null?void 0:y.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:y.description})]}),f,n.map(j=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:j.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:j.value})]},`${j.label}:${j.value}`)),h&&S&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.languageModel")}),s.jsx("input",{type:"text",value:g||"",onChange:j=>S(j.target.value),placeholder:b("machine.launchConfirm.autoDetect"),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&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.cliArgs")}),s.jsx("input",{type:"text",value:u||"",onChange:j=>m(j.target.value),placeholder:b("machine.launchConfirm.cliArgsPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:w,disabled:d,children:b("machine.launchConfirm.cancel")}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:x,disabled:d,children:[s.jsx(Fu,{size:14}),d?k:C]})]})]})});return typeof document>"u"?v:Fs.createPortal(v,document.body)}function vd(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function qm(e){const{machine:t,currentWorkspacePath:n,currentWorkspaceId:a,includeHome:r=!0,homeLabel:o="Home directory",homeDescription:i="Launch without a workspace"}=e,c=[];r&&c.push({key:"__home__",label:o,description:i,workspaceId:null,workspacePath:null});for(const u of t.workspaces||[])c.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${vd(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const d=(n==null?void 0:n.trim())||"",p=d?(t.workspaces||[]).find(u=>u.path===d):null;if(d&&!p&&c.push({key:`custom:${d}`,label:vd(d),description:d,workspaceId:null,workspacePath:d}),a){const u=`saved:${a}`;if(c.some(m=>m.key===u))return{options:c,selectedKey:u}}return p?{options:c,selectedKey:`saved:${p.id}`}:d?{options:c,selectedKey:`custom:${d}`}:{options:c,selectedKey:"__home__"}}function W1(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function O1(e){return[W1(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function U1(e){return e.lastLaunchedAt?Kr(e.lastLaunchedAt):""}function Gm(e){return{metaText:O1(e),updatedLabel:U1(e)}}function Wo(e,t,n){return e?"ide":t>0?"cli":n>0?"acp":null}function q1({selectedMachineEntry:e,cliProviders:t,acpProviders:n,machineAction:a,onBrowseDirectory:r,onListSavedSessions:o}){var re,Ne,Pe,qe;const i=Qn(),[c,d]=l.useState(!1),p=(((re=e.detectedIdes)==null?void 0:re.length)||0)>0,u=l.useMemo(()=>(e.workspaces||[]).map(we=>({id:we.id,path:we.path,label:we.label})),[e]),m=e.defaultWorkspaceId||null,[h,g]=l.useState(m||((Ne=u[0])==null?void 0:Ne.id)||""),[S,f]=l.useState(""),[x,w]=l.useState(""),[b,C]=l.useState([]),[k,y]=l.useState(!1),[v,j]=l.useState(""),[N,A]=l.useState(!1),[T,P]=l.useState(Wo(p,t.length,n.length)),M=l.useRef(null),[D,L]=l.useState(null),O=l.useRef("__home__"),[E,I]=l.useState("__home__"),[_,H]=l.useState(""),[B,$]=l.useState(""),[F,W]=l.useState(""),[Y,V]=l.useState([]),[ee,le]=l.useState(()=>Ut().textQuery),[ie,Z]=l.useState(()=>Ut().workspaceQuery),[U,J]=l.useState(()=>Ut().modelQuery),[R,z]=l.useState(()=>Ut().resumableOnly),[ve,he]=l.useState(()=>Ut().sortMode),[ge,me]=l.useState(!1),[K,G]=l.useState(!1),X=l.useRef(null),ce=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const se=h==="__custom__"?S.trim():((Pe=u.find(we=>we.id===h))==null?void 0:Pe.path)||"",Ae=h==="__custom__"&&!!se&&a.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(a.message),pe=h!=="__custom__"&&((qe=u.find(we=>we.id===h))==null?void 0:qe.path)||"",fe=l.useMemo(()=>(e.recentLaunches||[]).map(we=>we.workspace),[e]),q=l.useCallback(async we=>{y(!0),j("");try{const Fe=await r(we);w(Fe.path),f(Fe.path),C(Fe.directories)}catch(Fe){j(Fe instanceof Error?Fe.message:"Could not load folder")}finally{y(!1)}},[r]),ye=l.useCallback(()=>{var Fe;g("__custom__"),A(!0);const we=Ml(e.platform,Tl(S.trim(),pe,fe,e.defaultWorkspacePath,(Fe=u.find(lt=>lt.id===m))==null?void 0:Fe.path,u.map(lt=>lt.path)));q(we)},[S,m,q,fe,pe,e.platform,u]),de=l.useCallback(we=>{if(we!=null&&we.workspaceId){g(we.workspaceId),f("");return}if(we!=null&&we.workspacePath){g("__custom__"),f(we.workspacePath);return}g(""),f("")},[]),Me=l.useCallback(we=>{if(g(we),we==="__custom__"){ye();return}f("")},[ye]),He=l.useCallback(we=>{g("__custom__"),f(we)},[]),je=l.useCallback((we,Fe)=>{M.current=Fe,O.current=we.selectedWorkspaceKey||"__home__",I(we.selectedWorkspaceKey||"__home__"),H(we.initialArgs||""),$(we.initialModel||""),W(""),V([]);const lt=we.providerType?`${e.id}:${we.providerType}`:null;if(KS(ce.current,lt)){const rt=Ut();le(rt.textQuery),Z(rt.workspaceQuery),J(rt.modelQuery),z(rt.resumableOnly),he(rt.sortMode)}ce.current=lt,L(we),we.providerType&&o&&(me(!0),o(we.providerType).then(rt=>V(rt||[])).catch(rt=>console.warn("Failed to load saved sessions",rt)).finally(()=>me(!1)))},[o,e.id]),be=l.useMemo(()=>nm(Y,{textQuery:ee,workspaceQuery:ie,modelQuery:U,resumableOnly:R,sortMode:ve}),[U,R,Y,ve,ee,ie]);l.useEffect(()=>{F&&(be.some(we=>we.providerSessionId===F)||W(""))},[be,F]);const et=l.useCallback(()=>{M.current&&(G(!0),M.current().finally(()=>{M.current=null,G(!1),L(null)}))},[]),De=l.useCallback(()=>{M.current=null,L(null)},[]),_e=l.useCallback(we=>{O.current=we,I(we)},[]);return l.useEffect(()=>{var we;X.current!==e.id&&(X.current=e.id,g(m||((we=u[0])==null?void 0:we.id)||"__custom__"),f(""),w(""),C([]),j(""),A(!1),le(Ut().textQuery),Z(Ut().workspaceQuery),J(Ut().modelQuery),z(Ut().resumableOnly),he(Ut().sortMode),ce.current=null,P(Wo(p,t.length,n.length)))},[n.length,t.length,m,p,e.id,u]),l.useEffect(()=>{var we;h!=="__custom__"&&(h&&u.some(Fe=>Fe.id===h)||g(m||((we=u[0])==null?void 0:we.id)||"__custom__"))},[m,h,u]),l.useEffect(()=>{T==="ide"&&p||T==="cli"&&t.length>0||T==="acp"&&n.length>0||P(Wo(p,t.length,n.length))},[T,n.length,t.length,p]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:p,workspaceRows:u,defaultWorkspaceId:m,workspaceChoice:h,customWorkspacePath:S,browseCurrentPath:x,browseDirectories:b,browseBusy:k,browseError:v,browseDialogOpen:N,activeLauncherKind:T,launchConfirm:D,launchConfirmWorkspaceKeyRef:O,launchConfirmWorkspaceKey:E,launchConfirmArgs:_,launchConfirmModel:B,launchConfirmResumeId:F,launchConfirmSavedSessions:Y,launchConfirmTextFilter:ee,launchConfirmWorkspaceFilter:ie,launchConfirmModelFilter:U,launchConfirmResumableOnly:R,launchConfirmSortMode:ve,filteredLaunchConfirmSavedSessions:be,launchConfirmSessionsLoading:ge,launchConfirmBusy:K,resolvedWorkspacePath:se,canCreateMissingWorkspace:Ae,openBrowseDialog:ye,loadBrowsePath:q,handleWorkspaceChoiceChange:Me,chooseCustomWorkspacePath:He,setCustomWorkspacePath:f,setBrowseDialogOpen:A,setActiveLauncherKind:P,openLaunchConfirm:je,handleConfirmLaunch:et,closeLaunchConfirm:De,setWorkspaceSelectionFromOption:de,setLaunchConfirmWorkspaceKeyAndSync:_e,setLaunchConfirmArgs:H,setLaunchConfirmModel:$,setLaunchConfirmResumeId:W,setLaunchConfirmTextFilter:le,setLaunchConfirmWorkspaceFilter:Z,setLaunchConfirmModelFilter:J,setLaunchConfirmResumableOnly:z,setLaunchConfirmSortMode:he}}function G1({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:n,cliProviders:a,acpProviders:r,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:c,isStandalone:d,section:p,showBottomNav:u,onBack:m,onSectionChange:h,onOpenConversation:g,onOpenRecent:S,onOpenMachineDetails:f,onMachineUpgrade:x,onLaunchDetectedIde:w,onAddWorkspace:b,onBrowseDirectory:C,onLaunchWorkspaceProvider:k,onListSavedSessions:y}){const{t:v}=Ce("common"),j=I=>I==="ide"?"IDE":I==="cli"?"CLI":"ACP",N=n.slice(0,4),A=t.slice(0,3),T=q1({selectedMachineEntry:e,cliProviders:a,acpProviders:r,machineAction:c,onBrowseDirectory:C,onListSavedSessions:y}),P=l.useMemo(()=>N.map(I=>{const{metaText:_,updatedLabel:H}=Gm(I);return{key:`recent-launch:${I.id}`,primary:I.label,secondary:_,updatedLabel:H,onClick:()=>{const{options:B,selectedKey:$}=qm({machine:{workspaces:T.workspaceRows,defaultWorkspaceId:T.defaultWorkspaceId},currentWorkspacePath:I.workspace,homeLabel:v("newSession.homeDirectory"),homeDescription:v("newSession.launchWithoutWorkspace")});T.openLaunchConfirm({title:I.kind==="ide"?Ir(v,"restart-ide",I.label):I.providerSessionId?rm(v,I.label):Ir(v,"start-fresh",I.label),description:I.kind==="ide"?Lr(v,"restart-ide"):I.providerSessionId?om(v):Lr(v,"start-fresh"),confirmLabel:I.kind==="ide"?Rr(v,"restart-ide"):I.providerSessionId?Ri(v,!0):Rr(v,"start-fresh"),busyLabel:I.kind==="ide"?Er(v,"restart-ide"):I.providerSessionId?am(v,!0):Er(v,"start-fresh"),workspaceOptions:B,selectedWorkspaceKey:$,details:[{label:"Mode",value:j(I.kind)},...I.providerType?[{label:"Provider",value:I.providerType}]:[]]},async()=>{const F=B.find(W=>W.key===T.launchConfirmWorkspaceKeyRef.current);T.setWorkspaceSelectionFromOption(F),await S({...I,workspace:(F==null?void 0:F.workspacePath)??null})})}}}),[T,S,N,v]),M=l.useMemo(()=>A.map(I=>({key:`recent-chat:${I.conversation.tabKey}`,primary:wt(I.conversation),secondary:yS(I.conversation,{timestampLabel:I.timestamp?Xu(I.timestamp):null}),unread:I.unread,onClick:()=>g(I.conversation)})),[g,A]),D=T.showAllRecent?P:P.slice(0,4),L=P.length>0,O=M.length>0,E=d?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${E} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":"Back",children:s.jsx(Zi,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:rs(e,{fallbackId:e.id})}),s.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[O&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:M.map(I=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${I.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:I.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:I.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:I.secondary})]},I.key))})]}),L&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:D.map(I=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:I.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:I.primary}),I.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:I.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:I.secondary})]},I.key))}),P.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>T.setShowAllRecent(I=>!I),children:T.showAllRecent?"Show fewer":`Show ${P.length-4} more`})})]}),!1,s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:x,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",i]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:f,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),T.browseDialogOpen&&s.jsx(Il,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:T.browseCurrentPath,directories:T.browseDirectories,busy:T.browseBusy,error:T.browseError,confirmLabel:"Use this folder",onClose:()=>T.setBrowseDialogOpen(!1),onNavigate:I=>{T.loadBrowsePath(I)},onConfirm:I=>{T.chooseCustomWorkspacePath(I),T.setBrowseDialogOpen(!1)}}),T.launchConfirm&&s.jsx(ro,{title:T.launchConfirm.title,description:T.launchConfirm.description,details:T.launchConfirm.details,workspaceOptions:T.launchConfirm.workspaceOptions,selectedWorkspaceKey:T.launchConfirmWorkspaceKey,onWorkspaceChange:T.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:T.launchConfirm.providerType?Ri(v,!!T.launchConfirmResumeId):T.launchConfirm.confirmLabel,busyLabel:T.launchConfirm.providerType?void 0:T.launchConfirm.busyLabel,busy:T.launchConfirmBusy,showArgsInput:T.launchConfirm.showArgsInput,argsValue:T.launchConfirmArgs,onArgsChange:T.setLaunchConfirmArgs,showModelInput:T.launchConfirm.showModelInput,modelValue:T.launchConfirmModel,onModelChange:T.setLaunchConfirmModel,historyProviderNode:T.launchConfirm.providerType&&(T.launchConfirmSessionsLoading||T.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),T.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:wl(v)}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:T.launchConfirmTextFilter,onChange:I=>T.setLaunchConfirmTextFilter(I.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmWorkspaceFilter,onChange:I=>T.setLaunchConfirmWorkspaceFilter(I.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmModelFilter,onChange:I=>T.setLaunchConfirmModelFilter(I.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsxs("select",{value:T.launchConfirmSortMode,onChange:I=>T.setLaunchConfirmSortMode(I.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:T.launchConfirmResumableOnly,onChange:I=>T.setLaunchConfirmResumableOnly(I.target.checked),disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:T.launchConfirmResumeId,onChange:I=>T.setLaunchConfirmResumeId(I.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:QS(v)}),T.filteredLaunchConfirmSavedSessions.map(I=>s.jsxs("option",{value:I.providerSessionId,disabled:!I.canResume,children:[I.title||I.providerSessionId," ",I.canResume?"":"(workspace missing)"]},I.providerSessionId))]}),!T.launchConfirmSessionsLoading&&T.launchConfirmSavedSessions.length>0&&T.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),T.launchConfirmResumeId&&(()=>{const I=T.filteredLaunchConfirmSavedSessions.find(H=>H.providerSessionId===T.launchConfirmResumeId);if(!I)return null;const _=Um(I);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:_.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:_.providerSessionId}),s.jsx("div",{className:"mt-1",children:_.metaLine}),_.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:_.updatedLabel}),_.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:_.preview})]})})()]}),onConfirm:T.handleConfirmLaunch,onCancel:T.closeLaunchConfirm}),u&&s.jsx(Om,{section:p,onSectionChange:h})]})}const yd=8e3;function z1(e){const t=e&&typeof e=="object"&&"result"in e?e.result:e,n=t&&typeof t=="object",a=n&&t.success===!1,r=n&&t.mirrorStale===!0;return!a&&!r?{confirmed:!0}:{confirmed:!1,reason:a&&typeof t.error=="string"?t.error:r?"the coordinator did not confirm the change":"command was rejected"}}function zm(e,t,n){const a=l.useRef(new Map),[,r]=l.useState(0),o=l.useCallback(()=>r(g=>g+1),[]);l.useEffect(()=>{const g=a.current;if(g.size===0)return;const S=Date.now();let f=!1;for(const[x,w]of g){const b=e.get(x),C=w.muted===void 0||(b?b.muted===w.muted:!1),k=w.hidden===void 0||(b?b.surfaceHidden===w.hidden:!1),y=S-w.at>yd;(C&&k||y)&&(g.delete(x),f=!0)}f&&o()},[e,o]),l.useEffect(()=>{if(a.current.size===0)return;const g=setInterval(()=>{const S=a.current,f=Date.now();let x=!1;for(const[w,b]of S)f-b.at>yd&&(S.delete(w),x=!0);x&&o(),S.size===0&&clearInterval(g)},1e3);return()=>clearInterval(g)});const i=l.useCallback((g,S)=>{const f=a.current.get(g);a.current.set(g,{...f,...S,at:Date.now()}),o()},[o]),c=l.useCallback(g=>{const S=g.sessionId,f=S?a.current.get(S):void 0;return(f==null?void 0:f.muted)!==void 0?f.muted:Js(g,e).muted??!1},[e]),d=l.useCallback(g=>{const S=g.sessionId,f=S?a.current.get(S):void 0;return(f==null?void 0:f.hidden)!==void 0?f.hidden:Js(g,e).surfaceHidden??!1},[e]),p=l.useCallback((g,S)=>{const f=Bs(g),x=g.sessionId;!f||!x||(i(x,S),t(f,"set_conversation_prefs",{sessionId:x,...S,...Zr(g)}).then(w=>{const b=z1(w);b.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",b.reason),a.current.delete(x),o(),n==null||n(`Couldn't update conversation — ${b.reason}`))}).catch(w=>{console.warn("[conversation-prefs] set_conversation_prefs failed",w),a.current.delete(x),o();const b=w instanceof Error?w.message:String(w??"the daemon is unreachable");n==null||n(`Couldn't update conversation — ${b}`)}))},[t,i,o,n]),u=l.useCallback(g=>{p(g,{muted:!c(g)})},[p,c]),m=l.useCallback((g,S)=>{p(g,{hidden:S})},[p]),h=l.useCallback(g=>{p(g,{hidden:!d(g)})},[p,d]);return{isMuted:c,isHidden:d,toggleMute:u,setHidden:m,toggleHidden:h}}function gr(e){return[...e].sort((t,n)=>{const a=n.timestamp-t.timestamp;return a!==0?a:t.conversation.tabKey.localeCompare(n.conversation.tabKey)})}function K1(e,t=[]){const n=new Map(e.map(r=>[r.conversation.tabKey,r])),a=t.map(r=>n.get(r)).filter(r=>!!r);return a.length===e.length?a:gr(e)}function V1(e,t=[]){const n=e.filter(i=>i.requiresAction),a=e.filter(i=>i.unread&&!i.requiresAction),r=e.filter(i=>!i.unread&&!i.requiresAction&&i.isWorking),o=e.filter(i=>!i.unread&&!i.requiresAction&&!i.isWorking);return{attentionItems:gr(n),unreadItems:gr(a),workingItems:K1(r,t),completedItems:gr(o)}}function Y1(e){var a,r,o;const t=((a=e.p2p)==null?void 0:a.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":!(!!((r=e.p2p)!=null&&r.available)||!!((o=e.p2p)!=null&&o.state))&&e.status&&e.status!=="offline"?"Connected":"Offline"}function Q1(e,t){if(!e)return[];const n=e.recentLaunches||[];return n.length>0?n.map(a=>({id:a.id,label:a.title||a.providerName||a.providerType,kind:a.kind,providerType:a.providerType,providerSessionId:a.providerSessionId,subtitle:bn(a.summaryMetadata)||a.workspace||void 0,workspace:a.workspace,summaryMetadata:a.summaryMetadata})):t.filter(a=>a.type!=="adhdev-daemon"&&a.daemonId===e.id).map(a=>{var i;const r=Ma(a)?"cli":Rn(a)?"acp":"ide",o=bn(a.summaryMetadata);return{id:`${r}:${a.type}:${a.workspace||""}`,label:((i=a.activeChat)==null?void 0:i.title)||(Ma(a)?a.cliName||a.type:Rn(a)&&a.cliName||a.type),kind:r,providerType:a.type,providerSessionId:a.providerSessionId,subtitle:Rn(a)?o||a.workspace||void 0:a.workspace||void 0,workspace:a.workspace||void 0,timestamp:a.lastMessageAt||0}}).sort((a,r)=>r.timestamp-a.timestamp).map(({timestamp:a,...r})=>r)}function J1(e,t,n=[]){const a=new Map;for(const o of t){const i=Bs(o.conversation),c=a.get(i);c?c.push(o):a.set(i,[o])}const r=new Map;for(const o of n){const i=Bs(o),c=r.get(i);c?c.push(o):r.set(i,[o])}return e.map(o=>{const i=a.get(o.id)||[],c=r.get(o.id)||[],d=[...i].sort((f,x)=>x.timestamp-f.timestamp)[0]||null,p=(d==null?void 0:d.conversation)||null,u=Ai(o),m=i.filter(f=>f.unread||f.requiresAction).length,h=i.filter(f=>Aa(f.conversation)).length+c.filter(Aa).length,g=Y1(o),S=[o.platform||"machine",g].filter(Boolean);return{id:o.id,label:rs(o,{fallbackId:o.id}),subtitle:S.join(" · "),unread:m,total:i.length,generatingCount:h,latestConversation:p,latestTimestamp:(d==null?void 0:d.timestamp)||0,fallbackActivityAt:u,preview:p?wS(p,qp(p)):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((o,i)=>{const c=o.latestTimestamp||o.fallbackActivityAt||0,d=i.latestTimestamp||i.fallbackActivityAt||0;return d!==c?d-c:o.label.localeCompare(i.label)})}function X1(e){return e==="chat"}function tr(e,t){var n;if(!(typeof window>"u"))try{if(!(!!((n=import.meta.env)!=null&&n.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,t)}catch{}}function Z1({conversations:e,machineEntries:t,items:n,selectedConversation:a,selectedTabKey:r,screen:o,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:g,setSelectedTabKey:S,setScreen:f,setSelectedMachineId:x,setSection:w,setMachineBackTarget:b,resetMachineAction:C}){const k=l.useRef(null),y=l.useCallback(v=>{if(!(v!=null&&v.sessionId))return;const j=Js(v,i),N=Math.max(Date.now(),mn(v),j.lastUpdated||0);tr("mark_read:start",{tabKey:v.tabKey,sessionId:v.sessionId,displayPrimary:wt(v),inboxBucket:j.inboxBucket,unread:j.unread,lastSeenAt:j.lastSeenAt,lastUpdated:j.lastUpdated,activityAt:mn(v),readAt:N}),c(Bs(v)||v.routeId,"mark_session_seen",{sessionId:v.sessionId,providerSessionId:v.providerSessionId,seenAt:N,completionMarker:j.completionMarker}).then(A=>{tr("mark_read:result",{tabKey:v.tabKey,sessionId:v.sessionId,result:A})}).catch(A=>{tr("mark_read:error",{tabKey:v.tabKey,sessionId:v.sessionId,error:A instanceof Error?A.message:String(A)})})},[i,c]);return l.useEffect(()=>{var j;if(!a){X1(o)&&f("inbox"),S(((j=e[0])==null?void 0:j.tabKey)||null),k.current=null;return}if(o!=="chat"){k.current=null;return}const v=`${a.tabKey}:${a.sessionId||""}`;k.current!==v&&(k.current=v,y(a))},[e,y,o,a,f,S]),l.useEffect(()=>{if(!d)return;const v=e.find(j=>j.tabKey===d);v&&(S(v.tabKey),f("chat"),p==null||p())},[e,p,d,f,S]),l.useEffect(()=>{if(!u)return;const v=t.find(j=>j.id===u);v&&(x(v.id),C(),w("machines"),b("inbox"),f("machine"),m==null||m())},[t,m,u,C,b,f,w,x]),l.useEffect(()=>{h&&(w(h),f("inbox"),g==null||g())},[g,h,f,w]),l.useEffect(()=>{const v=n.filter(j=>j.inboxBucket==="task_complete"||j.unread);v.length!==0&&tr("inbox_state",{screen:o,selectedTabKey:r,items:v.map(j=>{const N=Js(j.conversation,i);return{liveState:N,tabKey:j.conversation.tabKey,sessionId:j.conversation.sessionId,displayPrimary:wt(j.conversation),serverBucket:N.inboxBucket,computedBucket:j.inboxBucket,serverUnread:N.unread,computedUnread:j.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:mn(j.conversation)}})})},[n,i,o,r]),{markConversationRead:y}}function eN(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function wd(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function tN(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function sN({sendDaemonCommand:e,navigate:t,ides:n,conversations:a}){const{launchCli:r}=qr(),[o,i]=l.useState("idle"),[c,d]=l.useState(""),[p,u]=l.useState(null),m=l.useCallback(()=>{i("idle"),d(""),u(null)},[]),h=l.useCallback(async(C,k,y)=>{var v;try{i("loading"),d(`Launching ${k}…`);const j={ideType:k,enableCdp:!0};(v=y==null?void 0:y.workspacePath)!=null&&v.trim()&&(j.workspace=y.workspacePath.trim()),await e(C,"launch_ide",j),i("done"),d(`${k} launch requested`)}catch(j){i("error"),d(j instanceof Error?j.message:"Launch IDE failed"),console.error("Launch IDE failed",j)}},[e]),g=l.useCallback(async(C,k,y)=>{if(k.trim())try{i("loading"),d(y!=null&&y.createIfMissing?"Creating folder…":"Saving workspace…");const v=await e(C,"workspace_add",{path:k.trim(),createIfMissing:(y==null?void 0:y.createIfMissing)===!0});if(v!=null&&v.success){i("done"),d(y!=null&&y.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),d((v==null?void 0:v.error)||"Could not save workspace")}catch(v){i("error"),d(v instanceof Error?v.message:"Could not save workspace")}},[e]),S=l.useCallback(async C=>{i("loading"),d("Starting daemon upgrade…");const k=n.find(v=>v.id===C||v.daemonId===C),y=await UC(e,C,k);i(y.state),d(y.message)},[n,e]),f=l.useCallback(async(C,k,y,v)=>{var A,T,P;const j=Date.now(),N={machineId:C,kind:k,providerType:y,workspaceId:(v==null?void 0:v.workspaceId)||null,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,startedAt:j};try{i("loading"),d(`Launching ${y}…`),u(N);const M={cliType:y};(A=v==null?void 0:v.workspacePath)!=null&&A.trim()?M.dir=v.workspacePath.trim():v!=null&&v.workspaceId?M.workspaceId=v.workspaceId:v!=null&&v.useHome&&(M.useHome=!0),v!=null&&v.resumeSessionId&&(M.resumeSessionId=v.resumeSessionId),(T=v==null?void 0:v.args)!=null&&T.trim()&&(M.cliArgs=v.args.trim().split(/\s+/).filter(Boolean)),(P=v==null?void 0:v.model)!=null&&P.trim()&&(M.initialModel=v.model.trim());const D=await r(C,M),L=(D==null?void 0:D.result)||D,O=(L==null?void 0:L.sessionId)||(L==null?void 0:L.id);if(D!=null&&D.success&&O){u(null),i("done"),d(`${y} launched`),t(Ia(O));return}if(D!=null&&D.success){i("loading"),d(`${y} launch requested — waiting for session…`);return}u(null),i("error"),d((D==null?void 0:D.error)||(L==null?void 0:L.error)||`Could not launch ${k.toUpperCase()} workspace`)}catch(M){if(tN(M)){i("loading"),d(`${y} launch requested — waiting for session…`);return}u(null),i("error"),d(M instanceof Error?M.message:`Could not launch ${k.toUpperCase()} workspace`)}},[t,e]),x=l.useCallback(async(C,k)=>{try{const y=await e(C,"list_saved_sessions",{providerType:k,kind:"cli",limit:30}),v=(y==null?void 0:y.result)??y;return Array.isArray(v==null?void 0:v.sessions)?v.sessions:[]}catch(y){return console.error("Failed to list saved sessions on mobile:",y),[]}},[e]),w=l.useCallback(async(C,k)=>Dl(e,C,k),[e]);l.useEffect(()=>{if(!p)return;const C=wd(p.workspacePath),k=n.find(v=>{var M,D,L,O;if(!v||v.type==="adhdev-daemon"||eN(v.daemonId||v.id)!==p.machineId||(v.transport==="acp"?"acp":v.transport==="pty"?"cli":null)!==p.kind||String(v.agentType||v.type||"")!==p.providerType)return!1;const T=String(v.providerSessionId||"");if(p.resumeSessionId&&T)return T===p.resumeSessionId;if(C){const E=wd(v.workspace||v.runtimeWorkspaceLabel);return E?E===C:!1}return Number(v.lastUpdated||v._lastUpdate||v.timestamp||((O=(L=(D=(M=v.activeChat)==null?void 0:M.messages)==null?void 0:D.at)==null?void 0:L.call(D,-1))==null?void 0:O.timestamp)||0)>=p.startedAt-5e3});if(!k)return;const y=Fm({entrySessionId:k.sessionId,entryInstanceId:k.instanceId,entryRouteId:k.id,conversations:a});y&&(u(null),i("done"),d(`${p.providerType} launched`),t(Ia(y)))},[a,n,t,p]),l.useEffect(()=>{if(!p)return;const C=window.setTimeout(()=>{u(k=>!k||k.startedAt!==p.startedAt?k:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(C)},[p]);const b=l.useCallback(async(C,k)=>{var y;if(k.kind==="ide"&&k.providerType){await h(C,k.providerType,{workspacePath:k.workspace||null});return}if((k.kind==="cli"||k.kind==="acp")&&k.providerType){const v=((y=k.workspace)==null?void 0:y.trim())||"";await f(C,k.kind,k.providerType,{workspacePath:v||null,useHome:!v,resumeSessionId:k.providerSessionId||null})}},[h,f]);return{machineAction:{state:o,message:c},resetMachineAction:m,handleLaunchDetectedIde:h,handleAddWorkspace:g,handleMachineUpgrade:S,handleLaunchWorkspaceProvider:f,handleListSavedSessions:x,handleBrowseDirectory:w,handleOpenRecent:b}}function nN({conversations:e,selectedConversation:t,machineBackTarget:n,markConversationRead:a,resetMachineAction:r,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:d,setMachineBackTarget:p}){const u=l.useCallback(w=>{o(w.tabKey),i("chat"),a(w)},[a,i,o]),m=l.useCallback(w=>{const b=e.find(C=>C.routeId===w.routeId&&C.streamSource==="native");b&&(o(b.tabKey),i("chat"),a(b))},[e,a,i,o]),h=l.useCallback(()=>{a(t),i("inbox")},[a,t,i]),g=l.useCallback((w,b="inbox")=>{c(w),r(),d("machines"),p(b),i("machine")},[r,p,i,d,c]),S=l.useCallback(w=>{const b=Bs(w);b&&g(b,"chat")},[g]),f=l.useCallback(()=>{r(),i(n)},[n,r,i]),x=l.useCallback(w=>{d(w),i("inbox")},[i,d]);return{openConversation:u,openNativeConversation:m,backFromConversation:h,openMachine:g,openConversationMachine:S,backFromMachine:f,changeMachineSection:x}}function Gn(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function aN(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function rN({conversations:e,hiddenConversations:t,ides:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:g,onOpenHistory:S,onOpenRemote:f,onStopCli:x,wsStatus:w,isConnected:b,initialDataLoaded:C=!0,onShowAllHiddenConversations:k,onHideConversation:y,onOpenMeshGraph:v,onOpenNewSession:j,liveSessionInboxState:N,setCliViewModeOverrides:A}){const[T,P]=l.useState(()=>{var de;return((de=e[0])==null?void 0:de.tabKey)||null}),[M,D]=l.useState(()=>e[0]?"chat":"inbox"),[L,O]=l.useState("chats"),[E,I]=l.useState(null),[_,H]=l.useState("inbox"),B=l.useRef([]),$=Ea(),F="1.0.38",W=l.useMemo(()=>e.find(de=>de.tabKey===T)||e[0]||null,[e,T]),Y=l.useMemo(()=>W?n.find(de=>de.id===W.routeId):void 0,[n,W]),V=l.useMemo(()=>!W||pt(W)||!ht(W)?null:Yn(W),[W]),ee=l.useMemo(()=>n.filter(de=>de.type==="adhdev-daemon").sort(cl),[n]),le=l.useMemo(()=>ee.find(de=>de.id===E)||null,[ee,E]),ie=eo({sendDaemonCommand:r,activeConv:W||void 0,setActionLogs:o,isStandalone:i}),Z=sN({sendDaemonCommand:r,navigate:$,ides:n,conversations:e}),U=Qk(e),J=l.useMemo(()=>e.map(de=>{const Me=M==="chat"&&(W==null?void 0:W.tabKey)===de.tabKey,He=Vr(de,N,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Me}),je=mn(de),be=qp(de),et=Jp(de,be);return{conversation:de,timestamp:je,preview:et,unread:He.unread,requiresAction:He.requiresAction,isWorking:He.isWorking,inboxBucket:He.inboxBucket}}),[e,N,M,W,U]),{markConversationRead:R}=Z1({conversations:e,machineEntries:ee,items:J,selectedConversation:W,selectedTabKey:T,screen:M,liveSessionInboxState:N,sendDaemonCommand:r,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:g,setSelectedTabKey:P,setScreen:D,setSelectedMachineId:I,setSection:O,setMachineBackTarget:H,resetMachineAction:Z.resetMachineAction}),z=nN({conversations:e,selectedConversation:W,machineBackTarget:_,markConversationRead:R,resetMachineAction:Z.resetMachineAction,setSelectedTabKey:P,setScreen:D,setSelectedMachineId:I,setSection:O,setMachineBackTarget:H}),{isMuted:ve,toggleMute:he}=zm(N,r),{attentionItems:ge,unreadItems:me,workingItems:K,completedItems:G}=l.useMemo(()=>V1(J,B.current),[J]);l.useEffect(()=>{B.current=K.map(de=>de.conversation.tabKey)},[K]);const X=l.useMemo(()=>le?J.filter(de=>Bs(de.conversation)===le.id):[],[J,le]),ce=l.useMemo(()=>Q1(le,n),[n,le]),se=!!le&&no(le,qs(le,F)),Ae=l.useMemo(()=>(le==null?void 0:le.availableProviders)||[],[le]),pe=l.useMemo(()=>Ae.filter(de=>Gn(de,"cli")).map(de=>({type:de.type,displayName:de.displayName||de.type,icon:de.icon})),[Ae]),fe=l.useMemo(()=>Ae.filter(de=>Gn(de,"acp")).map(de=>({type:de.type,displayName:de.displayName||de.type,icon:de.icon})),[Ae]),q=l.useMemo(()=>J1(ee,J,t),[J,ee,t]),ye=l.useCallback(async de=>{le&&await Z.handleOpenRecent(le.id,de)},[Z,le]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:M==="chat"&&W?s.jsx(_1,{selectedConversation:W,isAcp:pt(W),isStandalone:i,selectedIdeEntry:Y,actionLogs:a,userName:c,isSendingChat:ie.isSendingChat,sendFeedbackMessage:ie.sendFeedbackMessage,isFocusingAgent:ie.isFocusingAgent,handleModalButton:ie.handleModalButton,handleRelaunch:ie.handleRelaunch,onBack:z.backFromConversation,onOpenNativeConversation:z.openNativeConversation,onOpenMachine:z.openConversationMachine,onOpenHistory:S,onOpenRemote:f,onOpenMeshGraph:v,onStopCli:x,cliViewMode:V,onSetCliViewMode:async de=>{await Mm({conversation:W,mode:de,ides:n,sendDaemonCommand:r,setCliViewModeOverrides:A})},handleSendChat:ie.handleSendChat,handleForceSendChat:ie.handleForceSendChat,handleFocusAgent:ie.handleFocusAgent}):M==="machine"&&le?s.jsx(G1,{selectedMachineEntry:le,selectedMachineConversations:X,selectedMachineRecentLaunches:ce,cliProviders:pe,acpProviders:fe,selectedMachineNeedsUpgrade:se,appVersion:F,machineAction:Z.machineAction,isStandalone:i,section:L,showBottomNav:_==="inbox",onBack:z.backFromMachine,onSectionChange:z.changeMachineSection,onOpenConversation:z.openConversation,onOpenRecent:ye,onOpenMachineDetails:()=>$(`/machines/${le.id}`),onMachineUpgrade:()=>Z.handleMachineUpgrade(le.id),onLaunchDetectedIde:(de,Me)=>Z.handleLaunchDetectedIde(le.id,de,Me),onAddWorkspace:(de,Me)=>Z.handleAddWorkspace(le.id,de,Me),onBrowseDirectory:de=>Z.handleBrowseDirectory(le.id,de),onLaunchWorkspaceProvider:(de,Me,He)=>Z.handleLaunchWorkspaceProvider(le.id,de,Me,He),onListSavedSessions:de=>Z.handleListSavedSessions(le.id,de)}):s.jsx(F1,{section:L,attentionItems:ge,unreadItems:me,workingItems:K,completedItems:G,hiddenConversations:t,machineCards:q,getAvatarText:aN,actionLogs:a,sendDaemonCommand:r,onOpenConversation:z.openConversation,onShowAllHidden:k,onHideConversation:y,onOpenMeshGraph:v,onStopCli:x,onOpenNewSession:j,onOpenMachine:z.openMachine,onOpenSettings:()=>$("/settings"),onSectionChange:O,wsStatus:w,isConnected:b,initialDataLoaded:C,isStandalone:i,isConversationMuted:ve,onToggleMuteConversation:he})})}function Oo(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function oN({conversations:e,numGroups:t,onMoveTab:n,onReceiveTab:a,onOwnTabDrop:r,onClearPreviewOrder:o}){const i=l.useRef(0),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useCallback(()=>{i.current=0,d(!1),u(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",m),window.addEventListener("drop",m),()=>{window.removeEventListener("dragend",m),window.removeEventListener("drop",m)}),[m]);const h=l.useCallback(x=>{x.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,d(!0))},[]),g=l.useCallback(x=>{if(!x.dataTransfer.types.includes("text/tab-key"))return;if(x.preventDefault(),!Oo(t,n)){u("merge");return}const w=x.currentTarget.getBoundingClientRect(),b=x.clientX-w.left,C=w.width/3;b<C?u("split-left"):b>C*2?u("split-right"):u("merge")},[t,n]),S=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,d(!1),u(null))},[]),f=l.useCallback(x=>{i.current=0,d(!1);const w=x.dataTransfer.getData("text/tab-key"),b=w?e.some(k=>k.tabKey===w):!1,C=p;if(u(null),o(),!!w){if(x.preventDefault(),C==="split-left"&&Oo(t,n)){n==null||n(w,"split-left");return}if(C==="split-right"&&Oo(t,n)){n==null||n(w,"split-right");return}if(b){r(w);return}a==null||a(w)}},[e,p,t,n,a,r,o]);return{dragOver:c,dropAction:p,resetDragState:m,handleDragEnter:h,handleDragOver:g,handleDragLeave:S,handleDrop:f}}function iN(e,t){const n=new Set(t.map(o=>o.tabKey)),a=e.filter(o=>n.has(o)),r=t.filter(o=>!e.includes(o.tabKey)).map(o=>o.tabKey);return[...a,...r]}function lN({conversations:e,initialActiveTabId:t,initialTabOrder:n,onActiveTabChange:a,onTabOrderChange:r}){const[o,i]=l.useState(t??null),[c,d]=l.useState(n??[]),[p,u]=l.useState(null),m=l.useRef(null),h=l.useRef(null),g=l.useRef(a),S=l.useRef(r);l.useEffect(()=>{g.current=a},[a]),l.useEffect(()=>{S.current=r},[r]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{d(j=>{const N=iN(j,e);return N.length===j.length&&N.every((A,T)=>A===j[T])?j:N})},[e]);const f=l.useMemo(()=>{const j=p??c;if(j.length===0)return e;const N=new Map(j.map((A,T)=>[A,T]));return[...e].sort((A,T)=>{const P=N.get(A.tabKey)??999,M=N.get(T.tabKey)??999;return P-M})},[e,p,c]);l.useEffect(()=>{var N,A;if(f.length===0){o!==null&&(i(null),(N=g.current)==null||N.call(g,null));return}if(o&&f.some(T=>T.tabKey===o))return;const j=f[0].tabKey;j!==o&&(i(j),(A=g.current)==null||A.call(g,j))},[f,o]);const x=l.useMemo(()=>f.find(j=>j.tabKey===o),[f,o]),w=l.useCallback(j=>{var N;i(j),(N=g.current)==null||N.call(g,j)},[]),b=l.useCallback((j,N,A)=>{d(T=>{var L;const P=T.filter(O=>O!==j),M=P.indexOf(N);if(M<0)return T;const D=A==="left"?M:M+1;return P.splice(D,0,j),(L=S.current)==null||L.call(S,P),P}),u(null)},[]),C=l.useCallback((j,N,A)=>{const P=(c.length>0?c:e.map(L=>L.tabKey)).filter(L=>L!==j),M=P.indexOf(N);if(M<0)return;const D=A==="left"?M:M+1;P.splice(D,0,j),m.current=P,u(P)},[c,e]),k=l.useCallback(()=>{var N;const j=m.current;j&&(d(j),(N=S.current)==null||N.call(S,j))},[]),y=l.useCallback(()=>{m.current=null,u(null)},[]),v=l.useCallback(j=>{d(N=>{var T;const A=N.filter(P=>P!==j);return A.push(j),(T=S.current)==null||T.call(S,A),A})},[]);return{activeTabId:o,activeConv:x,sortedConversations:f,previewOrderRef:m,draggingTabRef:h,selectTab:w,handleTabReorder:b,updatePreviewOrder:C,commitPreviewOrder:k,clearPreviewOrder:y,moveTabToEnd:v,setDraggingTabKey:j=>{h.current=j}}}function cN({dropAction:e,canSplit:t}){return s.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-left"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Left"})}),s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Move Here"})}),s.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-right"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Right"})})]})}function Ll({conversationsCount:e,isSplitMode:t,isStandalone:n,hasRegisteredMachines:a=!1,suppressGuide:r=!1,onOpenNewSession:o,isLoading:i=!1}){const{t:c}=Ce("common");if(r)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});if(i)return s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center gap-3 -mt-8 text-text-muted",children:[s.jsx("div",{className:"w-7 h-7 rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light","aria-hidden":"true"}),s.jsx("p",{className:"text-sm",children:c("paneGroup.loadingSessions")})]});const d=!n&&!a,p=a&&!!o,u=c(a?"paneGroup.noConversations":n?"paneGroup.waitingForDaemon":"paneGroup.connectYourMachines"),m=c(a?"paneGroup.newSessionDescription":n?"paneGroup.daemonDescription":"paneGroup.installDescription");return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:u}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),p&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:o,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:c("paneGroup.newSession"),"aria-label":c("paneGroup.newSession"),children:[s.jsx(al,{size:14}),s.jsx("span",{children:c("paneGroup.newSession")})]})}),d&&s.jsx(Wm,{}),d&&s.jsx("div",{className:"mt-8",children:s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"📚 Read the documentation →"})})]})]}):s.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const Km="adhdev-tab-shortcuts";function Vm(){try{return JSON.parse(localStorage.getItem(Km)||"{}")}catch{return{}}}function Ym({enabled:e=!0,sortedTabKeys:t,onFocus:n,onSelectTab:a}){const r=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>Vm()),[c,d]=l.useState(null),p=l.useCallback(m=>{const h=[];return m.metaKey&&h.push(r?"⌘":"Meta"),m.ctrlKey&&h.push("Ctrl"),m.altKey&&h.push(r?"⌥":"Alt"),m.shiftKey&&h.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(h.push(m.key.length===1?m.key.toUpperCase():m.key),h.join("+"))},[r]),u=l.useCallback(m=>{i(m);try{localStorage.setItem(Km,JSON.stringify(m))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const m=h=>{if(h.preventDefault(),h.stopPropagation(),h.key==="Escape"){d(null);return}const g=p(h);if(!g)return;const S={...o};for(const[f,x]of Object.entries(S))x===g&&delete S[f];S[c]=g,u(S),d(null)};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[e,c,o,u,p]),l.useEffect(()=>{if(!e)return;const m=h=>{if(!(!h.ctrlKey&&!h.metaKey&&!h.altKey)){for(const[g,S]of Object.entries(o))if(t.includes(g)&&p(h)===S){h.preventDefault(),n(),a(g);return}}};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e,o,t,n,a,p]),{isMac:r,tabShortcuts:o,shortcutListening:c,setShortcutListening:d,saveShortcuts:u}}const Uo=e=>{e.preventDefault()},dN=l.memo(function({conv:t,isActive:n,isDraggedTab:a,isTaskCompleteUnread:r,shortcut:o,conversationKeys:i,draggingTabRef:c,onFocus:d,onSelectTab:p,onConversationActivated:u,onPreviewReorder:m,onReorderTab:h,onCommitPreviewOrder:g,onClearPreviewOrder:S,onDragStateReset:f,onDragTabKeyChange:x,onReceiveTab:w,onOpenContextMenu:b,longPressTimer:C,isGroupActive:k}){const y=wn(t),v=y.isGenerating?"agent-tab-generating":y.isWaiting?"agent-tab-waiting":"",j=y.isReconnecting,N=xS(t),A=vS(t),T=Qp(t),P=l.useCallback(B=>{c.current=t.tabKey,x(t.tabKey),B.dataTransfer.setData("text/tab-key",t.tabKey),B.dataTransfer.effectAllowed="move"},[t.tabKey,c,x]),M=l.useCallback(()=>{c.current=null,x(null),g(),S(),f()},[c,x,g,S,f]),D=l.useCallback(B=>{const $=c.current;if(!(!$||$===t.tabKey)&&B.dataTransfer.types.includes("text/tab-key")){B.preventDefault(),B.stopPropagation();const F=B.currentTarget.getBoundingClientRect(),W=B.clientX<F.left+F.width/2?"left":"right";m($,t.tabKey,W)}},[t.tabKey,c,m]),L=l.useCallback(B=>{B.preventDefault(),B.stopPropagation();const $=B.dataTransfer.getData("text/tab-key");if($&&$!==t.tabKey){const F=B.currentTarget.getBoundingClientRect(),W=B.clientX<F.left+F.width/2?"left":"right";i.includes($)?h($,t.tabKey,W):w&&w($)}S()},[t.tabKey,i,h,w,S]),O=l.useCallback(B=>{B.stopPropagation(),d(),p(t.tabKey),u(t)},[t,u,d,p]),E=l.useCallback(B=>{B.preventDefault(),b(B.clientX,B.clientY,t.tabKey)},[t.tabKey,b]),I=l.useCallback(B=>{const $=B.touches[0];C.current=setTimeout(()=>{b($.clientX,$.clientY,t.tabKey)},600)},[t.tabKey,C,b]),_=l.useCallback(()=>{C.current&&clearTimeout(C.current)},[C]),H=["adhdev-dockview-tab",v,n&&"is-active",k&&"is-group-active",j&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:H,draggable:!0,onDragStart:P,onDragEnd:M,onDragOver:D,onDrop:L,onClick:O,onContextMenu:E,onTouchStart:I,onTouchEnd:_,onTouchMove:_,style:{position:"relative",cursor:"pointer",opacity:a?.4:void 0},children:[T&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-badge pointer-events-none absolute top-0.5 right-0.5 text-text-muted",title:"Mesh chat","aria-label":"Mesh chat",children:s.jsx(as,{size:11})}),r&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:y.isGenerating?s.jsx("div",{className:"tab-spinner"}):y.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):j?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):y.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),N.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:A,"aria-label":A||N.join(" · "),children:N.join(" · ")}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:wt(t),children:wt(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[j?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:dn(t)}):y.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[dn(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:dn(t)}),s.jsx(Pr,{git:t.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),o&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${o}`,children:o})]})},(e,t)=>e.conv===t.conv&&e.isActive===t.isActive&&e.isDraggedTab===t.isDraggedTab&&e.isTaskCompleteUnread===t.isTaskCompleteUnread&&e.shortcut===t.shortcut&&e.conversationKeys===t.conversationKeys&&e.isGroupActive===t.isGroupActive);function uN({conversations:e,activeTabId:t,groupIndex:n,unreadTabKeys:a,draggingTabRef:r,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:h,onDragTabKeyChange:g,onReceiveTab:S,onHideTab:f,isGroupActive:x,allowTabShortcuts:w=!0}){const{t:b}=Ce("common"),[C,k]=l.useState(null),y=l.useRef(null),v=l.useRef(null),j=l.useMemo(()=>e.map(L=>L.tabKey),[e]);_a("PaneGroupTabBar",{groupIndex:n,activeTabId:t,tabCount:e.length,ctxMenuTab:(C==null?void 0:C.tabKey)||null});const{isMac:N,tabShortcuts:A,shortcutListening:T,setShortcutListening:P,saveShortcuts:M}=Ym({enabled:w,sortedTabKeys:e.map(L=>L.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!C)return;const L=O=>{const E=document.querySelector("[data-pane-context-menu]");E&&E.contains(O.target)||k(null)};return window.addEventListener("mousedown",L,!0),()=>window.removeEventListener("mousedown",L,!0)},[C]),l.useEffect(()=>{const L=v.current;if(!L)return;const O=E=>{Math.abs(E.deltaY)<=Math.abs(E.deltaX)||(E.preventDefault(),L.scrollLeft+=E.deltaY)};return L.addEventListener("wheel",O,{passive:!1}),()=>L.removeEventListener("wheel",O)},[]);const D=l.useCallback((L,O,E)=>{k({x:L,y:O,tabKey:E})},[]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:s.jsxs("div",{ref:v,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(L=>s.jsx(dN,{conv:L,isActive:t===L.tabKey,isDraggedTab:r.current===L.tabKey,isTaskCompleteUnread:a.has(L.tabKey),shortcut:w?A[L.tabKey]:void 0,conversationKeys:j,draggingTabRef:r,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:h,onDragTabKeyChange:g,onReceiveTab:S,onOpenContextMenu:D,longPressTimer:y,isGroupActive:x},L.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:b("paneGroup.noTabsInGroup")})]})}),C&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:C.x,top:C.y},children:[w&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:Uo,onClick:L=>{L.stopPropagation(),P(C.tabKey),k(null)},children:["⌨ ",A[C.tabKey]?`Change shortcut (${A[C.tabKey]})`:"Set shortcut"]}),A[C.tabKey]&&s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:Uo,onClick:()=>{const L={...A};delete L[C.tabKey],M(L),k(null)},children:"✕ Remove shortcut"})]}),f&&s.jsxs(s.Fragment,{children:[w&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:Uo,onClick:()=>{f(C.tabKey),k(null)},children:"🚫 Hide from Dashboard"})]})]}),w&&T&&s.jsx(Yt,{children:s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>P(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:L=>L.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",N?"⌘+1":"Ctrl+1",", ",N?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:b("paneGroup.pressEscToCancel")})]})})})]})}function pN({conversations:e,ides:t,clearedTabs:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d=!0,userName:p,groupIndex:u,onFocus:m,isSplitMode:h,numGroups:g,onMoveTab:S,onReceiveTab:f,style:x,onActiveTabChange:w,initialActiveTabId:b,initialTabOrder:C,onTabOrderChange:k,onHideTab:y,isFocused:v,allowTabShortcuts:j=!0,onOpenNewSession:N,liveSessionInboxState:A}){const{sendCommand:T}=kt(),P=l.useRef(null),{activeTabId:M,activeConv:D,sortedConversations:L,draggingTabRef:O,selectTab:E,handleTabReorder:I,updatePreviewOrder:_,commitPreviewOrder:H,clearPreviewOrder:B,moveTabToEnd:$,setDraggingTabKey:F}=lN({conversations:e,initialActiveTabId:b,initialTabOrder:C,onActiveTabChange:w,onTabOrderChange:k}),W=eo({sendDaemonCommand:r,activeConv:D,setActionLogs:o,isStandalone:i}),{dragOver:Y,dropAction:V,resetDragState:ee,handleDragEnter:le,handleDragOver:ie,handleDragLeave:Z,handleDrop:U}=oN({conversations:e,numGroups:g,onMoveTab:S,onReceiveTab:f,onOwnTabDrop:$,onClearPreviewOrder:B}),J=D&&!pt(D)&&Yn(D)==="terminal",R=l.useMemo(()=>D?t.find(ge=>ge.id===D.routeId):void 0,[t,D]),z=l.useMemo(()=>D?a.filter(ge=>ge.routeId===D.tabKey):[],[a,D]),ve=l.useMemo(()=>new Set(L.filter(ge=>vg(ge,A,{isOpenConversation:ge.tabKey===M})).map(ge=>ge.tabKey)),[M,A,L]);_a("PaneGroup",{groupIndex:u,conversationCount:e.length,activeTabId:M,dragOver:Y});const he=l.useCallback(ge=>{ge.streamSource==="agent-stream"&&ge.agentType&&T(ge.routeId,Pp(),{agentType:ge.agentType,...ge.sessionId&&{targetSessionId:ge.sessionId}}).catch(()=>{})},[T]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:m,style:{...x,outline:Y?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(uN,{conversations:L,activeTabId:M,groupIndex:u,numGroups:g,unreadTabKeys:ve,draggingTabRef:O,onFocus:m,onSelectTab:E,onConversationActivated:he,onPreviewReorder:_,onReorderTab:I,onCommitPreviewOrder:H,onClearPreviewOrder:B,onDragStateReset:ee,onDragTabKeyChange:F,onMoveTab:S,onReceiveTab:f,onHideTab:y,isGroupActive:v??!1,allowTabShortcuts:j}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:le,onDragOver:ie,onDragLeave:Z,onDrop:U,children:[Y&&s.jsx(cN,{dropAction:V,canSplit:!!(g<4&&S)}),D?s.jsx(Pl,{activeConv:D,clearToken:n[D.tabKey]||0,isCliTerminal:!!J,ideEntry:R,terminalRef:P,handleModalButton:W.handleModalButton,handleRelaunch:W.handleRelaunch,handleSendChat:W.handleSendChat,handleForceSendChat:W.handleForceSendChat,isSendingChat:W.isSendingChat,sendFeedbackMessage:W.sendFeedbackMessage,handleFocusAgent:W.handleFocusAgent,isFocusingAgent:W.isFocusingAgent,actionLogs:z,userName:p,isInputActive:!h||!!v}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(Ll,{conversationsCount:e.length,isSplitMode:h,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:N,isLoading:!d})})]})]})}function mN({containerRef:e,isSplitMode:t,numGroups:n,groupSizes:a,groupedConvs:r,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,initialDataLoaded:h,userName:g,focusedGroup:S,focusGroup:f,moveTabToGroup:x,splitTabRelative:w,closeGroup:b,handleResizeStart:C,groupActiveTabIds:k,setGroupActiveTab:y,groupTabOrders:v,setGroupTabOrder:j,toggleHiddenTab:N,onOpenNewSession:A,allowTabShortcuts:T=!0,liveSessionInboxState:P}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:r.map((M,D)=>{const L=t&&a.length===n?`${a[D]}%`:void 0;return s.jsxs(Lt.Fragment,{children:[t&&D>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:O=>C(D-1,O),onDoubleClick:()=>b(D),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(pN,{style:t?{flexBasis:L??`${100/n}%`,flexGrow:L?0:1,flexShrink:L?0:1}:void 0,conversations:M,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,initialDataLoaded:h,userName:g,groupIndex:D,isFocused:t&&S===D,onFocus:()=>f(D),isSplitMode:t,numGroups:n,onMoveTab:(O,E)=>{E==="left"&&D>0?x(O,D-1):E==="right"&&D<n-1?x(O,D+1):E==="split-left"&&n<4?w(O,D,"left"):E==="split-right"&&n<4&&w(O,D,"right")},onReceiveTab:O=>x(O,D),onActiveTabChange:O=>y(D,O),initialActiveTabId:k[D],initialTabOrder:v[D],onTabOrderChange:O=>j(D,O),onHideTab:N,onOpenNewSession:A,allowTabShortcuts:T,liveSessionInboxState:P})]},D)})})}const Qm="adhdev-dashboard-action-shortcuts",hN=1200,fN=[["toggleHiddenTabs","G H"],["openNewSession","N"],["setActiveTabShortcut","G S"],["selectPreviousGroupTab","G K"],["selectPreviousGroupTab","T ←"],["selectPreviousGroupTab","⌥+["],["selectPreviousGroupTab","Ctrl+Alt+["],["selectNextGroupTab","G J"],["selectNextGroupTab","T →"],["selectNextGroupTab","⌥+]"],["selectNextGroupTab","Ctrl+Alt+]"],["splitActiveTabDown","S ↓"],["splitActiveTabDown","⌘+⌥+-"],["splitActiveTabDown","Ctrl+Alt+-"],["splitActiveTabRight","S →"],["splitActiveTabRight","⌘+⌥+\\"],["splitActiveTabRight","⌘+⌥+="],["splitActiveTabRight","Ctrl+Alt+\\"],["focusLeftPane","F ←"],["focusLeftPane","⌘+⌥+←"],["focusLeftPane","⌘+⌥+["],["focusLeftPane","Ctrl+Alt+←"],["focusRightPane","F →"],["focusRightPane","⌘+⌥+→"],["focusRightPane","⌘+⌥+]"],["focusRightPane","Ctrl+Alt+→"],["focusUpPane","F ↑"],["focusUpPane","⌘+⌥+U"],["focusUpPane","Ctrl+Alt+↑"],["focusDownPane","F ↓"],["focusDownPane","⌘+⌥+J"],["focusDownPane","Ctrl+Alt+↓"],["moveActiveTabToLeftPane","M ←"],["moveActiveTabToLeftPane","⌘+⌥+⇧+←"],["moveActiveTabToLeftPane","⌘+⌥+,"],["moveActiveTabToLeftPane","Ctrl+Alt+Shift+←"],["moveActiveTabToRightPane","M →"],["moveActiveTabToRightPane","⌘+⌥+⇧+→"],["moveActiveTabToRightPane","⌘+⌥+."],["moveActiveTabToRightPane","Ctrl+Alt+Shift+→"],["moveActiveTabToUpPane","M ↑"],["moveActiveTabToUpPane","⌘+⌥+I"],["moveActiveTabToUpPane","Ctrl+Alt+Shift+↑"],["moveActiveTabToDownPane","M ↓"],["moveActiveTabToDownPane","⌘+⌥+K"],["moveActiveTabToDownPane","Ctrl+Alt+Shift+↓"],["triggerPrimaryApprovalAction","⌥+A"],["triggerSecondaryApprovalAction","⌥+D"],["toggleCliView","T"]];function bN(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function mt(e,t){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return t?"⌘+⇧+Enter":"Ctrl+Shift+Enter";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+Ctrl+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return t?"⌘+Ctrl+⇧+↓":"Ctrl+Alt+Shift+↓";case"focusLeftPane":return"";case"focusRightPane":return"";case"focusUpPane":return"";case"focusDownPane":return"";case"moveActiveTabToLeftPane":return"";case"moveActiveTabToRightPane":return"";case"moveActiveTabToUpPane":return"";case"moveActiveTabToDownPane":return"";case"triggerPrimaryApprovalAction":return t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌘+⇧+←":"Ctrl+Shift+←";case"selectNextGroupTab":return t?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function Jm(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:mt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:mt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:mt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:mt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:mt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:mt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:mt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:mt("popoutActiveTab",e)},{id:"dockActiveTab",label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window.",defaultShortcut:mt("dockActiveTab",e)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:mt("splitActiveTabRight",e)},{id:"splitActiveTabDown",label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it.",defaultShortcut:mt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:mt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:mt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:mt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:mt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:mt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:mt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:mt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:mt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:mt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:mt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:mt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:mt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:mt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:mt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:mt("toggleCliView",e)}]}function Oi(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Br(e){const t=Object.fromEntries(Jm(e).map(n=>[n.id,n.defaultShortcut]));try{const n=JSON.parse(localStorage.getItem(Qm)||"{}"),a={...t,...n};for(const[r,o]of fN)a[r]===o&&(a[r]=t[r]);return a}catch{return t}}function Xm(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function gN({enabled:e=!0,onTrigger:t}){const n=bN(),[a,r]=l.useState(()=>Br(n)),[o,i]=l.useState(null),[c,d]=l.useState([]),p=l.useRef({parts:[],timer:null}),u=l.useCallback(f=>{const x=[];return f.metaKey&&x.push(n?"⌘":"Meta"),f.ctrlKey&&x.push("Ctrl"),f.altKey&&x.push(n?"⌥":"Alt"),f.shiftKey&&f.key.length!==1&&x.push(n?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(x.push(Xm(f.key)),x.join("+"))},[n]),m=l.useCallback(f=>{r(f);try{localStorage.setItem(Qm,JSON.stringify(f))}catch{}},[]);l.useEffect(()=>{const f=Br(n),x=Object.entries(a),w=Object.entries(f);x.length===w.length&&x.every(([b,C])=>f[b]===C)||m(f)},[a,n,m]);const h=l.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),g=l.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},hN))},[]);l.useEffect(()=>{if(!o)return;const f=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){i(null),d([]);return}const w=u(x);if(!w)return;const C=!(x.metaKey||x.ctrlKey||x.altKey)&&/^[A-Z0-9]$/.test(w);if(c.length===0&&C){d([w]);return}const y=[...c,w].slice(0,2).join(" "),v={...a};for(const[j,N]of Object.entries(v))N===y&&delete v[j];v[o]=y,m(v),i(null),d([])};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[a,u,m,o,c]),l.useEffect(()=>{if(!e||o)return;const f=x=>{if(x.defaultPrevented)return;const w=u(x);if(!w)return;const b=x.metaKey||x.ctrlKey||x.altKey;if(Oi(x.target))return;const C=p.current.parts,k=b?[w]:[...C.slice(-1),w].slice(-2),y=k.join(" "),v=k[k.length-1],j=Object.entries(a).filter(([,M])=>!!M),N=j.find(([,M])=>M===y);if(N){x.preventDefault(),h(),t(N[0]);return}if(j.some(([,M])=>M.startsWith(`${y} `))){x.preventDefault(),p.current.parts=k,g();return}const T=j.find(([,M])=>M===v);if(T){x.preventDefault(),h(),t(T[0]);return}if(j.some(([,M])=>M.startsWith(`${v} `))){x.preventDefault(),p.current.parts=[v],g();return}h()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[a,g,e,u,t,h,o]),l.useEffect(()=>()=>h(),[h]);const S=l.useMemo(()=>Jm(n),[n]);return{isMac:n,actionDefinitions:S,actionShortcuts:a,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:m}}function xN({isTabInPopout:e,isTabFloating:t,tabShortcut:n,actionShortcuts:a}){const r=[];return e?(t&&r.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:a.dockActiveTab}),r.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:a.dockActiveTab})):t?r.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:a.dockActiveTab}):r.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:a.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:a.popoutActiveTab}),r.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:n?`Change shortcut (${n})`:"Set shortcut",shortcut:a.setActiveTabShortcut}),n&&r.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),r.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:a.hideCurrentTab,tone:"muted"}),r}function Zm(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function kd({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:n,ides:a}){return!e||n>0?!1:t?!Zm(a):!0}function vN({previousVisibleConversationCount:e,visibleConversationCount:t,ides:n}){return t>0||e<=0?!1:Zm(n)}const eh=1e3,yN=4;function Sd(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function Cd(e,t,n){return Math.abs(t.clientX-e.clientX)>n||Math.abs(t.clientY-e.clientY)>n}function wN({detachDelayMs:e=eh,stillnessThresholdPx:t=yN,onDetach:n,setTimeoutFn:a=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:r=globalThis.clearTimeout.bind(globalThis)}){let o=null,i=null,c=null,d=null,p=null,u=!1;const m=()=>{p!=null&&(r(p),p=null)},h=()=>{m(),c=null},g=()=>{m(),o=null,i=null,c=null,d=null,u=!1},S=()=>{!o||!c||!d||u||p!=null||(p=a(()=>{p=null,!(!o||!c||!d||u)&&Sd(d,i)&&(Cd(c,d,t)||(u=!0,n({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},f=w=>{if(!(!o||u)){if(!Sd(w,i)){d={clientX:w.clientX,clientY:w.clientY},h();return}(!c||Cd(c,w,t))&&(m(),c={clientX:w.clientX,clientY:w.clientY}),d={clientX:w.clientX,clientY:w.clientY},S()}},x=w=>{!o||u||(w&&(d={clientX:w.clientX,clientY:w.clientY}),h())};return{startDrag:w=>{m(),o=w.panelId,i=w.selfPanelBounds??null,c=null,d={clientX:w.clientX,clientY:w.clientY},u=!1},markSelfPanel:f,markNonSelfPanel:x,markNoDropTarget:x,markDockTarget:x,endDrag:g,isDragging:()=>o!=null,hasDetached:()=>u,dispose:g}}function kN(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function xr(e){return wt(e)||e.tabKey}function SN(e){return`remote:${e}`}function ls(e){return e.startsWith("remote:")}function jd(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function qo(e){var a;const t=e==null?void 0:e.defaultView;if(!t)return;const n=r=>{if(r)try{r.focus({preventScroll:!0})}catch{try{r.focus()}catch{}}};try{t.focus(),n(e==null?void 0:e.body),n(e==null?void 0:e.documentElement),(a=t.requestAnimationFrame)==null||a.call(t,()=>{try{t.focus(),n(e==null?void 0:e.body)}catch{}})}catch{}}function Go(e,t){e.classList.remove(mi.className,hi.className),e.classList.add(t==="light"?mi.className:hi.className)}function Nd(e){return e?Array.from(new Set(e.groups.map(t=>{var n,a;return(a=(n=t.element)==null?void 0:n.ownerDocument)==null?void 0:a.defaultView}).filter(t=>!!t&&t!==window))):[]}function CN(e,t,n){var i;const a=[t];let r;for(const c of a){let d;for(const p of c){const u=e.addPanel({id:p.tabKey,component:"conversation",title:xr(p),params:{kind:"conversation",tabKey:p.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:r?{position:{referencePanel:r,direction:"right"},inactive:!0}:{}});d||(d=u.id)}r=d??r}return n??((i=t[0])==null?void 0:i.tabKey)??null}function Ad(e,t){const n=new Set(t.map(r=>r.tabKey)),a=new Map;for(const r of t)a.set(r.tabKey,(a.get(r.tabKey)||0)+1);for(const r of[...e.panels])ls(r.id)||n.has(r.id)||e.removePanel(r);for(const r of t){const o=e.getPanel(r.tabKey);if(o){(a.get(r.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:r.tabKey,daemonId:r.daemonId,sessionId:r.sessionId,providerSessionId:r.providerSessionId,panelId:o.id}),o.update({params:{tabKey:r.tabKey}}),o.title!==xr(r)&&o.api.setTitle(xr(r));continue}e.addPanel({id:r.tabKey,component:"conversation",title:xr(r),params:{kind:"conversation",tabKey:r.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function Td(e,t,n){var d,p;const a=n?SN(n):null;for(const u of[...e.panels])ls(u.id)&&(!a||u.id!==a)&&e.removePanel(u);if(!n||!a)return;const r=hs(t,n);if(!r&&e.totalPanels===0)return;const o=e.getPanel(a),i=em(r);if(o){o.title!==i&&o.api.setTitle(i);return}const c=(r==null?void 0:r.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((p=e.panels.find(u=>!ls(u.id)))==null?void 0:p.id);e.addPanel({id:a,component:"remote",title:i,params:{kind:"remote",routeId:n},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function th({doId:e,targetSessionId:t,connState:n,viewMode:a}){const[r,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?Ct.onScreenshot("ide-page",(u,m)=>{if(u!==e)return;const h=new FileReader;h.onload=()=>o(h.result),h.readAsDataURL(m)}):void 0,[e]),l.useEffect(()=>{n!=="connected"&&o(null)},[n]),l.useEffect(()=>{var u;return e?((u=Ct.onStatus)==null?void 0:u.call(Ct,(m,h)=>{m===e&&h!=null&&h.screenshotUsage&&c(h.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const p=e?Ct.get(e):null;if(!(!p||n!=="connected"))return a!=="chat"&&t?p.startScreenshots(t):p.stopScreenshots(t),()=>{p.stopScreenshots(t)}},[a,n,t,e]);const d=l.useCallback(async(p,u)=>{const m=e?Ct.get(e):null;return!m||n!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):m.sendInput(p,u,t)},[e,n,t]);return{connScreenshot:r,screenshotUsage:i,handleRemoteAction:d}}const sh=l.createContext(null);function oo(){const e=l.useContext(sh);if(!e)throw new Error("DashboardDockviewContext missing");return e}function jN(e){const[,t]=l.useState(0);l.useEffect(()=>{const n=()=>t(r=>r+1),a=[e.api.onDidActiveGroupChange(n),e.api.onDidTitleChange(n),e.api.onDidGroupChange(n),e.containerApi.onDidActivePanelChange(n)];return()=>{for(const r of a)r.dispose()}},[e.api,e.containerApi])}function NN({params:e}){var d;const t=oo(),n=l.useMemo(()=>hs([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),a=l.useMemo(()=>t.ides.find(p=>p.id===e.routeId),[t.ides,e.routeId]),r=(n==null?void 0:n.daemonId)||((d=n==null?void 0:n.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:i,handleRemoteAction:c}=th({doId:r,targetSessionId:n?Mp(n):(a==null?void 0:a.sessionId)||(a==null?void 0:a.instanceId),connState:(n==null?void 0:n.connectionState)||"new",viewMode:"remote"});return n?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(Yu,{addLog:()=>{},connState:n.connectionState||"new",connScreenshot:o,screenshotUsage:i,transportType:n.transport,onAction:c})}):s.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:"Remote view unavailable"})}function AN(){const e=oo();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(Ll,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels,isLoading:!e.initialDataLoaded})})}function TN(e){var b,C;jN(e);const t=oo(),n=l.useCallback(k=>{"button"in k&&k.button!==0||e.api.setActive()},[e.api]),a=e.params.kind==="remote"?void 0:t.conversationsByTabKey.get(e.params.tabKey),r=a==null?void 0:a.sessionId,o=l.useCallback(k=>eS(k),[]),i=l.useCallback(()=>Zk(r),[r]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const k=hs([...t.conversationsByTabKey.values()],e.params.routeId),y=((b=e.api.group.activePanel)==null?void 0:b.id)===e.api.id,v=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${y?" is-active":""}${v?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(k==null?void 0:k.tabKey)||"",onMouseDown:n,onTouchStart:n,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:k!=null&&k.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:k.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const d=t.conversationsByTabKey.get(e.params.tabKey);if(!d)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const p=((C=e.api.group.activePanel)==null?void 0:C.id)===e.api.id,u=e.api.isGroupActive,m=Vr(d,t.liveSessionInboxState,{isOpenConversation:p}),h=m.isReconnecting,g=m.isConnecting,S=m.isGenerating||c,f=m.isWaiting,x=m.unread,w=t.tabShortcuts[d.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${u?" is-group-active":""}${h?" is-reconnecting":""}`,title:wt(d),"data-tab-key":e.params.tabKey,onMouseDown:n,onTouchStart:n,onContextMenu:k=>{var y;k.preventDefault(),n(k),t.openTabContextMenu({x:k.clientX,y:k.clientY,tabKey:d.tabKey,sourceDocument:((y=k.target)==null?void 0:y.ownerDocument)??document})},children:[x&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:S?s.jsx("div",{className:"tab-spinner"}):f?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):h?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):g?s.jsx("div",{className:"tab-connecting-spinner"}):d.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:wt(d)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:h?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:dn(d)}):g?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:dn(d)}):s.jsx("span",{children:dn(d)})})]}),w&&s.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 sr(e){return e.isActive}function Md(e){return e.isVisible}function MN(e){e.preventDefault()}function DN({params:e,api:t}){var g;const n=oo(),a=l.useRef(null),[r,o]=l.useState(()=>sr(t)),[i,c]=l.useState(()=>Md(t)),d=n.conversationsByTabKey.get(e.tabKey),p=eo({sendDaemonCommand:n.sendDaemonCommand,activeConv:d,setActionLogs:n.setActionLogs,isStandalone:n.isStandalone});l.useEffect(()=>{o(sr(t)),c(Md(t));const S=[t.onDidActiveChange(f=>o(f.isActive)),t.onDidActiveGroupChange(f=>{if(!sr(t)&&!f.isActive){o(!1);return}o(sr(t))}),t.onDidVisibilityChange(f=>c(f.isVisible))];return()=>{for(const f of S)f.dispose()}},[t]);const u=l.useMemo(()=>d?n.ides.find(S=>S.id===d.routeId):void 0,[n.ides,d]),m=l.useMemo(()=>d?n.actionLogs.filter(S=>S.routeId===d.tabKey):[],[n.actionLogs,d]);if(!d)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(Ll,{conversationsCount:0,isSplitMode:!1,isStandalone:n.isStandalone,hasRegisteredMachines:n.hasRegisteredMachines,onOpenNewSession:n.onOpenNewSession,suppressGuide:n.hasDetachedConversationPanels,isLoading:!n.initialDataLoaded})});const h=!pt(d)&&Yn(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(Pl,{activeConv:d,clearToken:n.clearedTabs[d.tabKey]||0,isCliTerminal:h,ideEntry:u,terminalRef:a,handleModalButton:p.handleModalButton,handleRelaunch:p.handleRelaunch,handleSendChat:p.handleSendChat,handleForceSendChat:p.handleForceSendChat,isSendingChat:p.isSendingChat,handleFocusAgent:p.handleFocusAgent,isFocusingAgent:p.isFocusingAgent,actionLogs:m,userName:n.userName,scrollToBottomRequestNonce:((g=n.scrollToBottomRequest)==null?void 0:g.tabKey)===d.tabKey?n.scrollToBottomRequest.nonce:void 0,isInputActive:r,isVisible:i})})}function PN({visibleConversations:e,clearedTabs:t,ides:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d,userName:p,toggleHiddenTab:u,actionShortcuts:m,registerActionHandlers:h,onActiveTabChange:g,onOpenNewSession:S,onRequestScrollToBottom:f,requestedActiveTabKey:x,requestedRemoteIdeId:w,onRequestedActiveTabConsumed:b,scrollToBottomRequest:C,liveSessionInboxState:k,layoutProfile:y}){var lt,rt,bt;const{theme:v}=Xs(),{sendCommand:j}=kt(),N=l.useRef(null),A=l.useRef(null),T=l.useRef(null),P=l.useRef(!1),M=l.useRef(!1),D=l.useRef(!1),L=l.useRef(null),O=l.useRef([]),[E,I]=l.useState(null),[_,H]=l.useState(0),B=l.useRef(typeof window>"u"?{}:Vj(y)),$=l.useMemo(()=>new Map(e.map(Q=>[Q.tabKey,Q])),[e]),F=l.useMemo(()=>{const Q=N.current;return Q?Q.groups.some(te=>{try{const oe=te.model.location.type;return oe!=="floating"&&oe!=="popout"?!1:te.panels.some(xe=>$.has(xe.id))}catch{return!1}}):!1},[$,_,e]),W=l.useCallback(()=>{var Q;(Q=N.current)==null||Q.focus()},[]),Y=l.useCallback((Q,te)=>{f==null||f(Q,te)},[f]),V=l.useCallback(Q=>{const te=document,oe=Q.document;for(const Ie of te.querySelectorAll('link[rel="stylesheet"]')){const Ge=oe.createElement("link");Ge.rel="stylesheet",Ge.href=Ie.href,Ie.crossOrigin&&(Ge.crossOrigin=Ie.crossOrigin),oe.head.appendChild(Ge)}for(const Ie of te.querySelectorAll("style")){const Ge=oe.createElement("style");Ge.textContent=Ie.textContent,oe.head.appendChild(Ge)}const xe=[];for(const Ie of te.styleSheets)try{for(const Ge of Ie.cssRules)Ge instanceof CSSStyleRule&&(Ge.selectorText===":root"||Ge.selectorText==="html")&&xe.push(Ge.cssText)}catch{}if(xe.length>0){const Ie=oe.createElement("style");Ie.textContent=xe.join(`
71
71
  `),oe.head.appendChild(Ie)}const ae=te.documentElement.getAttribute("data-theme");ae&&oe.documentElement.setAttribute("data-theme",ae),oe.documentElement.style.colorScheme=ae==="light"?"light":"dark",oe.body.className=te.body.className;const Te=te.documentElement.getAttribute("style");Te&&oe.documentElement.setAttribute("style",Te);const Ee=oe.getElementById("dv-popout-window");Ee instanceof HTMLElement&&(Ee.classList.add("adhdev-dockview"),Go(Ee,v))},[v]),ee=l.useCallback(()=>{var te;const Q=N.current;if(Q)for(const oe of Q.groups)try{const xe=(te=oe.element)==null?void 0:te.ownerDocument;if(!xe||xe===document)continue;const ae=xe.getElementById("dv-popout-window");ae instanceof HTMLElement&&(ae.classList.add("adhdev-dockview"),Go(ae,v));const Te=document.documentElement.getAttribute("data-theme");Te&&xe.documentElement.setAttribute("data-theme",Te),xe.documentElement.style.colorScheme=Te==="light"?"light":"dark",xe.body.className=document.body.className;const Ee=document.documentElement.getAttribute("style");Ee?xe.documentElement.setAttribute("style",Ee):xe.documentElement.removeAttribute("style")}catch{}},[v]),le=l.useCallback(Q=>{const te=N.current;if(!te)return;const oe=te.getPanel(Q);oe&&te.addPopoutGroup(oe,{popoutUrl:"/popout.html",onDidOpen:({window:xe})=>{V(xe),ge();const ae=$.get(Q);xe.document.title=ae?`${wt(ae)} — ADHDev`:"ADHDev — Popout"}})},[$,V]),ie=l.useCallback(Q=>{const te=N.current,oe=te==null?void 0:te.getPanel(Q);if(!te||!oe)return;const xe=te.groups.filter(ae=>{var Te;try{return((Te=ae.element)==null?void 0:Te.ownerDocument)===document}catch{return!0}});xe.length>0?oe.api.moveTo({group:xe[0],position:"center"}):oe.api.moveTo({position:"center"}),oe.api.setActive()},[]),Z=l.useCallback(Q=>{var xe;const te=N.current;if(!te)return!1;const oe=te.getPanel(Q);if(!oe)return!1;try{return((xe=oe.group.element)==null?void 0:xe.ownerDocument)!==document}catch{return!1}},[]),U=l.useCallback(Q=>{Z(Q)&&ie(Q),u(Q)},[Z,ie,u]),J=l.useCallback(Q=>{const te=N.current,oe=te==null?void 0:te.getPanel(Q);!te||!oe||te.addFloatingGroup(oe,{width:600,height:500})},[]),R=l.useCallback(Q=>{var oe;const te=(oe=N.current)==null?void 0:oe.getPanel(Q);if(!te)return!1;try{return te.group.model.location.type==="floating"}catch{return!1}},[]),z=l.useCallback(()=>{var te,oe;const Q=(oe=(te=N.current)==null?void 0:te.activePanel)==null?void 0:oe.id;return!Q||ls(Q)?null:$.has(Q)?Q:null},[$]),ve=l.useCallback(Q=>{const te=N.current,oe=te==null?void 0:te.getPanel(Q);if(!te||!oe)return;const xe=te.groups.filter(ae=>{try{return ae.model.location.type==="grid"}catch{return!0}});xe.length>0?oe.api.moveTo({group:xe[0],position:"center"}):oe.api.moveTo({position:"center"}),oe.api.setActive()},[]),he=l.useCallback(()=>{var Te;const Q=N.current;if(!Q)return;const oe=Q.groups.filter(Ee=>{var Ie;try{return((Ie=Ee.element)==null?void 0:Ie.ownerDocument)===document&&Ee.model.location.type==="grid"}catch{return!1}})[0]||null,xe=[...Q.panels];for(const Ee of xe){const Ie=(Te=Ee.group.element)==null?void 0:Te.ownerDocument,Ge=Ee.group.model.location.type;Ie===document&&Ge==="grid"||(oe&&oe.id!==Ee.group.id?Ee.api.moveTo({group:oe,position:"center"}):Ee.api.moveTo({position:"center"}))}const ae=Q.activePanel;ae&&(ae.group.model.openPanel(ae),ae.api.setActive()),qo(document)},[]),ge=l.useCallback(()=>{var te,oe;const Q=N.current;if(Q)for(const xe of Q.groups){const ae=(te=xe.element)==null?void 0:te.ownerDocument;if(!ae||ae===document)continue;const Te=ae.getElementById("dv-popout-window");if(!(Te instanceof HTMLElement))continue;let Ee=null,Ie=ae.title||"ADHDev",Ge="Popout workspace";const ze=xe.activePanel;if(ze)if(Ee=ze.id,ls(ze.id)){const We=((oe=ze.params)==null?void 0:oe.routeId)||ze.id.slice(7),ue=hs([...$.values()],We);Ie=em(ue),Ge=ue!=null&&ue.machineName?`Remote view · ${ue.machineName}`:"Remote view"}else{const We=$.get(ze.id);Ie=We?wt(We):ze.title||ze.id,Ge=We?dn(We):"Dockview panel"}ae.title=`${Ie} — ADHDev`;const Je=Array.from(ae.querySelectorAll("#adhdev-popout-header"));for(const We of Je)We.remove();const Ue=ae.createElement("div");Ue.id="adhdev-popout-header",ae.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=`
72
72
  <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">